babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708
  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._onCanvasPointerOut);
  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._bindedRenderFunction = null;
  14970. this.onResizeObservable.clear();
  14971. this.onCanvasBlurObservable.clear();
  14972. this.onCanvasFocusObservable.clear();
  14973. this.onCanvasPointerOutObservable.clear();
  14974. this.onBeginFrameObservable.clear();
  14975. this.onEndFrameObservable.clear();
  14976. BABYLON.Effect.ResetCache();
  14977. // Abort active requests
  14978. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14979. var request = _a[_i];
  14980. request.abort();
  14981. }
  14982. };
  14983. // Loading screen
  14984. Engine.prototype.displayLoadingUI = function () {
  14985. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14986. return;
  14987. }
  14988. var loadingScreen = this.loadingScreen;
  14989. if (loadingScreen) {
  14990. loadingScreen.displayLoadingUI();
  14991. }
  14992. };
  14993. Engine.prototype.hideLoadingUI = function () {
  14994. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14995. return;
  14996. }
  14997. var loadingScreen = this.loadingScreen;
  14998. if (loadingScreen) {
  14999. loadingScreen.hideLoadingUI();
  15000. }
  15001. };
  15002. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15003. get: function () {
  15004. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15005. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15006. return this._loadingScreen;
  15007. },
  15008. set: function (loadingScreen) {
  15009. this._loadingScreen = loadingScreen;
  15010. },
  15011. enumerable: true,
  15012. configurable: true
  15013. });
  15014. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15015. set: function (text) {
  15016. this.loadingScreen.loadingUIText = text;
  15017. },
  15018. enumerable: true,
  15019. configurable: true
  15020. });
  15021. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15022. set: function (color) {
  15023. this.loadingScreen.loadingUIBackgroundColor = color;
  15024. },
  15025. enumerable: true,
  15026. configurable: true
  15027. });
  15028. Engine.prototype.attachContextLostEvent = function (callback) {
  15029. if (this._renderingCanvas) {
  15030. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15031. }
  15032. };
  15033. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15034. if (this._renderingCanvas) {
  15035. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15036. }
  15037. };
  15038. Engine.prototype.getVertexShaderSource = function (program) {
  15039. var shaders = this._gl.getAttachedShaders(program);
  15040. if (!shaders) {
  15041. return null;
  15042. }
  15043. return this._gl.getShaderSource(shaders[0]);
  15044. };
  15045. Engine.prototype.getFragmentShaderSource = function (program) {
  15046. var shaders = this._gl.getAttachedShaders(program);
  15047. if (!shaders) {
  15048. return null;
  15049. }
  15050. return this._gl.getShaderSource(shaders[1]);
  15051. };
  15052. Engine.prototype.getError = function () {
  15053. return this._gl.getError();
  15054. };
  15055. // FPS
  15056. Engine.prototype.getFps = function () {
  15057. return this._fps;
  15058. };
  15059. Engine.prototype.getDeltaTime = function () {
  15060. return this._deltaTime;
  15061. };
  15062. Engine.prototype._measureFps = function () {
  15063. this._performanceMonitor.sampleFrame();
  15064. this._fps = this._performanceMonitor.averageFPS;
  15065. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15066. };
  15067. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15068. if (faceIndex === void 0) { faceIndex = -1; }
  15069. var gl = this._gl;
  15070. if (!this._dummyFramebuffer) {
  15071. var dummy = gl.createFramebuffer();
  15072. if (!dummy) {
  15073. throw new Error("Unable to create dummy framebuffer");
  15074. }
  15075. this._dummyFramebuffer = dummy;
  15076. }
  15077. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15078. if (faceIndex > -1) {
  15079. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15080. }
  15081. else {
  15082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15083. }
  15084. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15085. var buffer;
  15086. switch (readType) {
  15087. case gl.UNSIGNED_BYTE:
  15088. buffer = new Uint8Array(4 * width * height);
  15089. readType = gl.UNSIGNED_BYTE;
  15090. break;
  15091. default:
  15092. buffer = new Float32Array(4 * width * height);
  15093. readType = gl.FLOAT;
  15094. break;
  15095. }
  15096. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15097. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15098. return buffer;
  15099. };
  15100. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15101. if (this._webGLVersion > 1) {
  15102. return this._caps.colorBufferFloat;
  15103. }
  15104. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15105. };
  15106. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15107. if (this._webGLVersion > 1) {
  15108. return this._caps.colorBufferFloat;
  15109. }
  15110. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15111. };
  15112. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15113. Engine.prototype._canRenderToFramebuffer = function (type) {
  15114. var gl = this._gl;
  15115. //clear existing errors
  15116. while (gl.getError() !== gl.NO_ERROR) { }
  15117. var successful = true;
  15118. var texture = gl.createTexture();
  15119. gl.bindTexture(gl.TEXTURE_2D, texture);
  15120. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15123. var fb = gl.createFramebuffer();
  15124. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15126. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15127. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15128. successful = successful && (gl.getError() === gl.NO_ERROR);
  15129. //try render by clearing frame buffer's color buffer
  15130. if (successful) {
  15131. gl.clear(gl.COLOR_BUFFER_BIT);
  15132. successful = successful && (gl.getError() === gl.NO_ERROR);
  15133. }
  15134. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15135. if (successful) {
  15136. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15137. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15138. var readFormat = gl.RGBA;
  15139. var readType = gl.UNSIGNED_BYTE;
  15140. var buffer = new Uint8Array(4);
  15141. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15142. successful = successful && (gl.getError() === gl.NO_ERROR);
  15143. }
  15144. //clean up
  15145. gl.deleteTexture(texture);
  15146. gl.deleteFramebuffer(fb);
  15147. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15148. //clear accumulated errors
  15149. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15150. return successful;
  15151. };
  15152. Engine.prototype._getWebGLTextureType = function (type) {
  15153. if (type === Engine.TEXTURETYPE_FLOAT) {
  15154. return this._gl.FLOAT;
  15155. }
  15156. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15157. // Add Half Float Constant.
  15158. return this._gl.HALF_FLOAT_OES;
  15159. }
  15160. return this._gl.UNSIGNED_BYTE;
  15161. };
  15162. ;
  15163. /** @ignore */
  15164. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15165. if (this._webGLVersion === 1) {
  15166. return this._gl.RGBA;
  15167. }
  15168. if (type === Engine.TEXTURETYPE_FLOAT) {
  15169. if (format) {
  15170. switch (format) {
  15171. case Engine.TEXTUREFORMAT_R32F:
  15172. return this._gl.R32F;
  15173. case Engine.TEXTUREFORMAT_RG32F:
  15174. return this._gl.RG32F;
  15175. case Engine.TEXTUREFORMAT_RGB32F:
  15176. return this._gl.RGB32F;
  15177. }
  15178. }
  15179. return this._gl.RGBA32F;
  15180. }
  15181. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15182. return this._gl.RGBA16F;
  15183. }
  15184. return this._gl.RGBA;
  15185. };
  15186. ;
  15187. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15188. if (type === Engine.TEXTURETYPE_FLOAT) {
  15189. return this._gl.RGBA32F;
  15190. }
  15191. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15192. return this._gl.RGBA16F;
  15193. }
  15194. return this._gl.RGBA8;
  15195. };
  15196. ;
  15197. Engine.prototype.createQuery = function () {
  15198. return this._gl.createQuery();
  15199. };
  15200. Engine.prototype.deleteQuery = function (query) {
  15201. this._gl.deleteQuery(query);
  15202. return this;
  15203. };
  15204. Engine.prototype.isQueryResultAvailable = function (query) {
  15205. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15206. };
  15207. Engine.prototype.getQueryResult = function (query) {
  15208. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15209. };
  15210. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15211. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15212. this._gl.beginQuery(glAlgorithm, query);
  15213. return this;
  15214. };
  15215. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15216. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15217. this._gl.endQuery(glAlgorithm);
  15218. return this;
  15219. };
  15220. /* Time queries */
  15221. Engine.prototype._createTimeQuery = function () {
  15222. var timerQuery = this._caps.timerQuery;
  15223. if (timerQuery.createQueryEXT) {
  15224. return timerQuery.createQueryEXT();
  15225. }
  15226. return this.createQuery();
  15227. };
  15228. Engine.prototype._deleteTimeQuery = function (query) {
  15229. var timerQuery = this._caps.timerQuery;
  15230. if (timerQuery.deleteQueryEXT) {
  15231. timerQuery.deleteQueryEXT(query);
  15232. return;
  15233. }
  15234. this.deleteQuery(query);
  15235. };
  15236. Engine.prototype._getTimeQueryResult = function (query) {
  15237. var timerQuery = this._caps.timerQuery;
  15238. if (timerQuery.getQueryObjectEXT) {
  15239. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15240. }
  15241. return this.getQueryResult(query);
  15242. };
  15243. Engine.prototype._getTimeQueryAvailability = function (query) {
  15244. var timerQuery = this._caps.timerQuery;
  15245. if (timerQuery.getQueryObjectEXT) {
  15246. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15247. }
  15248. return this.isQueryResultAvailable(query);
  15249. };
  15250. Engine.prototype.startTimeQuery = function () {
  15251. var timerQuery = this._caps.timerQuery;
  15252. if (!timerQuery) {
  15253. return null;
  15254. }
  15255. var token = new BABYLON._TimeToken();
  15256. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15257. if (this._caps.canUseTimestampForTimerQuery) {
  15258. token._startTimeQuery = this._createTimeQuery();
  15259. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15260. }
  15261. else {
  15262. if (this._currentNonTimestampToken) {
  15263. return this._currentNonTimestampToken;
  15264. }
  15265. token._timeElapsedQuery = this._createTimeQuery();
  15266. if (timerQuery.beginQueryEXT) {
  15267. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15268. }
  15269. else {
  15270. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15271. }
  15272. this._currentNonTimestampToken = token;
  15273. }
  15274. return token;
  15275. };
  15276. Engine.prototype.endTimeQuery = function (token) {
  15277. var timerQuery = this._caps.timerQuery;
  15278. if (!timerQuery || !token) {
  15279. return -1;
  15280. }
  15281. if (this._caps.canUseTimestampForTimerQuery) {
  15282. if (!token._startTimeQuery) {
  15283. return -1;
  15284. }
  15285. if (!token._endTimeQuery) {
  15286. token._endTimeQuery = this._createTimeQuery();
  15287. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15288. }
  15289. }
  15290. else if (!token._timeElapsedQueryEnded) {
  15291. if (!token._timeElapsedQuery) {
  15292. return -1;
  15293. }
  15294. if (timerQuery.endQueryEXT) {
  15295. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15296. }
  15297. else {
  15298. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15299. }
  15300. token._timeElapsedQueryEnded = true;
  15301. }
  15302. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15303. var available = false;
  15304. if (token._endTimeQuery) {
  15305. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15306. }
  15307. else if (token._timeElapsedQuery) {
  15308. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15309. }
  15310. if (available && !disjoint) {
  15311. var result = 0;
  15312. if (this._caps.canUseTimestampForTimerQuery) {
  15313. if (!token._startTimeQuery || !token._endTimeQuery) {
  15314. return -1;
  15315. }
  15316. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15317. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15318. result = timeEnd - timeStart;
  15319. this._deleteTimeQuery(token._startTimeQuery);
  15320. this._deleteTimeQuery(token._endTimeQuery);
  15321. token._startTimeQuery = null;
  15322. token._endTimeQuery = null;
  15323. }
  15324. else {
  15325. if (!token._timeElapsedQuery) {
  15326. return -1;
  15327. }
  15328. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15329. this._deleteTimeQuery(token._timeElapsedQuery);
  15330. token._timeElapsedQuery = null;
  15331. token._timeElapsedQueryEnded = false;
  15332. this._currentNonTimestampToken = null;
  15333. }
  15334. return result;
  15335. }
  15336. return -1;
  15337. };
  15338. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15339. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15340. };
  15341. // Transform feedback
  15342. Engine.prototype.createTransformFeedback = function () {
  15343. return this._gl.createTransformFeedback();
  15344. };
  15345. Engine.prototype.deleteTransformFeedback = function (value) {
  15346. this._gl.deleteTransformFeedback(value);
  15347. };
  15348. Engine.prototype.bindTransformFeedback = function (value) {
  15349. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15350. };
  15351. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15352. if (usePoints === void 0) { usePoints = true; }
  15353. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15354. };
  15355. Engine.prototype.endTransformFeedback = function () {
  15356. this._gl.endTransformFeedback();
  15357. };
  15358. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15359. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15360. };
  15361. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15362. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15363. };
  15364. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15365. var _this = this;
  15366. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15367. this._activeRequests.push(request);
  15368. request.onCompleteObservable.add(function (request) {
  15369. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15370. });
  15371. return request;
  15372. };
  15373. /** @ignore */
  15374. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15375. var _this = this;
  15376. return new Promise(function (resolve, reject) {
  15377. _this._loadFile(url, function (data) {
  15378. resolve(data);
  15379. }, undefined, database, useArrayBuffer, function (request, exception) {
  15380. reject(exception);
  15381. });
  15382. });
  15383. };
  15384. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15385. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15386. var onload = function (data) {
  15387. loadedFiles[index] = data;
  15388. loadedFiles._internalCount++;
  15389. if (loadedFiles._internalCount === 6) {
  15390. onfinish(loadedFiles);
  15391. }
  15392. };
  15393. var onerror = function (request, exception) {
  15394. if (onErrorCallBack && request) {
  15395. onErrorCallBack(request.status + " " + request.statusText, exception);
  15396. }
  15397. };
  15398. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15399. };
  15400. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15401. if (onError === void 0) { onError = null; }
  15402. var loadedFiles = [];
  15403. loadedFiles._internalCount = 0;
  15404. for (var index = 0; index < 6; index++) {
  15405. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15406. }
  15407. };
  15408. // Statics
  15409. Engine.isSupported = function () {
  15410. try {
  15411. var tempcanvas = document.createElement("canvas");
  15412. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15413. return gl != null && !!window.WebGLRenderingContext;
  15414. }
  15415. catch (e) {
  15416. return false;
  15417. }
  15418. };
  15419. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15420. Engine.ExceptionList = [
  15421. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15422. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15423. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15424. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15425. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15426. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15427. ];
  15428. Engine.Instances = new Array();
  15429. // Const statics
  15430. Engine._ALPHA_DISABLE = 0;
  15431. Engine._ALPHA_ADD = 1;
  15432. Engine._ALPHA_COMBINE = 2;
  15433. Engine._ALPHA_SUBTRACT = 3;
  15434. Engine._ALPHA_MULTIPLY = 4;
  15435. Engine._ALPHA_MAXIMIZED = 5;
  15436. Engine._ALPHA_ONEONE = 6;
  15437. Engine._ALPHA_PREMULTIPLIED = 7;
  15438. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15439. Engine._ALPHA_INTERPOLATE = 9;
  15440. Engine._ALPHA_SCREENMODE = 10;
  15441. Engine._DELAYLOADSTATE_NONE = 0;
  15442. Engine._DELAYLOADSTATE_LOADED = 1;
  15443. Engine._DELAYLOADSTATE_LOADING = 2;
  15444. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15445. Engine._TEXTUREFORMAT_ALPHA = 0;
  15446. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15447. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15448. Engine._TEXTUREFORMAT_RGB = 4;
  15449. Engine._TEXTUREFORMAT_RGBA = 5;
  15450. Engine._TEXTUREFORMAT_R32F = 6;
  15451. Engine._TEXTUREFORMAT_RG32F = 7;
  15452. Engine._TEXTUREFORMAT_RGB32F = 8;
  15453. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15454. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15455. Engine._TEXTURETYPE_FLOAT = 1;
  15456. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15457. // Depht or Stencil test Constants.
  15458. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15459. 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.
  15460. 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.
  15461. 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.
  15462. 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.
  15463. 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.
  15464. 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.
  15465. 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.
  15466. // Stencil Actions Constants.
  15467. Engine._KEEP = 0x1E00;
  15468. Engine._REPLACE = 0x1E01;
  15469. Engine._INCR = 0x1E02;
  15470. Engine._DECR = 0x1E03;
  15471. Engine._INVERT = 0x150A;
  15472. Engine._INCR_WRAP = 0x8507;
  15473. Engine._DECR_WRAP = 0x8508;
  15474. // Texture rescaling mode
  15475. Engine._SCALEMODE_FLOOR = 1;
  15476. Engine._SCALEMODE_NEAREST = 2;
  15477. Engine._SCALEMODE_CEILING = 3;
  15478. // Updatable statics so stick with vars here
  15479. Engine.CollisionsEpsilon = 0.001;
  15480. Engine.CodeRepository = "src/";
  15481. Engine.ShadersRepository = "src/Shaders/";
  15482. return Engine;
  15483. }());
  15484. BABYLON.Engine = Engine;
  15485. })(BABYLON || (BABYLON = {}));
  15486. //# sourceMappingURL=babylon.engine.js.map
  15487. var BABYLON;
  15488. (function (BABYLON) {
  15489. /**
  15490. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15491. */
  15492. var Node = /** @class */ (function () {
  15493. /**
  15494. * Creates a new Node
  15495. * @param {string} name - the name and id to be given to this node
  15496. * @param {BABYLON.Scene} the scene this node will be added to
  15497. */
  15498. function Node(name, scene) {
  15499. if (scene === void 0) { scene = null; }
  15500. /**
  15501. * Gets or sets a string used to store user defined state for the node
  15502. */
  15503. this.state = "";
  15504. /**
  15505. * Gets or sets an object used to store user defined information for the node
  15506. */
  15507. this.metadata = null;
  15508. /**
  15509. * Gets or sets a boolean used to define if the node must be serialized
  15510. */
  15511. this.doNotSerialize = false;
  15512. /** @ignore */
  15513. this._isDisposed = false;
  15514. /**
  15515. * Gets a list of {BABYLON.Animation} associated with the node
  15516. */
  15517. this.animations = new Array();
  15518. this._ranges = {};
  15519. this._isEnabled = true;
  15520. this._isReady = true;
  15521. /** @ignore */
  15522. this._currentRenderId = -1;
  15523. this._parentRenderId = -1;
  15524. this._animationPropertiesOverride = null;
  15525. /**
  15526. * An event triggered when the mesh is disposed
  15527. * @type {BABYLON.Observable}
  15528. */
  15529. this.onDisposeObservable = new BABYLON.Observable();
  15530. // Behaviors
  15531. this._behaviors = new Array();
  15532. this.name = name;
  15533. this.id = name;
  15534. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15535. this.uniqueId = this._scene.getUniqueId();
  15536. this._initCache();
  15537. }
  15538. /**
  15539. * Gets a boolean indicating if the node has been disposed
  15540. * @returns true if the node was disposed
  15541. */
  15542. Node.prototype.isDisposed = function () {
  15543. return this._isDisposed;
  15544. };
  15545. Object.defineProperty(Node.prototype, "parent", {
  15546. get: function () {
  15547. return this._parentNode;
  15548. },
  15549. /**
  15550. * Gets or sets the parent of the node
  15551. */
  15552. set: function (parent) {
  15553. if (this._parentNode === parent) {
  15554. return;
  15555. }
  15556. // Remove self from list of children of parent
  15557. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15558. var index = this._parentNode._children.indexOf(this);
  15559. if (index !== -1) {
  15560. this._parentNode._children.splice(index, 1);
  15561. }
  15562. }
  15563. // Store new parent
  15564. this._parentNode = parent;
  15565. // Add as child to new parent
  15566. if (this._parentNode) {
  15567. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15568. this._parentNode._children = new Array();
  15569. }
  15570. this._parentNode._children.push(this);
  15571. }
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15577. /**
  15578. * Gets or sets the animation properties override
  15579. */
  15580. get: function () {
  15581. return this._animationPropertiesOverride;
  15582. },
  15583. set: function (value) {
  15584. this._animationPropertiesOverride = value;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. /**
  15590. * Gets a string idenfifying the name of the class
  15591. * @returns "Node" string
  15592. */
  15593. Node.prototype.getClassName = function () {
  15594. return "Node";
  15595. };
  15596. Object.defineProperty(Node.prototype, "onDispose", {
  15597. /**
  15598. * Sets a callback that will be raised when the node will be disposed
  15599. */
  15600. set: function (callback) {
  15601. if (this._onDisposeObserver) {
  15602. this.onDisposeObservable.remove(this._onDisposeObserver);
  15603. }
  15604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15605. },
  15606. enumerable: true,
  15607. configurable: true
  15608. });
  15609. /**
  15610. * Gets the scene of the node
  15611. * @returns a {BABYLON.Scene}
  15612. */
  15613. Node.prototype.getScene = function () {
  15614. return this._scene;
  15615. };
  15616. /**
  15617. * Gets the engine of the node
  15618. * @returns a {BABYLON.Engine}
  15619. */
  15620. Node.prototype.getEngine = function () {
  15621. return this._scene.getEngine();
  15622. };
  15623. /**
  15624. * Attach a behavior to the node
  15625. * @see http://doc.babylonjs.com/features/behaviour
  15626. * @param behavior defines the behavior to attach
  15627. * @returns the current Node
  15628. */
  15629. Node.prototype.addBehavior = function (behavior) {
  15630. var _this = this;
  15631. var index = this._behaviors.indexOf(behavior);
  15632. if (index !== -1) {
  15633. return this;
  15634. }
  15635. behavior.init();
  15636. if (this._scene.isLoading) {
  15637. // We defer the attach when the scene will be loaded
  15638. var observer = this._scene.onDataLoadedObservable.add(function () {
  15639. behavior.attach(_this);
  15640. setTimeout(function () {
  15641. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15642. _this._scene.onDataLoadedObservable.remove(observer);
  15643. }, 0);
  15644. });
  15645. }
  15646. else {
  15647. behavior.attach(this);
  15648. }
  15649. this._behaviors.push(behavior);
  15650. return this;
  15651. };
  15652. /**
  15653. * Remove an attached behavior
  15654. * @see http://doc.babylonjs.com/features/behaviour
  15655. * @param behavior defines the behavior to attach
  15656. * @returns the current Node
  15657. */
  15658. Node.prototype.removeBehavior = function (behavior) {
  15659. var index = this._behaviors.indexOf(behavior);
  15660. if (index === -1) {
  15661. return this;
  15662. }
  15663. this._behaviors[index].detach();
  15664. this._behaviors.splice(index, 1);
  15665. return this;
  15666. };
  15667. Object.defineProperty(Node.prototype, "behaviors", {
  15668. /**
  15669. * Gets the list of attached behaviors
  15670. * @see http://doc.babylonjs.com/features/behaviour
  15671. */
  15672. get: function () {
  15673. return this._behaviors;
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. /**
  15679. * Gets an attached behavior by name
  15680. * @param name defines the name of the behavior to look for
  15681. * @see http://doc.babylonjs.com/features/behaviour
  15682. * @returns null if behavior was not found else the requested behavior
  15683. */
  15684. Node.prototype.getBehaviorByName = function (name) {
  15685. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15686. var behavior = _a[_i];
  15687. if (behavior.name === name) {
  15688. return behavior;
  15689. }
  15690. }
  15691. return null;
  15692. };
  15693. /**
  15694. * Returns the world matrix of the node
  15695. * @returns a matrix containing the node's world matrix
  15696. */
  15697. Node.prototype.getWorldMatrix = function () {
  15698. return BABYLON.Matrix.Identity();
  15699. };
  15700. // override it in derived class if you add new variables to the cache
  15701. // and call the parent class method
  15702. /** @ignore */
  15703. Node.prototype._initCache = function () {
  15704. this._cache = {};
  15705. this._cache.parent = undefined;
  15706. };
  15707. /** @ignore */
  15708. Node.prototype.updateCache = function (force) {
  15709. if (!force && this.isSynchronized())
  15710. return;
  15711. this._cache.parent = this.parent;
  15712. this._updateCache();
  15713. };
  15714. // override it in derived class if you add new variables to the cache
  15715. // and call the parent class method if !ignoreParentClass
  15716. /** @ignore */
  15717. Node.prototype._updateCache = function (ignoreParentClass) {
  15718. };
  15719. // override it in derived class if you add new variables to the cache
  15720. /** @ignore */
  15721. Node.prototype._isSynchronized = function () {
  15722. return true;
  15723. };
  15724. /** @ignore */
  15725. Node.prototype._markSyncedWithParent = function () {
  15726. if (this.parent) {
  15727. this._parentRenderId = this.parent._currentRenderId;
  15728. }
  15729. };
  15730. /** @ignore */
  15731. Node.prototype.isSynchronizedWithParent = function () {
  15732. if (!this.parent) {
  15733. return true;
  15734. }
  15735. if (this._parentRenderId !== this.parent._currentRenderId) {
  15736. return false;
  15737. }
  15738. return this.parent.isSynchronized();
  15739. };
  15740. /** @ignore */
  15741. Node.prototype.isSynchronized = function (updateCache) {
  15742. var check = this.hasNewParent();
  15743. check = check || !this.isSynchronizedWithParent();
  15744. check = check || !this._isSynchronized();
  15745. if (updateCache)
  15746. this.updateCache(true);
  15747. return !check;
  15748. };
  15749. /** @ignore */
  15750. Node.prototype.hasNewParent = function (update) {
  15751. if (this._cache.parent === this.parent)
  15752. return false;
  15753. if (update)
  15754. this._cache.parent = this.parent;
  15755. return true;
  15756. };
  15757. /**
  15758. * Is this node ready to be used/rendered
  15759. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15760. * @return true if the node is ready
  15761. */
  15762. Node.prototype.isReady = function (completeCheck) {
  15763. if (completeCheck === void 0) { completeCheck = false; }
  15764. return this._isReady;
  15765. };
  15766. /**
  15767. * Is this node enabled?
  15768. * 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
  15769. * @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
  15770. * @return whether this node (and its parent) is enabled
  15771. * @see setEnabled
  15772. */
  15773. Node.prototype.isEnabled = function (checkAncestors) {
  15774. if (checkAncestors === void 0) { checkAncestors = true; }
  15775. if (checkAncestors === false) {
  15776. return this._isEnabled;
  15777. }
  15778. if (this._isEnabled === false) {
  15779. return false;
  15780. }
  15781. if (this.parent !== undefined && this.parent !== null) {
  15782. return this.parent.isEnabled(checkAncestors);
  15783. }
  15784. return true;
  15785. };
  15786. /**
  15787. * Set the enabled state of this node
  15788. * @param value defines the new enabled state
  15789. * @see isEnabled
  15790. */
  15791. Node.prototype.setEnabled = function (value) {
  15792. this._isEnabled = value;
  15793. };
  15794. /**
  15795. * Is this node a descendant of the given node?
  15796. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15797. * @param ancestor defines the parent node to inspect
  15798. * @see parent
  15799. * @returns a boolean indicating if this node is a descendant of the given node
  15800. */
  15801. Node.prototype.isDescendantOf = function (ancestor) {
  15802. if (this.parent) {
  15803. if (this.parent === ancestor) {
  15804. return true;
  15805. }
  15806. return this.parent.isDescendantOf(ancestor);
  15807. }
  15808. return false;
  15809. };
  15810. /** @ignore */
  15811. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15812. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15813. if (!this._children) {
  15814. return;
  15815. }
  15816. for (var index = 0; index < this._children.length; index++) {
  15817. var item = this._children[index];
  15818. if (!predicate || predicate(item)) {
  15819. results.push(item);
  15820. }
  15821. if (!directDescendantsOnly) {
  15822. item._getDescendants(results, false, predicate);
  15823. }
  15824. }
  15825. };
  15826. /**
  15827. * Will return all nodes that have this node as ascendant
  15828. * @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
  15829. * @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
  15830. * @return all children nodes of all types
  15831. */
  15832. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15833. var results = new Array();
  15834. this._getDescendants(results, directDescendantsOnly, predicate);
  15835. return results;
  15836. };
  15837. /**
  15838. * Get all child-meshes of this node
  15839. * @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
  15840. * @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
  15841. * @returns an array of {BABYLON.AbstractMesh}
  15842. */
  15843. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15844. var results = [];
  15845. this._getDescendants(results, directDescendantsOnly, function (node) {
  15846. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15847. });
  15848. return results;
  15849. };
  15850. /**
  15851. * Get all child-transformNodes of this node
  15852. * @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
  15853. * @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
  15854. * @returns an array of {BABYLON.TransformNode}
  15855. */
  15856. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15857. var results = [];
  15858. this._getDescendants(results, directDescendantsOnly, function (node) {
  15859. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15860. });
  15861. return results;
  15862. };
  15863. /**
  15864. * Get all direct children of this node
  15865. * @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
  15866. * @returns an array of {BABYLON.Node}
  15867. */
  15868. Node.prototype.getChildren = function (predicate) {
  15869. return this.getDescendants(true, predicate);
  15870. };
  15871. /** @ignore */
  15872. Node.prototype._setReady = function (state) {
  15873. if (state === this._isReady) {
  15874. return;
  15875. }
  15876. if (!state) {
  15877. this._isReady = false;
  15878. return;
  15879. }
  15880. this._isReady = true;
  15881. if (this.onReady) {
  15882. this.onReady(this);
  15883. }
  15884. };
  15885. /**
  15886. * Get an animation by name
  15887. * @param name defines the name of the animation to look for
  15888. * @returns null if not found else the requested animation
  15889. */
  15890. Node.prototype.getAnimationByName = function (name) {
  15891. for (var i = 0; i < this.animations.length; i++) {
  15892. var animation = this.animations[i];
  15893. if (animation.name === name) {
  15894. return animation;
  15895. }
  15896. }
  15897. return null;
  15898. };
  15899. /**
  15900. * Creates an animation range for this node
  15901. * @param name defines the name of the range
  15902. * @param from defines the starting key
  15903. * @param to defines the end key
  15904. */
  15905. Node.prototype.createAnimationRange = function (name, from, to) {
  15906. // check name not already in use
  15907. if (!this._ranges[name]) {
  15908. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15909. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15910. if (this.animations[i]) {
  15911. this.animations[i].createRange(name, from, to);
  15912. }
  15913. }
  15914. }
  15915. };
  15916. /**
  15917. * Delete a specific animation range
  15918. * @param name defines the name of the range to delete
  15919. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15920. */
  15921. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15922. if (deleteFrames === void 0) { deleteFrames = true; }
  15923. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15924. if (this.animations[i]) {
  15925. this.animations[i].deleteRange(name, deleteFrames);
  15926. }
  15927. }
  15928. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15929. };
  15930. /**
  15931. * Get an animation range by name
  15932. * @param name defines the name of the animation range to look for
  15933. * @returns null if not found else the requested animation range
  15934. */
  15935. Node.prototype.getAnimationRange = function (name) {
  15936. return this._ranges[name];
  15937. };
  15938. /**
  15939. * Will start the animation sequence
  15940. * @param name defines the range frames for animation sequence
  15941. * @param loop defines if the animation should loop (false by default)
  15942. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15943. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15944. * @returns the object created for this animation. If range does not exist, it will return null
  15945. */
  15946. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15947. var range = this.getAnimationRange(name);
  15948. if (!range) {
  15949. return null;
  15950. }
  15951. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15952. };
  15953. /**
  15954. * Serialize animation ranges into a JSON compatible object
  15955. * @returns serialization object
  15956. */
  15957. Node.prototype.serializeAnimationRanges = function () {
  15958. var serializationRanges = [];
  15959. for (var name in this._ranges) {
  15960. var localRange = this._ranges[name];
  15961. if (!localRange) {
  15962. continue;
  15963. }
  15964. var range = {};
  15965. range.name = name;
  15966. range.from = localRange.from;
  15967. range.to = localRange.to;
  15968. serializationRanges.push(range);
  15969. }
  15970. return serializationRanges;
  15971. };
  15972. /**
  15973. * Computes the world matrix of the node
  15974. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15975. * @returns the world matrix
  15976. */
  15977. Node.prototype.computeWorldMatrix = function (force) {
  15978. return BABYLON.Matrix.Identity();
  15979. };
  15980. /**
  15981. * Releases resources associated with this node.
  15982. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15983. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15984. */
  15985. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15986. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15987. if (!doNotRecurse) {
  15988. var nodes = this.getDescendants(true);
  15989. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15990. var node = nodes_1[_i];
  15991. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15992. }
  15993. }
  15994. else {
  15995. var transformNodes = this.getChildTransformNodes(true);
  15996. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15997. var transformNode = transformNodes_1[_a];
  15998. transformNode.parent = null;
  15999. transformNode.computeWorldMatrix(true);
  16000. }
  16001. }
  16002. this.parent = null;
  16003. // Callback
  16004. this.onDisposeObservable.notifyObservers(this);
  16005. this.onDisposeObservable.clear();
  16006. // Behaviors
  16007. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16008. var behavior = _c[_b];
  16009. behavior.detach();
  16010. }
  16011. this._behaviors = [];
  16012. this._isDisposed = true;
  16013. };
  16014. /**
  16015. * Parse animation range data from a serialization object and store them into a given node
  16016. * @param node defines where to store the animation ranges
  16017. * @param parsedNode defines the serialization object to read data from
  16018. * @param scene defines the hosting scene
  16019. */
  16020. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16021. if (parsedNode.ranges) {
  16022. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16023. var data = parsedNode.ranges[index];
  16024. node.createAnimationRange(data.name, data.from, data.to);
  16025. }
  16026. }
  16027. };
  16028. __decorate([
  16029. BABYLON.serialize()
  16030. ], Node.prototype, "name", void 0);
  16031. __decorate([
  16032. BABYLON.serialize()
  16033. ], Node.prototype, "id", void 0);
  16034. __decorate([
  16035. BABYLON.serialize()
  16036. ], Node.prototype, "uniqueId", void 0);
  16037. __decorate([
  16038. BABYLON.serialize()
  16039. ], Node.prototype, "state", void 0);
  16040. __decorate([
  16041. BABYLON.serialize()
  16042. ], Node.prototype, "metadata", void 0);
  16043. return Node;
  16044. }());
  16045. BABYLON.Node = Node;
  16046. })(BABYLON || (BABYLON = {}));
  16047. //# sourceMappingURL=babylon.node.js.map
  16048. var BABYLON;
  16049. (function (BABYLON) {
  16050. var BoundingSphere = /** @class */ (function () {
  16051. function BoundingSphere(minimum, maximum) {
  16052. this.minimum = minimum;
  16053. this.maximum = maximum;
  16054. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16055. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16056. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16057. this.radius = distance * 0.5;
  16058. this.centerWorld = BABYLON.Vector3.Zero();
  16059. this._update(BABYLON.Matrix.Identity());
  16060. }
  16061. // Methods
  16062. BoundingSphere.prototype._update = function (world) {
  16063. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16064. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16065. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16066. };
  16067. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16068. for (var i = 0; i < 6; i++) {
  16069. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16070. return false;
  16071. }
  16072. return true;
  16073. };
  16074. BoundingSphere.prototype.intersectsPoint = function (point) {
  16075. var x = this.centerWorld.x - point.x;
  16076. var y = this.centerWorld.y - point.y;
  16077. var z = this.centerWorld.z - point.z;
  16078. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16079. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16080. return false;
  16081. return true;
  16082. };
  16083. // Statics
  16084. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16085. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16086. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16087. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16088. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16089. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16090. return false;
  16091. return true;
  16092. };
  16093. return BoundingSphere;
  16094. }());
  16095. BABYLON.BoundingSphere = BoundingSphere;
  16096. })(BABYLON || (BABYLON = {}));
  16097. //# sourceMappingURL=babylon.boundingSphere.js.map
  16098. var BABYLON;
  16099. (function (BABYLON) {
  16100. var BoundingBox = /** @class */ (function () {
  16101. function BoundingBox(minimum, maximum) {
  16102. this.minimum = minimum;
  16103. this.maximum = maximum;
  16104. this.vectors = new Array();
  16105. this.vectorsWorld = new Array();
  16106. // Bounding vectors
  16107. this.vectors.push(this.minimum.clone());
  16108. this.vectors.push(this.maximum.clone());
  16109. this.vectors.push(this.minimum.clone());
  16110. this.vectors[2].x = this.maximum.x;
  16111. this.vectors.push(this.minimum.clone());
  16112. this.vectors[3].y = this.maximum.y;
  16113. this.vectors.push(this.minimum.clone());
  16114. this.vectors[4].z = this.maximum.z;
  16115. this.vectors.push(this.maximum.clone());
  16116. this.vectors[5].z = this.minimum.z;
  16117. this.vectors.push(this.maximum.clone());
  16118. this.vectors[6].x = this.minimum.x;
  16119. this.vectors.push(this.maximum.clone());
  16120. this.vectors[7].y = this.minimum.y;
  16121. // OBB
  16122. this.center = this.maximum.add(this.minimum).scale(0.5);
  16123. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16124. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16125. // World
  16126. for (var index = 0; index < this.vectors.length; index++) {
  16127. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16128. }
  16129. this.minimumWorld = BABYLON.Vector3.Zero();
  16130. this.maximumWorld = BABYLON.Vector3.Zero();
  16131. this.centerWorld = BABYLON.Vector3.Zero();
  16132. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16133. this._update(BABYLON.Matrix.Identity());
  16134. }
  16135. // Methods
  16136. BoundingBox.prototype.getWorldMatrix = function () {
  16137. return this._worldMatrix;
  16138. };
  16139. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16140. this._worldMatrix.copyFrom(matrix);
  16141. return this;
  16142. };
  16143. BoundingBox.prototype._update = function (world) {
  16144. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16145. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16146. for (var index = 0; index < this.vectors.length; index++) {
  16147. var v = this.vectorsWorld[index];
  16148. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16149. if (v.x < this.minimumWorld.x)
  16150. this.minimumWorld.x = v.x;
  16151. if (v.y < this.minimumWorld.y)
  16152. this.minimumWorld.y = v.y;
  16153. if (v.z < this.minimumWorld.z)
  16154. this.minimumWorld.z = v.z;
  16155. if (v.x > this.maximumWorld.x)
  16156. this.maximumWorld.x = v.x;
  16157. if (v.y > this.maximumWorld.y)
  16158. this.maximumWorld.y = v.y;
  16159. if (v.z > this.maximumWorld.z)
  16160. this.maximumWorld.z = v.z;
  16161. }
  16162. // Extend
  16163. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16164. this.extendSizeWorld.scaleInPlace(0.5);
  16165. // OBB
  16166. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16167. this.centerWorld.scaleInPlace(0.5);
  16168. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16169. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16170. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16171. this._worldMatrix = world;
  16172. };
  16173. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16174. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16175. };
  16176. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16177. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16178. };
  16179. BoundingBox.prototype.intersectsPoint = function (point) {
  16180. var delta = -BABYLON.Epsilon;
  16181. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16182. return false;
  16183. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16184. return false;
  16185. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16186. return false;
  16187. return true;
  16188. };
  16189. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16190. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16191. };
  16192. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16193. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16194. return false;
  16195. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16196. return false;
  16197. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingBox.Intersects = function (box0, box1) {
  16203. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16204. return false;
  16205. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16206. return false;
  16207. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16208. return false;
  16209. return true;
  16210. };
  16211. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16212. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16213. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16214. return (num <= (sphereRadius * sphereRadius));
  16215. };
  16216. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16217. for (var p = 0; p < 6; p++) {
  16218. for (var i = 0; i < 8; i++) {
  16219. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16220. return false;
  16221. }
  16222. }
  16223. }
  16224. return true;
  16225. };
  16226. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16227. for (var p = 0; p < 6; p++) {
  16228. var inCount = 8;
  16229. for (var i = 0; i < 8; i++) {
  16230. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16231. --inCount;
  16232. }
  16233. else {
  16234. break;
  16235. }
  16236. }
  16237. if (inCount === 0)
  16238. return false;
  16239. }
  16240. return true;
  16241. };
  16242. return BoundingBox;
  16243. }());
  16244. BABYLON.BoundingBox = BoundingBox;
  16245. })(BABYLON || (BABYLON = {}));
  16246. //# sourceMappingURL=babylon.boundingBox.js.map
  16247. var BABYLON;
  16248. (function (BABYLON) {
  16249. var computeBoxExtents = function (axis, box) {
  16250. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16251. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16252. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16253. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16254. var r = r0 + r1 + r2;
  16255. return {
  16256. min: p - r,
  16257. max: p + r
  16258. };
  16259. };
  16260. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16261. var axisOverlap = function (axis, box0, box1) {
  16262. var result0 = computeBoxExtents(axis, box0);
  16263. var result1 = computeBoxExtents(axis, box1);
  16264. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16265. };
  16266. var BoundingInfo = /** @class */ (function () {
  16267. function BoundingInfo(minimum, maximum) {
  16268. this.minimum = minimum;
  16269. this.maximum = maximum;
  16270. this._isLocked = false;
  16271. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16272. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16273. }
  16274. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16275. get: function () {
  16276. return this._isLocked;
  16277. },
  16278. set: function (value) {
  16279. this._isLocked = value;
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. // Methods
  16285. BoundingInfo.prototype.update = function (world) {
  16286. if (this._isLocked) {
  16287. return;
  16288. }
  16289. this.boundingBox._update(world);
  16290. this.boundingSphere._update(world);
  16291. };
  16292. /**
  16293. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16294. * @param center New center of the bounding info
  16295. * @param extend New extend of the bounding info
  16296. */
  16297. BoundingInfo.prototype.centerOn = function (center, extend) {
  16298. this.minimum = center.subtract(extend);
  16299. this.maximum = center.add(extend);
  16300. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16301. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16302. return this;
  16303. };
  16304. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16305. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16306. return false;
  16307. return this.boundingBox.isInFrustum(frustumPlanes);
  16308. };
  16309. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16310. /**
  16311. * Gets the world distance between the min and max points of the bounding box
  16312. */
  16313. get: function () {
  16314. var boundingBox = this.boundingBox;
  16315. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16316. return size.length();
  16317. },
  16318. enumerable: true,
  16319. configurable: true
  16320. });
  16321. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16322. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16323. };
  16324. BoundingInfo.prototype._checkCollision = function (collider) {
  16325. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16326. };
  16327. BoundingInfo.prototype.intersectsPoint = function (point) {
  16328. if (!this.boundingSphere.centerWorld) {
  16329. return false;
  16330. }
  16331. if (!this.boundingSphere.intersectsPoint(point)) {
  16332. return false;
  16333. }
  16334. if (!this.boundingBox.intersectsPoint(point)) {
  16335. return false;
  16336. }
  16337. return true;
  16338. };
  16339. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16340. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16341. return false;
  16342. }
  16343. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16344. return false;
  16345. }
  16346. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16347. return false;
  16348. }
  16349. if (!precise) {
  16350. return true;
  16351. }
  16352. var box0 = this.boundingBox;
  16353. var box1 = boundingInfo.boundingBox;
  16354. if (!axisOverlap(box0.directions[0], box0, box1))
  16355. return false;
  16356. if (!axisOverlap(box0.directions[1], box0, box1))
  16357. return false;
  16358. if (!axisOverlap(box0.directions[2], box0, box1))
  16359. return false;
  16360. if (!axisOverlap(box1.directions[0], box0, box1))
  16361. return false;
  16362. if (!axisOverlap(box1.directions[1], box0, box1))
  16363. return false;
  16364. if (!axisOverlap(box1.directions[2], box0, box1))
  16365. return false;
  16366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16367. return false;
  16368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16369. return false;
  16370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16371. return false;
  16372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16373. return false;
  16374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16375. return false;
  16376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16377. return false;
  16378. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16379. return false;
  16380. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16381. return false;
  16382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16383. return false;
  16384. return true;
  16385. };
  16386. return BoundingInfo;
  16387. }());
  16388. BABYLON.BoundingInfo = BoundingInfo;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.boundingInfo.js.map
  16391. var BABYLON;
  16392. (function (BABYLON) {
  16393. var TransformNode = /** @class */ (function (_super) {
  16394. __extends(TransformNode, _super);
  16395. function TransformNode(name, scene, isPure) {
  16396. if (scene === void 0) { scene = null; }
  16397. if (isPure === void 0) { isPure = true; }
  16398. var _this = _super.call(this, name, scene) || this;
  16399. // Properties
  16400. _this._rotation = BABYLON.Vector3.Zero();
  16401. _this._scaling = BABYLON.Vector3.One();
  16402. _this._isDirty = false;
  16403. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16404. _this.scalingDeterminant = 1;
  16405. _this.infiniteDistance = false;
  16406. _this.position = BABYLON.Vector3.Zero();
  16407. _this._localWorld = BABYLON.Matrix.Zero();
  16408. _this._worldMatrix = BABYLON.Matrix.Zero();
  16409. _this._worldMatrixDeterminant = 0;
  16410. _this._absolutePosition = BABYLON.Vector3.Zero();
  16411. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16412. _this._postMultiplyPivotMatrix = false;
  16413. _this._isWorldMatrixFrozen = false;
  16414. /**
  16415. * An event triggered after the world matrix is updated
  16416. * @type {BABYLON.Observable}
  16417. */
  16418. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16419. _this._nonUniformScaling = false;
  16420. if (isPure) {
  16421. _this.getScene().addTransformNode(_this);
  16422. }
  16423. return _this;
  16424. }
  16425. /**
  16426. * Gets a string idenfifying the name of the class
  16427. * @returns "TransformNode" string
  16428. */
  16429. TransformNode.prototype.getClassName = function () {
  16430. return "TransformNode";
  16431. };
  16432. Object.defineProperty(TransformNode.prototype, "rotation", {
  16433. /**
  16434. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16435. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16436. * Default : (0.0, 0.0, 0.0)
  16437. */
  16438. get: function () {
  16439. return this._rotation;
  16440. },
  16441. set: function (newRotation) {
  16442. this._rotation = newRotation;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(TransformNode.prototype, "scaling", {
  16448. /**
  16449. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16450. * Default : (1.0, 1.0, 1.0)
  16451. */
  16452. get: function () {
  16453. return this._scaling;
  16454. },
  16455. /**
  16456. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16457. * Default : (1.0, 1.0, 1.0)
  16458. */
  16459. set: function (newScaling) {
  16460. this._scaling = newScaling;
  16461. },
  16462. enumerable: true,
  16463. configurable: true
  16464. });
  16465. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16466. /**
  16467. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16468. * It's null by default.
  16469. * 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)
  16470. */
  16471. get: function () {
  16472. return this._rotationQuaternion;
  16473. },
  16474. set: function (quaternion) {
  16475. this._rotationQuaternion = quaternion;
  16476. //reset the rotation vector.
  16477. if (quaternion && this.rotation.length()) {
  16478. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16479. }
  16480. },
  16481. enumerable: true,
  16482. configurable: true
  16483. });
  16484. /**
  16485. * Returns the latest update of the World matrix
  16486. * Returns a Matrix.
  16487. */
  16488. TransformNode.prototype.getWorldMatrix = function () {
  16489. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16490. this.computeWorldMatrix();
  16491. }
  16492. return this._worldMatrix;
  16493. };
  16494. /**
  16495. * Returns the latest update of the World matrix determinant.
  16496. */
  16497. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16498. return this._worldMatrixDeterminant;
  16499. };
  16500. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16501. /**
  16502. * Returns directly the latest state of the mesh World matrix.
  16503. * A Matrix is returned.
  16504. */
  16505. get: function () {
  16506. return this._worldMatrix;
  16507. },
  16508. enumerable: true,
  16509. configurable: true
  16510. });
  16511. /**
  16512. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16513. * Returns the AbstractMesh.
  16514. */
  16515. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16516. this._poseMatrix.copyFrom(matrix);
  16517. return this;
  16518. };
  16519. /**
  16520. * Returns the mesh Pose matrix.
  16521. * Returned object : Matrix
  16522. */
  16523. TransformNode.prototype.getPoseMatrix = function () {
  16524. return this._poseMatrix;
  16525. };
  16526. TransformNode.prototype._isSynchronized = function () {
  16527. if (this._isDirty) {
  16528. return false;
  16529. }
  16530. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16531. return false;
  16532. if (this._cache.pivotMatrixUpdated) {
  16533. return false;
  16534. }
  16535. if (this.infiniteDistance) {
  16536. return false;
  16537. }
  16538. if (!this._cache.position.equals(this.position))
  16539. return false;
  16540. if (this.rotationQuaternion) {
  16541. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16542. return false;
  16543. }
  16544. if (!this._cache.rotation.equals(this.rotation))
  16545. return false;
  16546. if (!this._cache.scaling.equals(this.scaling))
  16547. return false;
  16548. return true;
  16549. };
  16550. TransformNode.prototype._initCache = function () {
  16551. _super.prototype._initCache.call(this);
  16552. this._cache.localMatrixUpdated = false;
  16553. this._cache.position = BABYLON.Vector3.Zero();
  16554. this._cache.scaling = BABYLON.Vector3.Zero();
  16555. this._cache.rotation = BABYLON.Vector3.Zero();
  16556. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16557. this._cache.billboardMode = -1;
  16558. };
  16559. TransformNode.prototype.markAsDirty = function (property) {
  16560. if (property === "rotation") {
  16561. this.rotationQuaternion = null;
  16562. }
  16563. this._currentRenderId = Number.MAX_VALUE;
  16564. this._isDirty = true;
  16565. return this;
  16566. };
  16567. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16568. /**
  16569. * Returns the current mesh absolute position.
  16570. * Retuns a Vector3.
  16571. */
  16572. get: function () {
  16573. return this._absolutePosition;
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. /**
  16579. * Sets a new matrix to apply before all other transformation
  16580. * @param matrix defines the transform matrix
  16581. * @returns the current TransformNode
  16582. */
  16583. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16584. return this.setPivotMatrix(matrix, false);
  16585. };
  16586. /**
  16587. * Sets a new pivot matrix to the current node
  16588. * @param matrix defines the new pivot matrix to use
  16589. * @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
  16590. * @returns the current TransformNode
  16591. */
  16592. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16593. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16594. this._pivotMatrix = matrix.clone();
  16595. this._cache.pivotMatrixUpdated = true;
  16596. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16597. if (this._postMultiplyPivotMatrix) {
  16598. if (!this._pivotMatrixInverse) {
  16599. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16600. }
  16601. else {
  16602. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16603. }
  16604. }
  16605. return this;
  16606. };
  16607. /**
  16608. * Returns the mesh pivot matrix.
  16609. * Default : Identity.
  16610. * A Matrix is returned.
  16611. */
  16612. TransformNode.prototype.getPivotMatrix = function () {
  16613. return this._pivotMatrix;
  16614. };
  16615. /**
  16616. * Prevents the World matrix to be computed any longer.
  16617. * Returns the AbstractMesh.
  16618. */
  16619. TransformNode.prototype.freezeWorldMatrix = function () {
  16620. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16621. this.computeWorldMatrix(true);
  16622. this._isWorldMatrixFrozen = true;
  16623. return this;
  16624. };
  16625. /**
  16626. * Allows back the World matrix computation.
  16627. * Returns the AbstractMesh.
  16628. */
  16629. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16630. this._isWorldMatrixFrozen = false;
  16631. this.computeWorldMatrix(true);
  16632. return this;
  16633. };
  16634. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16635. /**
  16636. * True if the World matrix has been frozen.
  16637. * Returns a boolean.
  16638. */
  16639. get: function () {
  16640. return this._isWorldMatrixFrozen;
  16641. },
  16642. enumerable: true,
  16643. configurable: true
  16644. });
  16645. /**
  16646. * Retuns the mesh absolute position in the World.
  16647. * Returns a Vector3.
  16648. */
  16649. TransformNode.prototype.getAbsolutePosition = function () {
  16650. this.computeWorldMatrix();
  16651. return this._absolutePosition;
  16652. };
  16653. /**
  16654. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16655. * Returns the AbstractMesh.
  16656. */
  16657. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16658. if (!absolutePosition) {
  16659. return this;
  16660. }
  16661. var absolutePositionX;
  16662. var absolutePositionY;
  16663. var absolutePositionZ;
  16664. if (absolutePosition.x === undefined) {
  16665. if (arguments.length < 3) {
  16666. return this;
  16667. }
  16668. absolutePositionX = arguments[0];
  16669. absolutePositionY = arguments[1];
  16670. absolutePositionZ = arguments[2];
  16671. }
  16672. else {
  16673. absolutePositionX = absolutePosition.x;
  16674. absolutePositionY = absolutePosition.y;
  16675. absolutePositionZ = absolutePosition.z;
  16676. }
  16677. if (this.parent) {
  16678. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16679. invertParentWorldMatrix.invert();
  16680. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16681. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16682. }
  16683. else {
  16684. this.position.x = absolutePositionX;
  16685. this.position.y = absolutePositionY;
  16686. this.position.z = absolutePositionZ;
  16687. }
  16688. return this;
  16689. };
  16690. /**
  16691. * Sets the mesh position in its local space.
  16692. * Returns the AbstractMesh.
  16693. */
  16694. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16695. this.computeWorldMatrix();
  16696. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16697. return this;
  16698. };
  16699. /**
  16700. * Returns the mesh position in the local space from the current World matrix values.
  16701. * Returns a new Vector3.
  16702. */
  16703. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16704. this.computeWorldMatrix();
  16705. var invLocalWorldMatrix = this._localWorld.clone();
  16706. invLocalWorldMatrix.invert();
  16707. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16708. };
  16709. /**
  16710. * Translates the mesh along the passed Vector3 in its local space.
  16711. * Returns the AbstractMesh.
  16712. */
  16713. TransformNode.prototype.locallyTranslate = function (vector3) {
  16714. this.computeWorldMatrix(true);
  16715. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16716. return this;
  16717. };
  16718. /**
  16719. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16720. * @param targetPoint the position (must be in same space as current mesh) to look at
  16721. * @param yawCor optional yaw (y-axis) correction in radians
  16722. * @param pitchCor optional pitch (x-axis) correction in radians
  16723. * @param rollCor optional roll (z-axis) correction in radians
  16724. * @param space the choosen space of the target
  16725. * @returns the TransformNode.
  16726. */
  16727. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16728. if (yawCor === void 0) { yawCor = 0; }
  16729. if (pitchCor === void 0) { pitchCor = 0; }
  16730. if (rollCor === void 0) { rollCor = 0; }
  16731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16732. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16733. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16734. targetPoint.subtractToRef(pos, dv);
  16735. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16736. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16737. var pitch = Math.atan2(dv.y, len);
  16738. if (this.rotationQuaternion) {
  16739. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16740. }
  16741. else {
  16742. this.rotation.x = pitch + pitchCor;
  16743. this.rotation.y = yaw + yawCor;
  16744. this.rotation.z = rollCor;
  16745. }
  16746. return this;
  16747. };
  16748. /**
  16749. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16750. * This Vector3 is expressed in the World space.
  16751. */
  16752. TransformNode.prototype.getDirection = function (localAxis) {
  16753. var result = BABYLON.Vector3.Zero();
  16754. this.getDirectionToRef(localAxis, result);
  16755. return result;
  16756. };
  16757. /**
  16758. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16759. * localAxis is expressed in the mesh local space.
  16760. * result is computed in the Wordl space from the mesh World matrix.
  16761. * Returns the AbstractMesh.
  16762. */
  16763. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16764. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16765. return this;
  16766. };
  16767. /**
  16768. * Sets a new pivot point to the current node
  16769. * @param point defines the new pivot point to use
  16770. * @param space defines if the point is in world or local space (local by default)
  16771. * @returns the current TransformNode
  16772. */
  16773. TransformNode.prototype.setPivotPoint = function (point, space) {
  16774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16775. if (this.getScene().getRenderId() == 0) {
  16776. this.computeWorldMatrix(true);
  16777. }
  16778. var wm = this.getWorldMatrix();
  16779. if (space == BABYLON.Space.WORLD) {
  16780. var tmat = BABYLON.Tmp.Matrix[0];
  16781. wm.invertToRef(tmat);
  16782. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16783. }
  16784. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16785. };
  16786. /**
  16787. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16788. */
  16789. TransformNode.prototype.getPivotPoint = function () {
  16790. var point = BABYLON.Vector3.Zero();
  16791. this.getPivotPointToRef(point);
  16792. return point;
  16793. };
  16794. /**
  16795. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16796. * Returns the AbstractMesh.
  16797. */
  16798. TransformNode.prototype.getPivotPointToRef = function (result) {
  16799. result.x = -this._pivotMatrix.m[12];
  16800. result.y = -this._pivotMatrix.m[13];
  16801. result.z = -this._pivotMatrix.m[14];
  16802. return this;
  16803. };
  16804. /**
  16805. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16806. */
  16807. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16808. var point = BABYLON.Vector3.Zero();
  16809. this.getAbsolutePivotPointToRef(point);
  16810. return point;
  16811. };
  16812. /**
  16813. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16814. * Returns the AbstractMesh.
  16815. */
  16816. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16817. result.x = this._pivotMatrix.m[12];
  16818. result.y = this._pivotMatrix.m[13];
  16819. result.z = this._pivotMatrix.m[14];
  16820. this.getPivotPointToRef(result);
  16821. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16822. return this;
  16823. };
  16824. /**
  16825. * Defines the passed node as the parent of the current node.
  16826. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16827. * Returns the TransformNode.
  16828. */
  16829. TransformNode.prototype.setParent = function (node) {
  16830. if (node === null) {
  16831. var rotation = BABYLON.Tmp.Quaternion[0];
  16832. var position = BABYLON.Tmp.Vector3[0];
  16833. var scale = BABYLON.Tmp.Vector3[1];
  16834. if (this.parent && this.parent.computeWorldMatrix) {
  16835. this.parent.computeWorldMatrix(true);
  16836. }
  16837. this.computeWorldMatrix(true);
  16838. this.getWorldMatrix().decompose(scale, rotation, position);
  16839. if (this.rotationQuaternion) {
  16840. this.rotationQuaternion.copyFrom(rotation);
  16841. }
  16842. else {
  16843. rotation.toEulerAnglesToRef(this.rotation);
  16844. }
  16845. this.scaling.x = scale.x;
  16846. this.scaling.y = scale.y;
  16847. this.scaling.z = scale.z;
  16848. this.position.x = position.x;
  16849. this.position.y = position.y;
  16850. this.position.z = position.z;
  16851. }
  16852. else {
  16853. var rotation = BABYLON.Tmp.Quaternion[0];
  16854. var position = BABYLON.Tmp.Vector3[0];
  16855. var scale = BABYLON.Tmp.Vector3[1];
  16856. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16857. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16858. this.computeWorldMatrix(true);
  16859. node.computeWorldMatrix(true);
  16860. node.getWorldMatrix().invertToRef(invParentMatrix);
  16861. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16862. diffMatrix.decompose(scale, rotation, position);
  16863. if (this.rotationQuaternion) {
  16864. this.rotationQuaternion.copyFrom(rotation);
  16865. }
  16866. else {
  16867. rotation.toEulerAnglesToRef(this.rotation);
  16868. }
  16869. this.position.x = position.x;
  16870. this.position.y = position.y;
  16871. this.position.z = position.z;
  16872. this.scaling.x = scale.x;
  16873. this.scaling.y = scale.y;
  16874. this.scaling.z = scale.z;
  16875. }
  16876. this.parent = node;
  16877. return this;
  16878. };
  16879. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16880. get: function () {
  16881. return this._nonUniformScaling;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16887. if (this._nonUniformScaling === value) {
  16888. return false;
  16889. }
  16890. this._nonUniformScaling = true;
  16891. return true;
  16892. };
  16893. /**
  16894. * Attach the current TransformNode to another TransformNode associated with a bone
  16895. * @param bone Bone affecting the TransformNode
  16896. * @param affectedTransformNode TransformNode associated with the bone
  16897. */
  16898. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16899. this._transformToBoneReferal = affectedTransformNode;
  16900. this.parent = bone;
  16901. if (bone.getWorldMatrix().determinant() < 0) {
  16902. this.scalingDeterminant *= -1;
  16903. }
  16904. return this;
  16905. };
  16906. TransformNode.prototype.detachFromBone = function () {
  16907. if (!this.parent) {
  16908. return this;
  16909. }
  16910. if (this.parent.getWorldMatrix().determinant() < 0) {
  16911. this.scalingDeterminant *= -1;
  16912. }
  16913. this._transformToBoneReferal = null;
  16914. this.parent = null;
  16915. return this;
  16916. };
  16917. /**
  16918. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16919. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16920. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16921. * The passed axis is also normalized.
  16922. * Returns the AbstractMesh.
  16923. */
  16924. TransformNode.prototype.rotate = function (axis, amount, space) {
  16925. axis.normalize();
  16926. if (!this.rotationQuaternion) {
  16927. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16928. this.rotation = BABYLON.Vector3.Zero();
  16929. }
  16930. var rotationQuaternion;
  16931. if (!space || space === BABYLON.Space.LOCAL) {
  16932. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16933. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16934. }
  16935. else {
  16936. if (this.parent) {
  16937. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16938. invertParentWorldMatrix.invert();
  16939. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16940. }
  16941. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16942. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16943. }
  16944. return this;
  16945. };
  16946. /**
  16947. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16948. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16949. * The passed axis is also normalized.
  16950. * Returns the AbstractMesh.
  16951. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16952. */
  16953. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16954. axis.normalize();
  16955. if (!this.rotationQuaternion) {
  16956. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16957. this.rotation.copyFromFloats(0, 0, 0);
  16958. }
  16959. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16960. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16961. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16962. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16963. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16964. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16965. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16966. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16967. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16968. return this;
  16969. };
  16970. /**
  16971. * Translates the mesh along the axis vector for the passed distance in the given space.
  16972. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16973. * Returns the AbstractMesh.
  16974. */
  16975. TransformNode.prototype.translate = function (axis, distance, space) {
  16976. var displacementVector = axis.scale(distance);
  16977. if (!space || space === BABYLON.Space.LOCAL) {
  16978. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16979. this.setPositionWithLocalVector(tempV3);
  16980. }
  16981. else {
  16982. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16983. }
  16984. return this;
  16985. };
  16986. /**
  16987. * Adds a rotation step to the mesh current rotation.
  16988. * x, y, z are Euler angles expressed in radians.
  16989. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16990. * This means this rotation is made in the mesh local space only.
  16991. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16992. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16993. * ```javascript
  16994. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16995. * ```
  16996. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16997. * 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.
  16998. * Returns the AbstractMesh.
  16999. */
  17000. TransformNode.prototype.addRotation = function (x, y, z) {
  17001. var rotationQuaternion;
  17002. if (this.rotationQuaternion) {
  17003. rotationQuaternion = this.rotationQuaternion;
  17004. }
  17005. else {
  17006. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17007. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17008. }
  17009. var accumulation = BABYLON.Tmp.Quaternion[0];
  17010. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17011. rotationQuaternion.multiplyInPlace(accumulation);
  17012. if (!this.rotationQuaternion) {
  17013. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17014. }
  17015. return this;
  17016. };
  17017. /**
  17018. * Computes the mesh World matrix and returns it.
  17019. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17020. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17021. * If the parameter `force`is set to `true`, the actual computation is done.
  17022. * Returns the mesh World Matrix.
  17023. */
  17024. TransformNode.prototype.computeWorldMatrix = function (force) {
  17025. if (this._isWorldMatrixFrozen) {
  17026. return this._worldMatrix;
  17027. }
  17028. if (!force && this.isSynchronized(true)) {
  17029. return this._worldMatrix;
  17030. }
  17031. this._cache.position.copyFrom(this.position);
  17032. this._cache.scaling.copyFrom(this.scaling);
  17033. this._cache.pivotMatrixUpdated = false;
  17034. this._cache.billboardMode = this.billboardMode;
  17035. this._currentRenderId = this.getScene().getRenderId();
  17036. this._isDirty = false;
  17037. // Scaling
  17038. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17039. // Rotation
  17040. //rotate, if quaternion is set and rotation was used
  17041. if (this.rotationQuaternion) {
  17042. var len = this.rotation.length();
  17043. if (len) {
  17044. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17045. this.rotation.copyFromFloats(0, 0, 0);
  17046. }
  17047. }
  17048. if (this.rotationQuaternion) {
  17049. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17050. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17051. }
  17052. else {
  17053. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17054. this._cache.rotation.copyFrom(this.rotation);
  17055. }
  17056. // Translation
  17057. var camera = this.getScene().activeCamera;
  17058. if (this.infiniteDistance && !this.parent && camera) {
  17059. var cameraWorldMatrix = camera.getWorldMatrix();
  17060. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17061. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17062. }
  17063. else {
  17064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17065. }
  17066. // Composing transformations
  17067. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17068. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17069. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17070. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17071. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17072. // Need to decompose each rotation here
  17073. var currentPosition = BABYLON.Tmp.Vector3[3];
  17074. if (this.parent && this.parent.getWorldMatrix) {
  17075. if (this._transformToBoneReferal) {
  17076. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17077. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17078. }
  17079. else {
  17080. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17081. }
  17082. }
  17083. else {
  17084. currentPosition.copyFrom(this.position);
  17085. }
  17086. currentPosition.subtractInPlace(camera.globalPosition);
  17087. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17088. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17089. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17090. }
  17091. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17092. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17093. }
  17094. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17095. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17096. }
  17097. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17098. }
  17099. else {
  17100. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17101. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17102. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17103. }
  17104. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17105. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17106. }
  17107. // Local world
  17108. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17109. // Parent
  17110. if (this.parent && this.parent.getWorldMatrix) {
  17111. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17112. if (this._transformToBoneReferal) {
  17113. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17114. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17115. }
  17116. else {
  17117. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17118. }
  17119. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17120. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17121. this._worldMatrix.copyFrom(this._localWorld);
  17122. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17123. }
  17124. else {
  17125. if (this._transformToBoneReferal) {
  17126. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17127. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17128. }
  17129. else {
  17130. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17131. }
  17132. }
  17133. this._markSyncedWithParent();
  17134. }
  17135. else {
  17136. this._worldMatrix.copyFrom(this._localWorld);
  17137. }
  17138. // Post multiply inverse of pivotMatrix
  17139. if (this._postMultiplyPivotMatrix) {
  17140. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17141. }
  17142. // Normal matrix
  17143. if (this.scaling.isNonUniform) {
  17144. this._updateNonUniformScalingState(true);
  17145. }
  17146. else if (this.parent && this.parent._nonUniformScaling) {
  17147. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17148. }
  17149. else {
  17150. this._updateNonUniformScalingState(false);
  17151. }
  17152. this._afterComputeWorldMatrix();
  17153. // Absolute position
  17154. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17155. // Callbacks
  17156. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17157. if (!this._poseMatrix) {
  17158. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17159. }
  17160. // Cache the determinant
  17161. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17162. return this._worldMatrix;
  17163. };
  17164. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17165. };
  17166. /**
  17167. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17168. * @param func: callback function to add
  17169. *
  17170. * Returns the TransformNode.
  17171. */
  17172. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17173. this.onAfterWorldMatrixUpdateObservable.add(func);
  17174. return this;
  17175. };
  17176. /**
  17177. * Removes a registered callback function.
  17178. * Returns the TransformNode.
  17179. */
  17180. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17181. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17182. return this;
  17183. };
  17184. /**
  17185. * Clone the current transform node
  17186. * Returns the new transform node
  17187. * @param name Name of the new clone
  17188. * @param newParent New parent for the clone
  17189. * @param doNotCloneChildren Do not clone children hierarchy
  17190. */
  17191. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17192. var _this = this;
  17193. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17194. result.name = name;
  17195. result.id = name;
  17196. if (newParent) {
  17197. result.parent = newParent;
  17198. }
  17199. if (!doNotCloneChildren) {
  17200. // Children
  17201. var directDescendants = this.getDescendants(true);
  17202. for (var index = 0; index < directDescendants.length; index++) {
  17203. var child = directDescendants[index];
  17204. if (child.clone) {
  17205. child.clone(name + "." + child.name, result);
  17206. }
  17207. }
  17208. }
  17209. return result;
  17210. };
  17211. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17212. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17213. serializationObject.type = this.getClassName();
  17214. // Parent
  17215. if (this.parent) {
  17216. serializationObject.parentId = this.parent.id;
  17217. }
  17218. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17219. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17220. }
  17221. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17222. serializationObject.isEnabled = this.isEnabled();
  17223. // Parent
  17224. if (this.parent) {
  17225. serializationObject.parentId = this.parent.id;
  17226. }
  17227. return serializationObject;
  17228. };
  17229. // Statics
  17230. /**
  17231. * Returns a new TransformNode object parsed from the source provided.
  17232. * The parameter `parsedMesh` is the source.
  17233. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17234. */
  17235. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17236. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17237. if (BABYLON.Tags) {
  17238. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17239. }
  17240. if (parsedTransformNode.localMatrix) {
  17241. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17242. }
  17243. else if (parsedTransformNode.pivotMatrix) {
  17244. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17245. }
  17246. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17247. // Parent
  17248. if (parsedTransformNode.parentId) {
  17249. transformNode._waitingParentId = parsedTransformNode.parentId;
  17250. }
  17251. return transformNode;
  17252. };
  17253. /**
  17254. * Releases resources associated with this transform node.
  17255. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17256. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17257. */
  17258. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17260. // Animations
  17261. this.getScene().stopAnimation(this);
  17262. // Remove from scene
  17263. this.getScene().removeTransformNode(this);
  17264. this.onAfterWorldMatrixUpdateObservable.clear();
  17265. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17266. };
  17267. // Statics
  17268. TransformNode.BILLBOARDMODE_NONE = 0;
  17269. TransformNode.BILLBOARDMODE_X = 1;
  17270. TransformNode.BILLBOARDMODE_Y = 2;
  17271. TransformNode.BILLBOARDMODE_Z = 4;
  17272. TransformNode.BILLBOARDMODE_ALL = 7;
  17273. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17274. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17275. __decorate([
  17276. BABYLON.serializeAsVector3()
  17277. ], TransformNode.prototype, "_rotation", void 0);
  17278. __decorate([
  17279. BABYLON.serializeAsQuaternion()
  17280. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17281. __decorate([
  17282. BABYLON.serializeAsVector3()
  17283. ], TransformNode.prototype, "_scaling", void 0);
  17284. __decorate([
  17285. BABYLON.serialize()
  17286. ], TransformNode.prototype, "billboardMode", void 0);
  17287. __decorate([
  17288. BABYLON.serialize()
  17289. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17290. __decorate([
  17291. BABYLON.serialize()
  17292. ], TransformNode.prototype, "infiniteDistance", void 0);
  17293. __decorate([
  17294. BABYLON.serializeAsVector3()
  17295. ], TransformNode.prototype, "position", void 0);
  17296. return TransformNode;
  17297. }(BABYLON.Node));
  17298. BABYLON.TransformNode = TransformNode;
  17299. })(BABYLON || (BABYLON = {}));
  17300. //# sourceMappingURL=babylon.transformNode.js.map
  17301. var BABYLON;
  17302. (function (BABYLON) {
  17303. var AbstractMesh = /** @class */ (function (_super) {
  17304. __extends(AbstractMesh, _super);
  17305. // Constructor
  17306. function AbstractMesh(name, scene) {
  17307. if (scene === void 0) { scene = null; }
  17308. var _this = _super.call(this, name, scene, false) || this;
  17309. _this._facetNb = 0; // facet number
  17310. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17311. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17312. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17313. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17314. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17315. _this._subDiv = {
  17316. max: 1,
  17317. X: 1,
  17318. Y: 1,
  17319. Z: 1
  17320. };
  17321. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17322. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17323. // Events
  17324. /**
  17325. * An event triggered when this mesh collides with another one
  17326. * @type {BABYLON.Observable}
  17327. */
  17328. _this.onCollideObservable = new BABYLON.Observable();
  17329. /**
  17330. * An event triggered when the collision's position changes
  17331. * @type {BABYLON.Observable}
  17332. */
  17333. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17334. /**
  17335. * An event triggered when material is changed
  17336. * @type {BABYLON.Observable}
  17337. */
  17338. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17339. // Properties
  17340. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17341. /**
  17342. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17343. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17344. * or
  17345. * 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.
  17346. * for more info check WebGl documentations
  17347. */
  17348. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17349. /**
  17350. * 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:
  17351. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17352. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17353. * 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.
  17354. */
  17355. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17356. /**
  17357. * 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.
  17358. * The default value is -1 which means don't break the query and wait till the result.
  17359. */
  17360. _this.occlusionRetryCount = -1;
  17361. _this._occlusionInternalRetryCounter = 0;
  17362. _this._isOccluded = false;
  17363. _this._isOcclusionQueryInProgress = false;
  17364. _this._visibility = 1.0;
  17365. _this.alphaIndex = Number.MAX_VALUE;
  17366. _this.isVisible = true;
  17367. _this.isPickable = true;
  17368. _this.showBoundingBox = false;
  17369. _this.showSubMeshesBoundingBox = false;
  17370. _this.isBlocker = false;
  17371. _this.enablePointerMoveEvents = false;
  17372. _this.renderingGroupId = 0;
  17373. _this._receiveShadows = false;
  17374. _this.renderOutline = false;
  17375. _this.outlineColor = BABYLON.Color3.Red();
  17376. _this.outlineWidth = 0.02;
  17377. _this.renderOverlay = false;
  17378. _this.overlayColor = BABYLON.Color3.Red();
  17379. _this.overlayAlpha = 0.5;
  17380. _this._hasVertexAlpha = false;
  17381. _this._useVertexColors = true;
  17382. _this._computeBonesUsingShaders = true;
  17383. _this._numBoneInfluencers = 4;
  17384. _this._applyFog = true;
  17385. _this.useOctreeForRenderingSelection = true;
  17386. _this.useOctreeForPicking = true;
  17387. _this.useOctreeForCollisions = true;
  17388. _this._layerMask = 0x0FFFFFFF;
  17389. /**
  17390. * True if the mesh must be rendered in any case.
  17391. */
  17392. _this.alwaysSelectAsActiveMesh = false;
  17393. /**
  17394. * This scene's action manager
  17395. * @type {BABYLON.ActionManager}
  17396. */
  17397. _this.actionManager = null;
  17398. // Physics
  17399. _this.physicsImpostor = null;
  17400. // Collisions
  17401. _this._checkCollisions = false;
  17402. _this._collisionMask = -1;
  17403. _this._collisionGroup = -1;
  17404. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17405. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17406. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17407. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17408. // Edges
  17409. _this.edgesWidth = 1;
  17410. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17411. // Cache
  17412. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17413. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17414. _this._renderId = 0;
  17415. _this._intersectionsInProgress = new Array();
  17416. _this._unIndexed = false;
  17417. _this._lightSources = new Array();
  17418. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17419. if (collidedMesh === void 0) { collidedMesh = null; }
  17420. //TODO move this to the collision coordinator!
  17421. if (_this.getScene().workerCollisions)
  17422. newPosition.multiplyInPlace(_this._collider._radius);
  17423. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17424. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17425. _this.position.addInPlace(_this._diffPositionForCollisions);
  17426. }
  17427. if (collidedMesh) {
  17428. _this.onCollideObservable.notifyObservers(collidedMesh);
  17429. }
  17430. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17431. };
  17432. _this.getScene().addMesh(_this);
  17433. _this._resyncLightSources();
  17434. return _this;
  17435. }
  17436. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17437. get: function () {
  17438. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17444. get: function () {
  17445. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17446. },
  17447. enumerable: true,
  17448. configurable: true
  17449. });
  17450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17451. get: function () {
  17452. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17458. get: function () {
  17459. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17460. },
  17461. enumerable: true,
  17462. configurable: true
  17463. });
  17464. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17465. get: function () {
  17466. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17472. /**
  17473. * Read-only : the number of facets in the mesh
  17474. */
  17475. get: function () {
  17476. return this._facetNb;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17482. /**
  17483. * The number (integer) of subdivisions per axis in the partioning space
  17484. */
  17485. get: function () {
  17486. return this._partitioningSubdivisions;
  17487. },
  17488. set: function (nb) {
  17489. this._partitioningSubdivisions = nb;
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17495. /**
  17496. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17497. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17498. */
  17499. get: function () {
  17500. return this._partitioningBBoxRatio;
  17501. },
  17502. set: function (ratio) {
  17503. this._partitioningBBoxRatio = ratio;
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17509. /**
  17510. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17511. * Works only for updatable meshes.
  17512. * Doesn't work with multi-materials.
  17513. */
  17514. get: function () {
  17515. return this._facetDepthSort;
  17516. },
  17517. set: function (sort) {
  17518. this._facetDepthSort = sort;
  17519. },
  17520. enumerable: true,
  17521. configurable: true
  17522. });
  17523. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17524. /**
  17525. * The location (Vector3) where the facet depth sort must be computed from.
  17526. * By default, the active camera position.
  17527. * Used only when facet depth sort is enabled.
  17528. */
  17529. get: function () {
  17530. return this._facetDepthSortFrom;
  17531. },
  17532. set: function (location) {
  17533. this._facetDepthSortFrom = location;
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17539. /**
  17540. * Read-only boolean : is the feature facetData enabled ?
  17541. */
  17542. get: function () {
  17543. return this._facetDataEnabled;
  17544. },
  17545. enumerable: true,
  17546. configurable: true
  17547. });
  17548. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17549. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17550. return false;
  17551. }
  17552. this._markSubMeshesAsMiscDirty();
  17553. return true;
  17554. };
  17555. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17556. set: function (callback) {
  17557. if (this._onCollideObserver) {
  17558. this.onCollideObservable.remove(this._onCollideObserver);
  17559. }
  17560. this._onCollideObserver = this.onCollideObservable.add(callback);
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17566. set: function (callback) {
  17567. if (this._onCollisionPositionChangeObserver) {
  17568. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17569. }
  17570. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17571. },
  17572. enumerable: true,
  17573. configurable: true
  17574. });
  17575. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17576. /**
  17577. * 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.
  17578. */
  17579. get: function () {
  17580. return this._isOccluded;
  17581. },
  17582. set: function (value) {
  17583. this._isOccluded = value;
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17589. /**
  17590. * Flag to check the progress status of the query
  17591. */
  17592. get: function () {
  17593. return this._isOcclusionQueryInProgress;
  17594. },
  17595. enumerable: true,
  17596. configurable: true
  17597. });
  17598. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17599. /**
  17600. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17601. */
  17602. get: function () {
  17603. return this._visibility;
  17604. },
  17605. /**
  17606. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17607. */
  17608. set: function (value) {
  17609. if (this._visibility === value) {
  17610. return;
  17611. }
  17612. this._visibility = value;
  17613. this._markSubMeshesAsMiscDirty();
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh.prototype, "material", {
  17619. get: function () {
  17620. return this._material;
  17621. },
  17622. set: function (value) {
  17623. if (this._material === value) {
  17624. return;
  17625. }
  17626. this._material = value;
  17627. if (this.onMaterialChangedObservable.hasObservers) {
  17628. this.onMaterialChangedObservable.notifyObservers(this);
  17629. }
  17630. if (!this.subMeshes) {
  17631. return;
  17632. }
  17633. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17634. var subMesh = _a[_i];
  17635. subMesh.setEffect(null);
  17636. }
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17642. get: function () {
  17643. return this._receiveShadows;
  17644. },
  17645. set: function (value) {
  17646. if (this._receiveShadows === value) {
  17647. return;
  17648. }
  17649. this._receiveShadows = value;
  17650. this._markSubMeshesAsLightDirty();
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17656. get: function () {
  17657. return this._hasVertexAlpha;
  17658. },
  17659. set: function (value) {
  17660. if (this._hasVertexAlpha === value) {
  17661. return;
  17662. }
  17663. this._hasVertexAlpha = value;
  17664. this._markSubMeshesAsAttributesDirty();
  17665. this._markSubMeshesAsMiscDirty();
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17671. get: function () {
  17672. return this._useVertexColors;
  17673. },
  17674. set: function (value) {
  17675. if (this._useVertexColors === value) {
  17676. return;
  17677. }
  17678. this._useVertexColors = value;
  17679. this._markSubMeshesAsAttributesDirty();
  17680. },
  17681. enumerable: true,
  17682. configurable: true
  17683. });
  17684. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17685. get: function () {
  17686. return this._computeBonesUsingShaders;
  17687. },
  17688. set: function (value) {
  17689. if (this._computeBonesUsingShaders === value) {
  17690. return;
  17691. }
  17692. this._computeBonesUsingShaders = value;
  17693. this._markSubMeshesAsAttributesDirty();
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17699. get: function () {
  17700. return this._numBoneInfluencers;
  17701. },
  17702. set: function (value) {
  17703. if (this._numBoneInfluencers === value) {
  17704. return;
  17705. }
  17706. this._numBoneInfluencers = value;
  17707. this._markSubMeshesAsAttributesDirty();
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17713. get: function () {
  17714. return this._applyFog;
  17715. },
  17716. set: function (value) {
  17717. if (this._applyFog === value) {
  17718. return;
  17719. }
  17720. this._applyFog = value;
  17721. this._markSubMeshesAsMiscDirty();
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17727. get: function () {
  17728. return this._layerMask;
  17729. },
  17730. set: function (value) {
  17731. if (value === this._layerMask) {
  17732. return;
  17733. }
  17734. this._layerMask = value;
  17735. this._resyncLightSources();
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17741. get: function () {
  17742. return this._collisionMask;
  17743. },
  17744. set: function (mask) {
  17745. this._collisionMask = !isNaN(mask) ? mask : -1;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17751. get: function () {
  17752. return this._collisionGroup;
  17753. },
  17754. set: function (mask) {
  17755. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17761. get: function () {
  17762. return null;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17768. get: function () {
  17769. return this._skeleton;
  17770. },
  17771. set: function (value) {
  17772. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17773. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17774. }
  17775. if (value && value.needInitialSkinMatrix) {
  17776. value._registerMeshWithPoseMatrix(this);
  17777. }
  17778. this._skeleton = value;
  17779. if (!this._skeleton) {
  17780. this._bonesTransformMatrices = null;
  17781. }
  17782. this._markSubMeshesAsAttributesDirty();
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. /**
  17788. * Returns the string "AbstractMesh"
  17789. */
  17790. AbstractMesh.prototype.getClassName = function () {
  17791. return "AbstractMesh";
  17792. };
  17793. /**
  17794. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17795. */
  17796. AbstractMesh.prototype.toString = function (fullDetails) {
  17797. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17798. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17799. if (this._skeleton) {
  17800. ret += ", skeleton: " + this._skeleton.name;
  17801. }
  17802. if (fullDetails) {
  17803. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17804. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17805. }
  17806. return ret;
  17807. };
  17808. AbstractMesh.prototype._rebuild = function () {
  17809. if (this._occlusionQuery) {
  17810. this._occlusionQuery = null;
  17811. }
  17812. if (this._edgesRenderer) {
  17813. this._edgesRenderer._rebuild();
  17814. }
  17815. if (!this.subMeshes) {
  17816. return;
  17817. }
  17818. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17819. var subMesh = _a[_i];
  17820. subMesh._rebuild();
  17821. }
  17822. };
  17823. AbstractMesh.prototype._resyncLightSources = function () {
  17824. this._lightSources.length = 0;
  17825. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17826. var light = _a[_i];
  17827. if (!light.isEnabled()) {
  17828. continue;
  17829. }
  17830. if (light.canAffectMesh(this)) {
  17831. this._lightSources.push(light);
  17832. }
  17833. }
  17834. this._markSubMeshesAsLightDirty();
  17835. };
  17836. AbstractMesh.prototype._resyncLighSource = function (light) {
  17837. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17838. var index = this._lightSources.indexOf(light);
  17839. if (index === -1) {
  17840. if (!isIn) {
  17841. return;
  17842. }
  17843. this._lightSources.push(light);
  17844. }
  17845. else {
  17846. if (isIn) {
  17847. return;
  17848. }
  17849. this._lightSources.splice(index, 1);
  17850. }
  17851. this._markSubMeshesAsLightDirty();
  17852. };
  17853. AbstractMesh.prototype._removeLightSource = function (light) {
  17854. var index = this._lightSources.indexOf(light);
  17855. if (index === -1) {
  17856. return;
  17857. }
  17858. this._lightSources.splice(index, 1);
  17859. this._markSubMeshesAsLightDirty();
  17860. };
  17861. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17862. if (!this.subMeshes) {
  17863. return;
  17864. }
  17865. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17866. var subMesh = _a[_i];
  17867. if (subMesh._materialDefines) {
  17868. func(subMesh._materialDefines);
  17869. }
  17870. }
  17871. };
  17872. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17873. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17874. };
  17875. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17876. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17877. };
  17878. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17879. if (!this.subMeshes) {
  17880. return;
  17881. }
  17882. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17883. var subMesh = _a[_i];
  17884. var material = subMesh.getMaterial();
  17885. if (material) {
  17886. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17887. }
  17888. }
  17889. };
  17890. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17891. /**
  17892. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17893. * Default : (1.0, 1.0, 1.0)
  17894. */
  17895. get: function () {
  17896. return this._scaling;
  17897. },
  17898. /**
  17899. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17900. * Default : (1.0, 1.0, 1.0)
  17901. */
  17902. set: function (newScaling) {
  17903. this._scaling = newScaling;
  17904. if (this.physicsImpostor) {
  17905. this.physicsImpostor.forceUpdate();
  17906. }
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. // Methods
  17912. /**
  17913. * Disables the mesh edger rendering mode.
  17914. * Returns the AbstractMesh.
  17915. */
  17916. AbstractMesh.prototype.disableEdgesRendering = function () {
  17917. if (this._edgesRenderer) {
  17918. this._edgesRenderer.dispose();
  17919. this._edgesRenderer = null;
  17920. }
  17921. return this;
  17922. };
  17923. /**
  17924. * Enables the edge rendering mode on the mesh.
  17925. * This mode makes the mesh edges visible.
  17926. * Returns the AbstractMesh.
  17927. */
  17928. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17929. if (epsilon === void 0) { epsilon = 0.95; }
  17930. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17931. this.disableEdgesRendering();
  17932. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17933. return this;
  17934. };
  17935. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17936. /**
  17937. * Returns true if the mesh is blocked. Used by the class Mesh.
  17938. * Returns the boolean `false` by default.
  17939. */
  17940. get: function () {
  17941. return false;
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. /**
  17947. * Returns the mesh itself by default, used by the class Mesh.
  17948. * Returned type : AbstractMesh
  17949. */
  17950. AbstractMesh.prototype.getLOD = function (camera) {
  17951. return this;
  17952. };
  17953. /**
  17954. * Returns 0 by default, used by the class Mesh.
  17955. * Returns an integer.
  17956. */
  17957. AbstractMesh.prototype.getTotalVertices = function () {
  17958. return 0;
  17959. };
  17960. /**
  17961. * Returns null by default, used by the class Mesh.
  17962. * Returned type : integer array
  17963. */
  17964. AbstractMesh.prototype.getIndices = function () {
  17965. return null;
  17966. };
  17967. /**
  17968. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17969. * Returned type : float array or Float32Array
  17970. */
  17971. AbstractMesh.prototype.getVerticesData = function (kind) {
  17972. return null;
  17973. };
  17974. /**
  17975. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17976. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17977. * The `data` are either a numeric array either a Float32Array.
  17978. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17979. * 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).
  17980. * Note that a new underlying VertexBuffer object is created each call.
  17981. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17982. *
  17983. * Possible `kind` values :
  17984. * - BABYLON.VertexBuffer.PositionKind
  17985. * - BABYLON.VertexBuffer.UVKind
  17986. * - BABYLON.VertexBuffer.UV2Kind
  17987. * - BABYLON.VertexBuffer.UV3Kind
  17988. * - BABYLON.VertexBuffer.UV4Kind
  17989. * - BABYLON.VertexBuffer.UV5Kind
  17990. * - BABYLON.VertexBuffer.UV6Kind
  17991. * - BABYLON.VertexBuffer.ColorKind
  17992. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17993. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17994. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17995. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17996. *
  17997. * Returns the Mesh.
  17998. */
  17999. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18000. return this;
  18001. };
  18002. /**
  18003. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18004. * If the mesh has no geometry, it is simply returned as it is.
  18005. * The `data` are either a numeric array either a Float32Array.
  18006. * No new underlying VertexBuffer object is created.
  18007. * 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.
  18008. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18009. *
  18010. * Possible `kind` values :
  18011. * - BABYLON.VertexBuffer.PositionKind
  18012. * - BABYLON.VertexBuffer.UVKind
  18013. * - BABYLON.VertexBuffer.UV2Kind
  18014. * - BABYLON.VertexBuffer.UV3Kind
  18015. * - BABYLON.VertexBuffer.UV4Kind
  18016. * - BABYLON.VertexBuffer.UV5Kind
  18017. * - BABYLON.VertexBuffer.UV6Kind
  18018. * - BABYLON.VertexBuffer.ColorKind
  18019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18023. *
  18024. * Returns the Mesh.
  18025. */
  18026. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18027. return this;
  18028. };
  18029. /**
  18030. * Sets the mesh indices.
  18031. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18032. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18033. * This method creates a new index buffer each call.
  18034. * Returns the Mesh.
  18035. */
  18036. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18037. return this;
  18038. };
  18039. /** Returns false by default, used by the class Mesh.
  18040. * Returns a boolean
  18041. */
  18042. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18043. return false;
  18044. };
  18045. /**
  18046. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18047. * Returns a BoundingInfo
  18048. */
  18049. AbstractMesh.prototype.getBoundingInfo = function () {
  18050. if (this._masterMesh) {
  18051. return this._masterMesh.getBoundingInfo();
  18052. }
  18053. if (!this._boundingInfo) {
  18054. // this._boundingInfo is being created here
  18055. this._updateBoundingInfo();
  18056. }
  18057. // cannot be null.
  18058. return this._boundingInfo;
  18059. };
  18060. /**
  18061. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18062. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18063. */
  18064. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18065. if (includeDescendants === void 0) { includeDescendants = true; }
  18066. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18067. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18068. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18069. if (maxDimension === 0) {
  18070. return this;
  18071. }
  18072. var scale = 1 / maxDimension;
  18073. this.scaling.scaleInPlace(scale);
  18074. return this;
  18075. };
  18076. /**
  18077. * Sets a mesh new object BoundingInfo.
  18078. * Returns the AbstractMesh.
  18079. */
  18080. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18081. this._boundingInfo = boundingInfo;
  18082. return this;
  18083. };
  18084. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18085. get: function () {
  18086. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18087. },
  18088. enumerable: true,
  18089. configurable: true
  18090. });
  18091. AbstractMesh.prototype._preActivate = function () {
  18092. };
  18093. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18094. };
  18095. AbstractMesh.prototype._activate = function (renderId) {
  18096. this._renderId = renderId;
  18097. };
  18098. /**
  18099. * Returns the latest update of the World matrix
  18100. * Returns a Matrix.
  18101. */
  18102. AbstractMesh.prototype.getWorldMatrix = function () {
  18103. if (this._masterMesh) {
  18104. return this._masterMesh.getWorldMatrix();
  18105. }
  18106. return _super.prototype.getWorldMatrix.call(this);
  18107. };
  18108. /**
  18109. * Returns the latest update of the World matrix determinant.
  18110. */
  18111. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18112. if (this._masterMesh) {
  18113. return this._masterMesh._getWorldMatrixDeterminant();
  18114. }
  18115. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18116. };
  18117. // ================================== Point of View Movement =================================
  18118. /**
  18119. * Perform relative position change from the point of view of behind the front of the mesh.
  18120. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18121. * Supports definition of mesh facing forward or backward.
  18122. * @param {number} amountRight
  18123. * @param {number} amountUp
  18124. * @param {number} amountForward
  18125. *
  18126. * Returns the AbstractMesh.
  18127. */
  18128. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18129. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18130. return this;
  18131. };
  18132. /**
  18133. * Calculate relative position change from the point of view of behind the front of the mesh.
  18134. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18135. * Supports definition of mesh facing forward or backward.
  18136. * @param {number} amountRight
  18137. * @param {number} amountUp
  18138. * @param {number} amountForward
  18139. *
  18140. * Returns a new Vector3.
  18141. */
  18142. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18143. var rotMatrix = new BABYLON.Matrix();
  18144. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18145. rotQuaternion.toRotationMatrix(rotMatrix);
  18146. var translationDelta = BABYLON.Vector3.Zero();
  18147. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18149. return translationDelta;
  18150. };
  18151. // ================================== Point of View Rotation =================================
  18152. /**
  18153. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18154. * Supports definition of mesh facing forward or backward.
  18155. * @param {number} flipBack
  18156. * @param {number} twirlClockwise
  18157. * @param {number} tiltRight
  18158. *
  18159. * Returns the AbstractMesh.
  18160. */
  18161. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18162. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18163. return this;
  18164. };
  18165. /**
  18166. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18167. * Supports definition of mesh facing forward or backward.
  18168. * @param {number} flipBack
  18169. * @param {number} twirlClockwise
  18170. * @param {number} tiltRight
  18171. *
  18172. * Returns a new Vector3.
  18173. */
  18174. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18175. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18176. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18177. };
  18178. /**
  18179. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18180. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18181. */
  18182. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18183. if (includeDescendants === void 0) { includeDescendants = true; }
  18184. this.computeWorldMatrix(true);
  18185. var min;
  18186. var max;
  18187. var boundingInfo = this.getBoundingInfo();
  18188. if (!this.subMeshes) {
  18189. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18190. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18191. }
  18192. else {
  18193. min = boundingInfo.boundingBox.minimumWorld;
  18194. max = boundingInfo.boundingBox.maximumWorld;
  18195. }
  18196. if (includeDescendants) {
  18197. var descendants = this.getDescendants(false);
  18198. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18199. var descendant = descendants_1[_i];
  18200. var childMesh = descendant;
  18201. childMesh.computeWorldMatrix(true);
  18202. //make sure we have the needed params to get mix and max
  18203. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18204. continue;
  18205. }
  18206. var childBoundingInfo = childMesh.getBoundingInfo();
  18207. var boundingBox = childBoundingInfo.boundingBox;
  18208. var minBox = boundingBox.minimumWorld;
  18209. var maxBox = boundingBox.maximumWorld;
  18210. BABYLON.Tools.CheckExtends(minBox, min, max);
  18211. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18212. }
  18213. }
  18214. return {
  18215. min: min,
  18216. max: max
  18217. };
  18218. };
  18219. /**
  18220. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18221. * Returns the AbstractMesh.
  18222. */
  18223. AbstractMesh.prototype._updateBoundingInfo = function () {
  18224. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18225. this._boundingInfo.update(this.worldMatrixFromCache);
  18226. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18227. return this;
  18228. };
  18229. /**
  18230. * Update a mesh's children BoundingInfo objects only.
  18231. * Returns the AbstractMesh.
  18232. */
  18233. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18234. if (!this.subMeshes) {
  18235. return this;
  18236. }
  18237. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18238. var subMesh = this.subMeshes[subIndex];
  18239. if (!subMesh.IsGlobal) {
  18240. subMesh.updateBoundingInfo(matrix);
  18241. }
  18242. }
  18243. return this;
  18244. };
  18245. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18246. // Bounding info
  18247. this._updateBoundingInfo();
  18248. };
  18249. /**
  18250. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18251. * A mesh is in the frustum if its bounding box intersects the frustum.
  18252. * Boolean returned.
  18253. */
  18254. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18255. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18256. };
  18257. /**
  18258. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18259. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18260. * Boolean returned.
  18261. */
  18262. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18263. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18264. ;
  18265. };
  18266. /**
  18267. * True if the mesh intersects another mesh or a SolidParticle object.
  18268. * 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)
  18269. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18270. * Returns a boolean.
  18271. */
  18272. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18273. if (precise === void 0) { precise = false; }
  18274. if (!this._boundingInfo || !mesh._boundingInfo) {
  18275. return false;
  18276. }
  18277. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18278. return true;
  18279. }
  18280. if (includeDescendants) {
  18281. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18282. var child = _a[_i];
  18283. if (child.intersectsMesh(mesh, precise, true)) {
  18284. return true;
  18285. }
  18286. }
  18287. }
  18288. return false;
  18289. };
  18290. /**
  18291. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18292. * Returns a boolean.
  18293. */
  18294. AbstractMesh.prototype.intersectsPoint = function (point) {
  18295. if (!this._boundingInfo) {
  18296. return false;
  18297. }
  18298. return this._boundingInfo.intersectsPoint(point);
  18299. };
  18300. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18301. return this.physicsImpostor;
  18302. };
  18303. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18304. if (camera === void 0) { camera = null; }
  18305. if (!camera) {
  18306. camera = this.getScene().activeCamera;
  18307. }
  18308. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18309. };
  18310. /**
  18311. * Returns the distance from the mesh to the active camera.
  18312. * Returns a float.
  18313. */
  18314. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18315. if (camera === void 0) { camera = null; }
  18316. if (!camera) {
  18317. camera = this.getScene().activeCamera;
  18318. }
  18319. return this.absolutePosition.subtract(camera.position).length();
  18320. };
  18321. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18322. if (!this.physicsImpostor) {
  18323. return this;
  18324. }
  18325. this.physicsImpostor.applyImpulse(force, contactPoint);
  18326. return this;
  18327. };
  18328. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18329. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18330. return this;
  18331. }
  18332. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18333. mainPivot: pivot1,
  18334. connectedPivot: pivot2,
  18335. nativeParams: options
  18336. });
  18337. return this;
  18338. };
  18339. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18340. // Collisions
  18341. /**
  18342. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18343. * Default `false`.
  18344. */
  18345. get: function () {
  18346. return this._checkCollisions;
  18347. },
  18348. set: function (collisionEnabled) {
  18349. this._checkCollisions = collisionEnabled;
  18350. if (this.getScene().workerCollisions) {
  18351. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18352. }
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18358. /**
  18359. * Gets Collider object used to compute collisions (not physics)
  18360. */
  18361. get: function () {
  18362. return this._collider;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18368. var globalPosition = this.getAbsolutePosition();
  18369. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18370. if (!this._collider) {
  18371. this._collider = new BABYLON.Collider();
  18372. }
  18373. this._collider._radius = this.ellipsoid;
  18374. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18375. return this;
  18376. };
  18377. // Submeshes octree
  18378. /**
  18379. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18380. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18381. * Returns an Octree of submeshes.
  18382. */
  18383. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18384. if (maxCapacity === void 0) { maxCapacity = 64; }
  18385. if (maxDepth === void 0) { maxDepth = 2; }
  18386. if (!this._submeshesOctree) {
  18387. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18388. }
  18389. this.computeWorldMatrix(true);
  18390. var boundingInfo = this.getBoundingInfo();
  18391. // Update octree
  18392. var bbox = boundingInfo.boundingBox;
  18393. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18394. return this._submeshesOctree;
  18395. };
  18396. // Collisions
  18397. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18398. this._generatePointsArray();
  18399. if (!this._positions) {
  18400. return this;
  18401. }
  18402. // Transformation
  18403. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18404. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18405. subMesh._lastColliderWorldVertices = [];
  18406. subMesh._trianglePlanes = [];
  18407. var start = subMesh.verticesStart;
  18408. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18409. for (var i = start; i < end; i++) {
  18410. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18411. }
  18412. }
  18413. // Collide
  18414. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18415. if (collider.collisionFound) {
  18416. collider.collidedMesh = this;
  18417. }
  18418. return this;
  18419. };
  18420. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18421. var subMeshes;
  18422. var len;
  18423. // Octrees
  18424. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18425. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18426. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18427. len = intersections.length;
  18428. subMeshes = intersections.data;
  18429. }
  18430. else {
  18431. subMeshes = this.subMeshes;
  18432. len = subMeshes.length;
  18433. }
  18434. for (var index = 0; index < len; index++) {
  18435. var subMesh = subMeshes[index];
  18436. // Bounding test
  18437. if (len > 1 && !subMesh._checkCollision(collider))
  18438. continue;
  18439. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18440. }
  18441. return this;
  18442. };
  18443. AbstractMesh.prototype._checkCollision = function (collider) {
  18444. // Bounding box test
  18445. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18446. return this;
  18447. // Transformation matrix
  18448. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18449. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18450. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18451. return this;
  18452. };
  18453. // Picking
  18454. AbstractMesh.prototype._generatePointsArray = function () {
  18455. return false;
  18456. };
  18457. /**
  18458. * Checks if the passed Ray intersects with the mesh.
  18459. * Returns an object PickingInfo.
  18460. */
  18461. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18462. var pickingInfo = new BABYLON.PickingInfo();
  18463. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18464. return pickingInfo;
  18465. }
  18466. if (!this._generatePointsArray()) {
  18467. return pickingInfo;
  18468. }
  18469. var intersectInfo = null;
  18470. // Octrees
  18471. var subMeshes;
  18472. var len;
  18473. if (this._submeshesOctree && this.useOctreeForPicking) {
  18474. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18475. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18476. len = intersections.length;
  18477. subMeshes = intersections.data;
  18478. }
  18479. else {
  18480. subMeshes = this.subMeshes;
  18481. len = subMeshes.length;
  18482. }
  18483. for (var index = 0; index < len; index++) {
  18484. var subMesh = subMeshes[index];
  18485. // Bounding test
  18486. if (len > 1 && !subMesh.canIntersects(ray))
  18487. continue;
  18488. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18489. if (currentIntersectInfo) {
  18490. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18491. intersectInfo = currentIntersectInfo;
  18492. intersectInfo.subMeshId = index;
  18493. if (fastCheck) {
  18494. break;
  18495. }
  18496. }
  18497. }
  18498. }
  18499. if (intersectInfo) {
  18500. // Get picked point
  18501. var world = this.getWorldMatrix();
  18502. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18503. var direction = ray.direction.clone();
  18504. direction = direction.scale(intersectInfo.distance);
  18505. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18506. var pickedPoint = worldOrigin.add(worldDirection);
  18507. // Return result
  18508. pickingInfo.hit = true;
  18509. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18510. pickingInfo.pickedPoint = pickedPoint;
  18511. pickingInfo.pickedMesh = this;
  18512. pickingInfo.bu = intersectInfo.bu || 0;
  18513. pickingInfo.bv = intersectInfo.bv || 0;
  18514. pickingInfo.faceId = intersectInfo.faceId;
  18515. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18516. return pickingInfo;
  18517. }
  18518. return pickingInfo;
  18519. };
  18520. /**
  18521. * Clones the mesh, used by the class Mesh.
  18522. * Just returns `null` for an AbstractMesh.
  18523. */
  18524. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18525. return null;
  18526. };
  18527. /**
  18528. * Disposes all the mesh submeshes.
  18529. * Returns the AbstractMesh.
  18530. */
  18531. AbstractMesh.prototype.releaseSubMeshes = function () {
  18532. if (this.subMeshes) {
  18533. while (this.subMeshes.length) {
  18534. this.subMeshes[0].dispose();
  18535. }
  18536. }
  18537. else {
  18538. this.subMeshes = new Array();
  18539. }
  18540. return this;
  18541. };
  18542. /**
  18543. * Releases resources associated with this abstract mesh.
  18544. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18545. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18546. */
  18547. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18548. var _this = this;
  18549. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18550. var index;
  18551. // Smart Array Retainers.
  18552. this.getScene().freeActiveMeshes();
  18553. this.getScene().freeRenderingGroups();
  18554. // Action manager
  18555. if (this.actionManager !== undefined && this.actionManager !== null) {
  18556. this.actionManager.dispose();
  18557. this.actionManager = null;
  18558. }
  18559. // Skeleton
  18560. this.skeleton = null;
  18561. // Physics
  18562. if (this.physicsImpostor) {
  18563. this.physicsImpostor.dispose();
  18564. }
  18565. // Intersections in progress
  18566. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18567. var other = this._intersectionsInProgress[index];
  18568. var pos = other._intersectionsInProgress.indexOf(this);
  18569. other._intersectionsInProgress.splice(pos, 1);
  18570. }
  18571. this._intersectionsInProgress = [];
  18572. // Lights
  18573. var lights = this.getScene().lights;
  18574. lights.forEach(function (light) {
  18575. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18576. if (meshIndex !== -1) {
  18577. light.includedOnlyMeshes.splice(meshIndex, 1);
  18578. }
  18579. meshIndex = light.excludedMeshes.indexOf(_this);
  18580. if (meshIndex !== -1) {
  18581. light.excludedMeshes.splice(meshIndex, 1);
  18582. }
  18583. // Shadow generators
  18584. var generator = light.getShadowGenerator();
  18585. if (generator) {
  18586. var shadowMap = generator.getShadowMap();
  18587. if (shadowMap && shadowMap.renderList) {
  18588. meshIndex = shadowMap.renderList.indexOf(_this);
  18589. if (meshIndex !== -1) {
  18590. shadowMap.renderList.splice(meshIndex, 1);
  18591. }
  18592. }
  18593. }
  18594. });
  18595. // Edges
  18596. if (this._edgesRenderer) {
  18597. this._edgesRenderer.dispose();
  18598. this._edgesRenderer = null;
  18599. }
  18600. // SubMeshes
  18601. if (this.getClassName() !== "InstancedMesh") {
  18602. this.releaseSubMeshes();
  18603. }
  18604. // Octree
  18605. var sceneOctree = this.getScene().selectionOctree;
  18606. if (sceneOctree !== undefined && sceneOctree !== null) {
  18607. var index = sceneOctree.dynamicContent.indexOf(this);
  18608. if (index !== -1) {
  18609. sceneOctree.dynamicContent.splice(index, 1);
  18610. }
  18611. }
  18612. // Query
  18613. var engine = this.getScene().getEngine();
  18614. if (this._occlusionQuery) {
  18615. this._isOcclusionQueryInProgress = false;
  18616. engine.deleteQuery(this._occlusionQuery);
  18617. this._occlusionQuery = null;
  18618. }
  18619. // Engine
  18620. engine.wipeCaches();
  18621. // Remove from scene
  18622. this.getScene().removeMesh(this);
  18623. if (disposeMaterialAndTextures) {
  18624. if (this.material) {
  18625. this.material.dispose(false, true);
  18626. }
  18627. }
  18628. if (!doNotRecurse) {
  18629. // Particles
  18630. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18631. if (this.getScene().particleSystems[index].emitter === this) {
  18632. this.getScene().particleSystems[index].dispose();
  18633. index--;
  18634. }
  18635. }
  18636. }
  18637. // facet data
  18638. if (this._facetDataEnabled) {
  18639. this.disableFacetData();
  18640. }
  18641. this.onAfterWorldMatrixUpdateObservable.clear();
  18642. this.onCollideObservable.clear();
  18643. this.onCollisionPositionChangeObservable.clear();
  18644. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18645. };
  18646. /**
  18647. * Adds the passed mesh as a child to the current mesh.
  18648. * Returns the AbstractMesh.
  18649. */
  18650. AbstractMesh.prototype.addChild = function (mesh) {
  18651. mesh.setParent(this);
  18652. return this;
  18653. };
  18654. /**
  18655. * Removes the passed mesh from the current mesh children list.
  18656. * Returns the AbstractMesh.
  18657. */
  18658. AbstractMesh.prototype.removeChild = function (mesh) {
  18659. mesh.setParent(null);
  18660. return this;
  18661. };
  18662. // Facet data
  18663. /**
  18664. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18665. * Returns the AbstractMesh.
  18666. */
  18667. AbstractMesh.prototype._initFacetData = function () {
  18668. if (!this._facetNormals) {
  18669. this._facetNormals = new Array();
  18670. }
  18671. if (!this._facetPositions) {
  18672. this._facetPositions = new Array();
  18673. }
  18674. if (!this._facetPartitioning) {
  18675. this._facetPartitioning = new Array();
  18676. }
  18677. this._facetNb = (this.getIndices().length / 3) | 0;
  18678. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18679. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18680. for (var f = 0; f < this._facetNb; f++) {
  18681. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18682. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18683. }
  18684. this._facetDataEnabled = true;
  18685. return this;
  18686. };
  18687. /**
  18688. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18689. * This method can be called within the render loop.
  18690. * 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.
  18691. * Returns the AbstractMesh.
  18692. */
  18693. AbstractMesh.prototype.updateFacetData = function () {
  18694. if (!this._facetDataEnabled) {
  18695. this._initFacetData();
  18696. }
  18697. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18698. var indices = this.getIndices();
  18699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18700. var bInfo = this.getBoundingInfo();
  18701. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18702. // init arrays, matrix and sort function on first call
  18703. this._facetDepthSortEnabled = true;
  18704. if (indices instanceof Uint16Array) {
  18705. this._depthSortedIndices = new Uint16Array(indices);
  18706. }
  18707. else if (indices instanceof Uint32Array) {
  18708. this._depthSortedIndices = new Uint32Array(indices);
  18709. }
  18710. else {
  18711. var needs32bits = false;
  18712. for (var i = 0; i < indices.length; i++) {
  18713. if (indices[i] > 65535) {
  18714. needs32bits = true;
  18715. break;
  18716. }
  18717. }
  18718. if (needs32bits) {
  18719. this._depthSortedIndices = new Uint32Array(indices);
  18720. }
  18721. else {
  18722. this._depthSortedIndices = new Uint16Array(indices);
  18723. }
  18724. }
  18725. this._facetDepthSortFunction = function (f1, f2) {
  18726. return (f2.sqDistance - f1.sqDistance);
  18727. };
  18728. if (!this._facetDepthSortFrom) {
  18729. var camera = this.getScene().activeCamera;
  18730. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18731. }
  18732. this._depthSortedFacets = [];
  18733. for (var f = 0; f < this._facetNb; f++) {
  18734. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18735. this._depthSortedFacets.push(depthSortedFacet);
  18736. }
  18737. this._invertedMatrix = BABYLON.Matrix.Identity();
  18738. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18739. }
  18740. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18741. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18742. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18743. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18744. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18745. this._subDiv.max = this._partitioningSubdivisions;
  18746. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18747. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18748. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18749. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18750. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18751. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18752. // set the parameters for ComputeNormals()
  18753. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18754. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18755. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18756. this._facetParameters.bInfo = bInfo;
  18757. this._facetParameters.bbSize = this._bbSize;
  18758. this._facetParameters.subDiv = this._subDiv;
  18759. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18760. this._facetParameters.depthSort = this._facetDepthSort;
  18761. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18762. this.computeWorldMatrix(true);
  18763. this._worldMatrix.invertToRef(this._invertedMatrix);
  18764. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18765. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18766. }
  18767. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18768. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18769. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18770. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18771. var l = (this._depthSortedIndices.length / 3) | 0;
  18772. for (var f = 0; f < l; f++) {
  18773. var sind = this._depthSortedFacets[f].ind;
  18774. this._depthSortedIndices[f * 3] = indices[sind];
  18775. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18776. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18777. }
  18778. this.updateIndices(this._depthSortedIndices);
  18779. }
  18780. return this;
  18781. };
  18782. /**
  18783. * Returns the facetLocalNormals array.
  18784. * The normals are expressed in the mesh local space.
  18785. */
  18786. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18787. if (!this._facetNormals) {
  18788. this.updateFacetData();
  18789. }
  18790. return this._facetNormals;
  18791. };
  18792. /**
  18793. * Returns the facetLocalPositions array.
  18794. * The facet positions are expressed in the mesh local space.
  18795. */
  18796. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18797. if (!this._facetPositions) {
  18798. this.updateFacetData();
  18799. }
  18800. return this._facetPositions;
  18801. };
  18802. /**
  18803. * Returns the facetLocalPartioning array.
  18804. */
  18805. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18806. if (!this._facetPartitioning) {
  18807. this.updateFacetData();
  18808. }
  18809. return this._facetPartitioning;
  18810. };
  18811. /**
  18812. * Returns the i-th facet position in the world system.
  18813. * This method allocates a new Vector3 per call.
  18814. */
  18815. AbstractMesh.prototype.getFacetPosition = function (i) {
  18816. var pos = BABYLON.Vector3.Zero();
  18817. this.getFacetPositionToRef(i, pos);
  18818. return pos;
  18819. };
  18820. /**
  18821. * Sets the reference Vector3 with the i-th facet position in the world system.
  18822. * Returns the AbstractMesh.
  18823. */
  18824. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18825. var localPos = (this.getFacetLocalPositions())[i];
  18826. var world = this.getWorldMatrix();
  18827. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18828. return this;
  18829. };
  18830. /**
  18831. * Returns the i-th facet normal in the world system.
  18832. * This method allocates a new Vector3 per call.
  18833. */
  18834. AbstractMesh.prototype.getFacetNormal = function (i) {
  18835. var norm = BABYLON.Vector3.Zero();
  18836. this.getFacetNormalToRef(i, norm);
  18837. return norm;
  18838. };
  18839. /**
  18840. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18841. * Returns the AbstractMesh.
  18842. */
  18843. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18844. var localNorm = (this.getFacetLocalNormals())[i];
  18845. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18846. return this;
  18847. };
  18848. /**
  18849. * 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).
  18850. */
  18851. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18852. var bInfo = this.getBoundingInfo();
  18853. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18854. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18855. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18856. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18857. return null;
  18858. }
  18859. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18860. };
  18861. /**
  18862. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18863. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18864. * 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.
  18865. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18866. * 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.
  18867. */
  18868. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18869. if (checkFace === void 0) { checkFace = false; }
  18870. if (facing === void 0) { facing = true; }
  18871. var world = this.getWorldMatrix();
  18872. var invMat = BABYLON.Tmp.Matrix[5];
  18873. world.invertToRef(invMat);
  18874. var invVect = BABYLON.Tmp.Vector3[8];
  18875. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18876. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18877. if (projected) {
  18878. // tranform the local computed projected vector to world coordinates
  18879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18880. }
  18881. return closest;
  18882. };
  18883. /**
  18884. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18885. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18886. * 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.
  18887. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18888. * 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.
  18889. */
  18890. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18891. if (checkFace === void 0) { checkFace = false; }
  18892. if (facing === void 0) { facing = true; }
  18893. var closest = null;
  18894. var tmpx = 0.0;
  18895. var tmpy = 0.0;
  18896. var tmpz = 0.0;
  18897. var d = 0.0; // tmp dot facet normal * facet position
  18898. var t0 = 0.0;
  18899. var projx = 0.0;
  18900. var projy = 0.0;
  18901. var projz = 0.0;
  18902. // Get all the facets in the same partitioning block than (x, y, z)
  18903. var facetPositions = this.getFacetLocalPositions();
  18904. var facetNormals = this.getFacetLocalNormals();
  18905. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18906. if (!facetsInBlock) {
  18907. return null;
  18908. }
  18909. // Get the closest facet to (x, y, z)
  18910. var shortest = Number.MAX_VALUE; // init distance vars
  18911. var tmpDistance = shortest;
  18912. var fib; // current facet in the block
  18913. var norm; // current facet normal
  18914. var p0; // current facet barycenter position
  18915. // loop on all the facets in the current partitioning block
  18916. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18917. fib = facetsInBlock[idx];
  18918. norm = facetNormals[fib];
  18919. p0 = facetPositions[fib];
  18920. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18921. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18922. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18923. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18924. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18925. projx = x + norm.x * t0;
  18926. projy = y + norm.y * t0;
  18927. projz = z + norm.z * t0;
  18928. tmpx = projx - x;
  18929. tmpy = projy - y;
  18930. tmpz = projz - z;
  18931. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18932. if (tmpDistance < shortest) {
  18933. shortest = tmpDistance;
  18934. closest = fib;
  18935. if (projected) {
  18936. projected.x = projx;
  18937. projected.y = projy;
  18938. projected.z = projz;
  18939. }
  18940. }
  18941. }
  18942. }
  18943. return closest;
  18944. };
  18945. /**
  18946. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18947. */
  18948. AbstractMesh.prototype.getFacetDataParameters = function () {
  18949. return this._facetParameters;
  18950. };
  18951. /**
  18952. * Disables the feature FacetData and frees the related memory.
  18953. * Returns the AbstractMesh.
  18954. */
  18955. AbstractMesh.prototype.disableFacetData = function () {
  18956. if (this._facetDataEnabled) {
  18957. this._facetDataEnabled = false;
  18958. this._facetPositions = new Array();
  18959. this._facetNormals = new Array();
  18960. this._facetPartitioning = new Array();
  18961. this._facetParameters = null;
  18962. this._depthSortedIndices = new Uint32Array(0);
  18963. }
  18964. return this;
  18965. };
  18966. /**
  18967. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18968. * Returns the mesh.
  18969. */
  18970. AbstractMesh.prototype.updateIndices = function (indices) {
  18971. return this;
  18972. };
  18973. /**
  18974. * The mesh Geometry. Actually used by the Mesh object.
  18975. * Returns a blank geometry object.
  18976. */
  18977. /**
  18978. * Creates new normals data for the mesh.
  18979. * @param updatable.
  18980. */
  18981. AbstractMesh.prototype.createNormals = function (updatable) {
  18982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18983. var indices = this.getIndices();
  18984. var normals;
  18985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18986. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18987. }
  18988. else {
  18989. normals = [];
  18990. }
  18991. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18992. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18993. };
  18994. /**
  18995. * Align the mesh with a normal.
  18996. * Returns the mesh.
  18997. */
  18998. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18999. if (!upDirection) {
  19000. upDirection = BABYLON.Axis.Y;
  19001. }
  19002. var axisX = BABYLON.Tmp.Vector3[0];
  19003. var axisZ = BABYLON.Tmp.Vector3[1];
  19004. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19005. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19006. if (this.rotationQuaternion) {
  19007. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19008. }
  19009. else {
  19010. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19011. }
  19012. return this;
  19013. };
  19014. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19015. var engine = this.getEngine();
  19016. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19017. this._isOccluded = false;
  19018. return;
  19019. }
  19020. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19021. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19022. if (isOcclusionQueryAvailable) {
  19023. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19024. this._isOcclusionQueryInProgress = false;
  19025. this._occlusionInternalRetryCounter = 0;
  19026. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19027. }
  19028. else {
  19029. this._occlusionInternalRetryCounter++;
  19030. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19031. this._isOcclusionQueryInProgress = false;
  19032. this._occlusionInternalRetryCounter = 0;
  19033. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19034. // if strict continue the last state of the object.
  19035. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19036. }
  19037. else {
  19038. return;
  19039. }
  19040. }
  19041. }
  19042. var scene = this.getScene();
  19043. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19044. if (!this._occlusionQuery) {
  19045. this._occlusionQuery = engine.createQuery();
  19046. }
  19047. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19048. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19049. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19050. this._isOcclusionQueryInProgress = true;
  19051. };
  19052. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19053. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19054. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19055. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19056. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19057. return AbstractMesh;
  19058. }(BABYLON.TransformNode));
  19059. BABYLON.AbstractMesh = AbstractMesh;
  19060. })(BABYLON || (BABYLON = {}));
  19061. //# sourceMappingURL=babylon.abstractMesh.js.map
  19062. var BABYLON;
  19063. (function (BABYLON) {
  19064. /**
  19065. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19066. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19067. * 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.
  19068. */
  19069. var Light = /** @class */ (function (_super) {
  19070. __extends(Light, _super);
  19071. /**
  19072. * Creates a Light object in the scene.
  19073. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19074. * @param name The firendly name of the light
  19075. * @param scene The scene the light belongs too
  19076. */
  19077. function Light(name, scene) {
  19078. var _this = _super.call(this, name, scene) || this;
  19079. /**
  19080. * Diffuse gives the basic color to an object.
  19081. */
  19082. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19083. /**
  19084. * Specular produces a highlight color on an object.
  19085. * Note: This is note affecting PBR materials.
  19086. */
  19087. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19088. /**
  19089. * Strength of the light.
  19090. * Note: By default it is define in the framework own unit.
  19091. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19092. */
  19093. _this.intensity = 1.0;
  19094. /**
  19095. * Defines how far from the source the light is impacting in scene units.
  19096. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19097. */
  19098. _this.range = Number.MAX_VALUE;
  19099. /**
  19100. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19101. * of light.
  19102. */
  19103. _this._photometricScale = 1.0;
  19104. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19105. _this._radius = 0.00001;
  19106. /**
  19107. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19108. * exceeding the number allowed of the materials.
  19109. */
  19110. _this.renderPriority = 0;
  19111. /**
  19112. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19113. * the current shadow generator.
  19114. */
  19115. _this.shadowEnabled = true;
  19116. _this._excludeWithLayerMask = 0;
  19117. _this._includeOnlyWithLayerMask = 0;
  19118. _this._lightmapMode = 0;
  19119. /**
  19120. * @ignore Internal use only.
  19121. */
  19122. _this._excludedMeshesIds = new Array();
  19123. /**
  19124. * @ignore Internal use only.
  19125. */
  19126. _this._includedOnlyMeshesIds = new Array();
  19127. _this.getScene().addLight(_this);
  19128. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19129. _this._buildUniformLayout();
  19130. _this.includedOnlyMeshes = new Array();
  19131. _this.excludedMeshes = new Array();
  19132. _this._resyncMeshes();
  19133. return _this;
  19134. }
  19135. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19136. /**
  19137. * If every light affecting the material is in this lightmapMode,
  19138. * material.lightmapTexture adds or multiplies
  19139. * (depends on material.useLightmapAsShadowmap)
  19140. * after every other light calculations.
  19141. */
  19142. get: function () {
  19143. return Light._LIGHTMAP_DEFAULT;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19149. /**
  19150. * material.lightmapTexture as only diffuse lighting from this light
  19151. * adds only specular lighting from this light
  19152. * adds dynamic shadows
  19153. */
  19154. get: function () {
  19155. return Light._LIGHTMAP_SPECULAR;
  19156. },
  19157. enumerable: true,
  19158. configurable: true
  19159. });
  19160. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19161. /**
  19162. * material.lightmapTexture as only lighting
  19163. * no light calculation from this light
  19164. * only adds dynamic shadows from this light
  19165. */
  19166. get: function () {
  19167. return Light._LIGHTMAP_SHADOWSONLY;
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19173. /**
  19174. * Each light type uses the default quantity according to its type:
  19175. * point/spot lights use luminous intensity
  19176. * directional lights use illuminance
  19177. */
  19178. get: function () {
  19179. return Light._INTENSITYMODE_AUTOMATIC;
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19185. /**
  19186. * lumen (lm)
  19187. */
  19188. get: function () {
  19189. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19190. },
  19191. enumerable: true,
  19192. configurable: true
  19193. });
  19194. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19195. /**
  19196. * candela (lm/sr)
  19197. */
  19198. get: function () {
  19199. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19200. },
  19201. enumerable: true,
  19202. configurable: true
  19203. });
  19204. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19205. /**
  19206. * lux (lm/m^2)
  19207. */
  19208. get: function () {
  19209. return Light._INTENSITYMODE_ILLUMINANCE;
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19215. /**
  19216. * nit (cd/m^2)
  19217. */
  19218. get: function () {
  19219. return Light._INTENSITYMODE_LUMINANCE;
  19220. },
  19221. enumerable: true,
  19222. configurable: true
  19223. });
  19224. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19225. /**
  19226. * Light type const id of the point light.
  19227. */
  19228. get: function () {
  19229. return Light._LIGHTTYPEID_POINTLIGHT;
  19230. },
  19231. enumerable: true,
  19232. configurable: true
  19233. });
  19234. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19235. /**
  19236. * Light type const id of the directional light.
  19237. */
  19238. get: function () {
  19239. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19240. },
  19241. enumerable: true,
  19242. configurable: true
  19243. });
  19244. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19245. /**
  19246. * Light type const id of the spot light.
  19247. */
  19248. get: function () {
  19249. return Light._LIGHTTYPEID_SPOTLIGHT;
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19255. /**
  19256. * Light type const id of the hemispheric light.
  19257. */
  19258. get: function () {
  19259. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19260. },
  19261. enumerable: true,
  19262. configurable: true
  19263. });
  19264. Object.defineProperty(Light.prototype, "intensityMode", {
  19265. /**
  19266. * Gets the photometric scale used to interpret the intensity.
  19267. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19268. */
  19269. get: function () {
  19270. return this._intensityMode;
  19271. },
  19272. /**
  19273. * Sets the photometric scale used to interpret the intensity.
  19274. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19275. */
  19276. set: function (value) {
  19277. this._intensityMode = value;
  19278. this._computePhotometricScale();
  19279. },
  19280. enumerable: true,
  19281. configurable: true
  19282. });
  19283. ;
  19284. ;
  19285. Object.defineProperty(Light.prototype, "radius", {
  19286. /**
  19287. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19288. */
  19289. get: function () {
  19290. return this._radius;
  19291. },
  19292. /**
  19293. * sets the light radius used by PBR Materials to simulate soft area lights.
  19294. */
  19295. set: function (value) {
  19296. this._radius = value;
  19297. this._computePhotometricScale();
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. ;
  19303. ;
  19304. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19305. /**
  19306. * Gets the only meshes impacted by this light.
  19307. */
  19308. get: function () {
  19309. return this._includedOnlyMeshes;
  19310. },
  19311. /**
  19312. * Sets the only meshes impacted by this light.
  19313. */
  19314. set: function (value) {
  19315. this._includedOnlyMeshes = value;
  19316. this._hookArrayForIncludedOnly(value);
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19322. /**
  19323. * Gets the meshes not impacted by this light.
  19324. */
  19325. get: function () {
  19326. return this._excludedMeshes;
  19327. },
  19328. /**
  19329. * Sets the meshes not impacted by this light.
  19330. */
  19331. set: function (value) {
  19332. this._excludedMeshes = value;
  19333. this._hookArrayForExcluded(value);
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19339. /**
  19340. * Gets the layer id use to find what meshes are not impacted by the light.
  19341. * Inactive if 0
  19342. */
  19343. get: function () {
  19344. return this._excludeWithLayerMask;
  19345. },
  19346. /**
  19347. * Sets the layer id use to find what meshes are not impacted by the light.
  19348. * Inactive if 0
  19349. */
  19350. set: function (value) {
  19351. this._excludeWithLayerMask = value;
  19352. this._resyncMeshes();
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19358. /**
  19359. * Gets the layer id use to find what meshes are impacted by the light.
  19360. * Inactive if 0
  19361. */
  19362. get: function () {
  19363. return this._includeOnlyWithLayerMask;
  19364. },
  19365. /**
  19366. * Sets the layer id use to find what meshes are impacted by the light.
  19367. * Inactive if 0
  19368. */
  19369. set: function (value) {
  19370. this._includeOnlyWithLayerMask = value;
  19371. this._resyncMeshes();
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Light.prototype, "lightmapMode", {
  19377. /**
  19378. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19379. */
  19380. get: function () {
  19381. return this._lightmapMode;
  19382. },
  19383. /**
  19384. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19385. */
  19386. set: function (value) {
  19387. if (this._lightmapMode === value) {
  19388. return;
  19389. }
  19390. this._lightmapMode = value;
  19391. this._markMeshesAsLightDirty();
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. /**
  19397. * Returns the string "Light".
  19398. * @returns the class name
  19399. */
  19400. Light.prototype.getClassName = function () {
  19401. return "Light";
  19402. };
  19403. /**
  19404. * Converts the light information to a readable string for debug purpose.
  19405. * @param fullDetails Supports for multiple levels of logging within scene loading
  19406. * @returns the human readable light info
  19407. */
  19408. Light.prototype.toString = function (fullDetails) {
  19409. var ret = "Name: " + this.name;
  19410. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19411. if (this.animations) {
  19412. for (var i = 0; i < this.animations.length; i++) {
  19413. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19414. }
  19415. }
  19416. if (fullDetails) {
  19417. }
  19418. return ret;
  19419. };
  19420. /**
  19421. * Set the enabled state of this node.
  19422. * @param value - the new enabled state
  19423. * @see isEnabled
  19424. */
  19425. Light.prototype.setEnabled = function (value) {
  19426. _super.prototype.setEnabled.call(this, value);
  19427. this._resyncMeshes();
  19428. };
  19429. /**
  19430. * Returns the Light associated shadow generator if any.
  19431. * @return the associated shadow generator.
  19432. */
  19433. Light.prototype.getShadowGenerator = function () {
  19434. return this._shadowGenerator;
  19435. };
  19436. /**
  19437. * Returns a Vector3, the absolute light position in the World.
  19438. * @returns the world space position of the light
  19439. */
  19440. Light.prototype.getAbsolutePosition = function () {
  19441. return BABYLON.Vector3.Zero();
  19442. };
  19443. /**
  19444. * Specifies if the light will affect the passed mesh.
  19445. * @param mesh The mesh to test against the light
  19446. * @return true the mesh is affected otherwise, false.
  19447. */
  19448. Light.prototype.canAffectMesh = function (mesh) {
  19449. if (!mesh) {
  19450. return true;
  19451. }
  19452. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19453. return false;
  19454. }
  19455. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19456. return false;
  19457. }
  19458. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19459. return false;
  19460. }
  19461. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19462. return false;
  19463. }
  19464. return true;
  19465. };
  19466. /**
  19467. * Computes and Returns the light World matrix.
  19468. * @returns the world matrix
  19469. */
  19470. Light.prototype.getWorldMatrix = function () {
  19471. this._currentRenderId = this.getScene().getRenderId();
  19472. var worldMatrix = this._getWorldMatrix();
  19473. if (this.parent && this.parent.getWorldMatrix) {
  19474. if (!this._parentedWorldMatrix) {
  19475. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19476. }
  19477. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19478. this._markSyncedWithParent();
  19479. return this._parentedWorldMatrix;
  19480. }
  19481. return worldMatrix;
  19482. };
  19483. /**
  19484. * Sort function to order lights for rendering.
  19485. * @param a First Light object to compare to second.
  19486. * @param b Second Light object to compare first.
  19487. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19488. */
  19489. Light.CompareLightsPriority = function (a, b) {
  19490. //shadow-casting lights have priority over non-shadow-casting lights
  19491. //the renderPrioirty is a secondary sort criterion
  19492. if (a.shadowEnabled !== b.shadowEnabled) {
  19493. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19494. }
  19495. return b.renderPriority - a.renderPriority;
  19496. };
  19497. /**
  19498. * Releases resources associated with this node.
  19499. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19500. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19501. */
  19502. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19504. if (this._shadowGenerator) {
  19505. this._shadowGenerator.dispose();
  19506. this._shadowGenerator = null;
  19507. }
  19508. // Animations
  19509. this.getScene().stopAnimation(this);
  19510. // Remove from meshes
  19511. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19512. var mesh = _a[_i];
  19513. mesh._removeLightSource(this);
  19514. }
  19515. this._uniformBuffer.dispose();
  19516. // Remove from scene
  19517. this.getScene().removeLight(this);
  19518. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19519. };
  19520. /**
  19521. * Returns the light type ID (integer).
  19522. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19523. */
  19524. Light.prototype.getTypeID = function () {
  19525. return 0;
  19526. };
  19527. /**
  19528. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19529. * @returns the scaled intensity in intensity mode unit
  19530. */
  19531. Light.prototype.getScaledIntensity = function () {
  19532. return this._photometricScale * this.intensity;
  19533. };
  19534. /**
  19535. * Returns a new Light object, named "name", from the current one.
  19536. * @param name The name of the cloned light
  19537. * @returns the new created light
  19538. */
  19539. Light.prototype.clone = function (name) {
  19540. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19541. if (!constructor) {
  19542. return null;
  19543. }
  19544. return BABYLON.SerializationHelper.Clone(constructor, this);
  19545. };
  19546. /**
  19547. * Serializes the current light into a Serialization object.
  19548. * @returns the serialized object.
  19549. */
  19550. Light.prototype.serialize = function () {
  19551. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19552. // Type
  19553. serializationObject.type = this.getTypeID();
  19554. // Parent
  19555. if (this.parent) {
  19556. serializationObject.parentId = this.parent.id;
  19557. }
  19558. // Inclusion / exclusions
  19559. if (this.excludedMeshes.length > 0) {
  19560. serializationObject.excludedMeshesIds = [];
  19561. this.excludedMeshes.forEach(function (mesh) {
  19562. serializationObject.excludedMeshesIds.push(mesh.id);
  19563. });
  19564. }
  19565. if (this.includedOnlyMeshes.length > 0) {
  19566. serializationObject.includedOnlyMeshesIds = [];
  19567. this.includedOnlyMeshes.forEach(function (mesh) {
  19568. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19569. });
  19570. }
  19571. // Animations
  19572. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19573. serializationObject.ranges = this.serializeAnimationRanges();
  19574. return serializationObject;
  19575. };
  19576. /**
  19577. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19578. * This new light is named "name" and added to the passed scene.
  19579. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19580. * @param name The friendly name of the light
  19581. * @param scene The scene the new light will belong to
  19582. * @returns the constructor function
  19583. */
  19584. Light.GetConstructorFromName = function (type, name, scene) {
  19585. switch (type) {
  19586. case 0:
  19587. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19588. case 1:
  19589. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19590. case 2:
  19591. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19592. case 3:
  19593. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19594. }
  19595. return null;
  19596. };
  19597. /**
  19598. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19599. * @param parsedLight The JSON representation of the light
  19600. * @param scene The scene to create the parsed light in
  19601. * @returns the created light after parsing
  19602. */
  19603. Light.Parse = function (parsedLight, scene) {
  19604. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19605. if (!constructor) {
  19606. return null;
  19607. }
  19608. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19609. // Inclusion / exclusions
  19610. if (parsedLight.excludedMeshesIds) {
  19611. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19612. }
  19613. if (parsedLight.includedOnlyMeshesIds) {
  19614. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19615. }
  19616. // Parent
  19617. if (parsedLight.parentId) {
  19618. light._waitingParentId = parsedLight.parentId;
  19619. }
  19620. // Animations
  19621. if (parsedLight.animations) {
  19622. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19623. var parsedAnimation = parsedLight.animations[animationIndex];
  19624. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19625. }
  19626. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19627. }
  19628. if (parsedLight.autoAnimate) {
  19629. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19630. }
  19631. return light;
  19632. };
  19633. Light.prototype._hookArrayForExcluded = function (array) {
  19634. var _this = this;
  19635. var oldPush = array.push;
  19636. array.push = function () {
  19637. var items = [];
  19638. for (var _i = 0; _i < arguments.length; _i++) {
  19639. items[_i] = arguments[_i];
  19640. }
  19641. var result = oldPush.apply(array, items);
  19642. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19643. var item = items_1[_a];
  19644. item._resyncLighSource(_this);
  19645. }
  19646. return result;
  19647. };
  19648. var oldSplice = array.splice;
  19649. array.splice = function (index, deleteCount) {
  19650. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19651. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19652. var item = deleted_1[_i];
  19653. item._resyncLighSource(_this);
  19654. }
  19655. return deleted;
  19656. };
  19657. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19658. var item = array_1[_i];
  19659. item._resyncLighSource(this);
  19660. }
  19661. };
  19662. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19663. var _this = this;
  19664. var oldPush = array.push;
  19665. array.push = function () {
  19666. var items = [];
  19667. for (var _i = 0; _i < arguments.length; _i++) {
  19668. items[_i] = arguments[_i];
  19669. }
  19670. var result = oldPush.apply(array, items);
  19671. _this._resyncMeshes();
  19672. return result;
  19673. };
  19674. var oldSplice = array.splice;
  19675. array.splice = function (index, deleteCount) {
  19676. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19677. _this._resyncMeshes();
  19678. return deleted;
  19679. };
  19680. this._resyncMeshes();
  19681. };
  19682. Light.prototype._resyncMeshes = function () {
  19683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19684. var mesh = _a[_i];
  19685. mesh._resyncLighSource(this);
  19686. }
  19687. };
  19688. /**
  19689. * Forces the meshes to update their light related information in their rendering used effects
  19690. * @ignore Internal Use Only
  19691. */
  19692. Light.prototype._markMeshesAsLightDirty = function () {
  19693. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19694. var mesh = _a[_i];
  19695. if (mesh._lightSources.indexOf(this) !== -1) {
  19696. mesh._markSubMeshesAsLightDirty();
  19697. }
  19698. }
  19699. };
  19700. /**
  19701. * Recomputes the cached photometric scale if needed.
  19702. */
  19703. Light.prototype._computePhotometricScale = function () {
  19704. this._photometricScale = this._getPhotometricScale();
  19705. this.getScene().resetCachedMaterial();
  19706. };
  19707. /**
  19708. * Returns the Photometric Scale according to the light type and intensity mode.
  19709. */
  19710. Light.prototype._getPhotometricScale = function () {
  19711. var photometricScale = 0.0;
  19712. var lightTypeID = this.getTypeID();
  19713. //get photometric mode
  19714. var photometricMode = this.intensityMode;
  19715. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19716. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19717. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19718. }
  19719. else {
  19720. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19721. }
  19722. }
  19723. //compute photometric scale
  19724. switch (lightTypeID) {
  19725. case Light.LIGHTTYPEID_POINTLIGHT:
  19726. case Light.LIGHTTYPEID_SPOTLIGHT:
  19727. switch (photometricMode) {
  19728. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19729. photometricScale = 1.0 / (4.0 * Math.PI);
  19730. break;
  19731. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19732. photometricScale = 1.0;
  19733. break;
  19734. case Light.INTENSITYMODE_LUMINANCE:
  19735. photometricScale = this.radius * this.radius;
  19736. break;
  19737. }
  19738. break;
  19739. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19740. switch (photometricMode) {
  19741. case Light.INTENSITYMODE_ILLUMINANCE:
  19742. photometricScale = 1.0;
  19743. break;
  19744. case Light.INTENSITYMODE_LUMINANCE:
  19745. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19746. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19747. var apexAngleRadians = this.radius;
  19748. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19749. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19750. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19751. photometricScale = solidAngle;
  19752. break;
  19753. }
  19754. break;
  19755. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19756. // No fall off in hemisperic light.
  19757. photometricScale = 1.0;
  19758. break;
  19759. }
  19760. return photometricScale;
  19761. };
  19762. /**
  19763. * Reorder the light in the scene according to their defined priority.
  19764. * @ignore Internal Use Only
  19765. */
  19766. Light.prototype._reorderLightsInScene = function () {
  19767. var scene = this.getScene();
  19768. if (this._renderPriority != 0) {
  19769. scene.requireLightSorting = true;
  19770. }
  19771. this.getScene().sortLightsByPriority();
  19772. };
  19773. //lightmapMode Consts
  19774. Light._LIGHTMAP_DEFAULT = 0;
  19775. Light._LIGHTMAP_SPECULAR = 1;
  19776. Light._LIGHTMAP_SHADOWSONLY = 2;
  19777. // Intensity Mode Consts
  19778. Light._INTENSITYMODE_AUTOMATIC = 0;
  19779. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19780. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19781. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19782. Light._INTENSITYMODE_LUMINANCE = 4;
  19783. // Light types ids const.
  19784. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19785. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19786. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19787. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19788. __decorate([
  19789. BABYLON.serializeAsColor3()
  19790. ], Light.prototype, "diffuse", void 0);
  19791. __decorate([
  19792. BABYLON.serializeAsColor3()
  19793. ], Light.prototype, "specular", void 0);
  19794. __decorate([
  19795. BABYLON.serialize()
  19796. ], Light.prototype, "intensity", void 0);
  19797. __decorate([
  19798. BABYLON.serialize()
  19799. ], Light.prototype, "range", void 0);
  19800. __decorate([
  19801. BABYLON.serialize()
  19802. ], Light.prototype, "intensityMode", null);
  19803. __decorate([
  19804. BABYLON.serialize()
  19805. ], Light.prototype, "radius", null);
  19806. __decorate([
  19807. BABYLON.serialize()
  19808. ], Light.prototype, "_renderPriority", void 0);
  19809. __decorate([
  19810. BABYLON.expandToProperty("_reorderLightsInScene")
  19811. ], Light.prototype, "renderPriority", void 0);
  19812. __decorate([
  19813. BABYLON.serialize()
  19814. ], Light.prototype, "shadowEnabled", void 0);
  19815. __decorate([
  19816. BABYLON.serialize("excludeWithLayerMask")
  19817. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19818. __decorate([
  19819. BABYLON.serialize("includeOnlyWithLayerMask")
  19820. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19821. __decorate([
  19822. BABYLON.serialize("lightmapMode")
  19823. ], Light.prototype, "_lightmapMode", void 0);
  19824. return Light;
  19825. }(BABYLON.Node));
  19826. BABYLON.Light = Light;
  19827. })(BABYLON || (BABYLON = {}));
  19828. //# sourceMappingURL=babylon.light.js.map
  19829. var BABYLON;
  19830. (function (BABYLON) {
  19831. var Camera = /** @class */ (function (_super) {
  19832. __extends(Camera, _super);
  19833. function Camera(name, position, scene) {
  19834. var _this = _super.call(this, name, scene) || this;
  19835. /**
  19836. * The vector the camera should consider as up.
  19837. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19838. */
  19839. _this.upVector = BABYLON.Vector3.Up();
  19840. _this.orthoLeft = null;
  19841. _this.orthoRight = null;
  19842. _this.orthoBottom = null;
  19843. _this.orthoTop = null;
  19844. /**
  19845. * FOV is set in Radians. (default is 0.8)
  19846. */
  19847. _this.fov = 0.8;
  19848. _this.minZ = 1;
  19849. _this.maxZ = 10000.0;
  19850. _this.inertia = 0.9;
  19851. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19852. _this.isIntermediate = false;
  19853. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19854. /**
  19855. * Restricts the camera to viewing objects with the same layerMask.
  19856. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19857. */
  19858. _this.layerMask = 0x0FFFFFFF;
  19859. /**
  19860. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19861. */
  19862. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19863. // Camera rig members
  19864. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19865. _this._rigCameras = new Array();
  19866. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19867. _this._skipRendering = false;
  19868. _this.customRenderTargets = new Array();
  19869. // Observables
  19870. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19871. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19872. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19873. _this.onRestoreStateObservable = new BABYLON.Observable();
  19874. // Cache
  19875. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19876. _this._projectionMatrix = new BABYLON.Matrix();
  19877. _this._doNotComputeProjectionMatrix = false;
  19878. _this._postProcesses = new Array();
  19879. _this._transformMatrix = BABYLON.Matrix.Zero();
  19880. _this._activeMeshes = new BABYLON.SmartArray(256);
  19881. _this._globalPosition = BABYLON.Vector3.Zero();
  19882. _this._refreshFrustumPlanes = true;
  19883. _this.getScene().addCamera(_this);
  19884. if (!_this.getScene().activeCamera) {
  19885. _this.getScene().activeCamera = _this;
  19886. }
  19887. _this.position = position;
  19888. return _this;
  19889. }
  19890. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19891. get: function () {
  19892. return Camera._PERSPECTIVE_CAMERA;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19898. get: function () {
  19899. return Camera._ORTHOGRAPHIC_CAMERA;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19905. /**
  19906. * This is the default FOV mode for perspective cameras.
  19907. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19908. *
  19909. */
  19910. get: function () {
  19911. return Camera._FOVMODE_VERTICAL_FIXED;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19917. /**
  19918. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19919. *
  19920. */
  19921. get: function () {
  19922. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19928. get: function () {
  19929. return Camera._RIG_MODE_NONE;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19935. get: function () {
  19936. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19942. get: function () {
  19943. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19949. get: function () {
  19950. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19956. get: function () {
  19957. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19963. get: function () {
  19964. return Camera._RIG_MODE_VR;
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19970. get: function () {
  19971. return Camera._RIG_MODE_WEBVR;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. /**
  19977. * Store current camera state (fov, position, etc..)
  19978. */
  19979. Camera.prototype.storeState = function () {
  19980. this._stateStored = true;
  19981. this._storedFov = this.fov;
  19982. return this;
  19983. };
  19984. /**
  19985. * Restores the camera state values if it has been stored. You must call storeState() first
  19986. */
  19987. Camera.prototype._restoreStateValues = function () {
  19988. if (!this._stateStored) {
  19989. return false;
  19990. }
  19991. this.fov = this._storedFov;
  19992. return true;
  19993. };
  19994. /**
  19995. * Restored camera state. You must call storeState() first
  19996. */
  19997. Camera.prototype.restoreState = function () {
  19998. if (this._restoreStateValues()) {
  19999. this.onRestoreStateObservable.notifyObservers(this);
  20000. return true;
  20001. }
  20002. return false;
  20003. };
  20004. Camera.prototype.getClassName = function () {
  20005. return "Camera";
  20006. };
  20007. /**
  20008. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20009. */
  20010. Camera.prototype.toString = function (fullDetails) {
  20011. var ret = "Name: " + this.name;
  20012. ret += ", type: " + this.getClassName();
  20013. if (this.animations) {
  20014. for (var i = 0; i < this.animations.length; i++) {
  20015. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20016. }
  20017. }
  20018. if (fullDetails) {
  20019. }
  20020. return ret;
  20021. };
  20022. Object.defineProperty(Camera.prototype, "globalPosition", {
  20023. get: function () {
  20024. return this._globalPosition;
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Camera.prototype.getActiveMeshes = function () {
  20030. return this._activeMeshes;
  20031. };
  20032. Camera.prototype.isActiveMesh = function (mesh) {
  20033. return (this._activeMeshes.indexOf(mesh) !== -1);
  20034. };
  20035. //Cache
  20036. Camera.prototype._initCache = function () {
  20037. _super.prototype._initCache.call(this);
  20038. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20039. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20040. this._cache.mode = undefined;
  20041. this._cache.minZ = undefined;
  20042. this._cache.maxZ = undefined;
  20043. this._cache.fov = undefined;
  20044. this._cache.fovMode = undefined;
  20045. this._cache.aspectRatio = undefined;
  20046. this._cache.orthoLeft = undefined;
  20047. this._cache.orthoRight = undefined;
  20048. this._cache.orthoBottom = undefined;
  20049. this._cache.orthoTop = undefined;
  20050. this._cache.renderWidth = undefined;
  20051. this._cache.renderHeight = undefined;
  20052. };
  20053. Camera.prototype._updateCache = function (ignoreParentClass) {
  20054. if (!ignoreParentClass) {
  20055. _super.prototype._updateCache.call(this);
  20056. }
  20057. this._cache.position.copyFrom(this.position);
  20058. this._cache.upVector.copyFrom(this.upVector);
  20059. };
  20060. // Synchronized
  20061. Camera.prototype._isSynchronized = function () {
  20062. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20063. };
  20064. Camera.prototype._isSynchronizedViewMatrix = function () {
  20065. if (!_super.prototype._isSynchronized.call(this))
  20066. return false;
  20067. return this._cache.position.equals(this.position)
  20068. && this._cache.upVector.equals(this.upVector)
  20069. && this.isSynchronizedWithParent();
  20070. };
  20071. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20072. var check = this._cache.mode === this.mode
  20073. && this._cache.minZ === this.minZ
  20074. && this._cache.maxZ === this.maxZ;
  20075. if (!check) {
  20076. return false;
  20077. }
  20078. var engine = this.getEngine();
  20079. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20080. check = this._cache.fov === this.fov
  20081. && this._cache.fovMode === this.fovMode
  20082. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20083. }
  20084. else {
  20085. check = this._cache.orthoLeft === this.orthoLeft
  20086. && this._cache.orthoRight === this.orthoRight
  20087. && this._cache.orthoBottom === this.orthoBottom
  20088. && this._cache.orthoTop === this.orthoTop
  20089. && this._cache.renderWidth === engine.getRenderWidth()
  20090. && this._cache.renderHeight === engine.getRenderHeight();
  20091. }
  20092. return check;
  20093. };
  20094. // Controls
  20095. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20096. };
  20097. Camera.prototype.detachControl = function (element) {
  20098. };
  20099. Camera.prototype.update = function () {
  20100. this._checkInputs();
  20101. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20102. this._updateRigCameras();
  20103. }
  20104. };
  20105. Camera.prototype._checkInputs = function () {
  20106. this.onAfterCheckInputsObservable.notifyObservers(this);
  20107. };
  20108. Object.defineProperty(Camera.prototype, "rigCameras", {
  20109. get: function () {
  20110. return this._rigCameras;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20116. get: function () {
  20117. return this._rigPostProcess;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20123. // invalidate framebuffer
  20124. if (this._postProcesses.length > 0) {
  20125. this._postProcesses[0].markTextureDirty();
  20126. }
  20127. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20128. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20129. var cam = this._rigCameras[i];
  20130. var rigPostProcess = cam._rigPostProcess;
  20131. // for VR rig, there does not have to be a post process
  20132. if (rigPostProcess) {
  20133. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20134. if (isPass) {
  20135. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20136. cam.isIntermediate = this._postProcesses.length === 0;
  20137. }
  20138. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20139. rigPostProcess.markTextureDirty();
  20140. }
  20141. else {
  20142. cam._postProcesses = this._postProcesses.slice(0);
  20143. }
  20144. }
  20145. };
  20146. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20147. if (insertAt === void 0) { insertAt = null; }
  20148. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20149. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20150. return 0;
  20151. }
  20152. if (insertAt == null || insertAt < 0) {
  20153. this._postProcesses.push(postProcess);
  20154. }
  20155. else {
  20156. this._postProcesses.splice(insertAt, 0, postProcess);
  20157. }
  20158. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20159. return this._postProcesses.indexOf(postProcess);
  20160. };
  20161. Camera.prototype.detachPostProcess = function (postProcess) {
  20162. var idx = this._postProcesses.indexOf(postProcess);
  20163. if (idx !== -1) {
  20164. this._postProcesses.splice(idx, 1);
  20165. }
  20166. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20167. };
  20168. Camera.prototype.getWorldMatrix = function () {
  20169. if (!this._worldMatrix) {
  20170. this._worldMatrix = BABYLON.Matrix.Identity();
  20171. }
  20172. var viewMatrix = this.getViewMatrix();
  20173. viewMatrix.invertToRef(this._worldMatrix);
  20174. return this._worldMatrix;
  20175. };
  20176. Camera.prototype._getViewMatrix = function () {
  20177. return BABYLON.Matrix.Identity();
  20178. };
  20179. Camera.prototype.getViewMatrix = function (force) {
  20180. if (!force && this._isSynchronizedViewMatrix()) {
  20181. return this._computedViewMatrix;
  20182. }
  20183. this.updateCache();
  20184. this._computedViewMatrix = this._getViewMatrix();
  20185. this._currentRenderId = this.getScene().getRenderId();
  20186. this._refreshFrustumPlanes = true;
  20187. if (!this.parent || !this.parent.getWorldMatrix) {
  20188. this._globalPosition.copyFrom(this.position);
  20189. }
  20190. else {
  20191. if (!this._worldMatrix) {
  20192. this._worldMatrix = BABYLON.Matrix.Identity();
  20193. }
  20194. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20195. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20196. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20197. this._computedViewMatrix.invert();
  20198. this._markSyncedWithParent();
  20199. }
  20200. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20201. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20202. }
  20203. this.onViewMatrixChangedObservable.notifyObservers(this);
  20204. return this._computedViewMatrix;
  20205. };
  20206. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20207. this._doNotComputeProjectionMatrix = true;
  20208. if (projection !== undefined) {
  20209. this._projectionMatrix = projection;
  20210. }
  20211. };
  20212. ;
  20213. Camera.prototype.unfreezeProjectionMatrix = function () {
  20214. this._doNotComputeProjectionMatrix = false;
  20215. };
  20216. ;
  20217. Camera.prototype.getProjectionMatrix = function (force) {
  20218. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20219. return this._projectionMatrix;
  20220. }
  20221. // Cache
  20222. this._cache.mode = this.mode;
  20223. this._cache.minZ = this.minZ;
  20224. this._cache.maxZ = this.maxZ;
  20225. // Matrix
  20226. this._refreshFrustumPlanes = true;
  20227. var engine = this.getEngine();
  20228. var scene = this.getScene();
  20229. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20230. this._cache.fov = this.fov;
  20231. this._cache.fovMode = this.fovMode;
  20232. this._cache.aspectRatio = engine.getAspectRatio(this);
  20233. if (this.minZ <= 0) {
  20234. this.minZ = 0.1;
  20235. }
  20236. if (scene.useRightHandedSystem) {
  20237. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20238. }
  20239. else {
  20240. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20241. }
  20242. }
  20243. else {
  20244. var halfWidth = engine.getRenderWidth() / 2.0;
  20245. var halfHeight = engine.getRenderHeight() / 2.0;
  20246. if (scene.useRightHandedSystem) {
  20247. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20248. }
  20249. else {
  20250. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20251. }
  20252. this._cache.orthoLeft = this.orthoLeft;
  20253. this._cache.orthoRight = this.orthoRight;
  20254. this._cache.orthoBottom = this.orthoBottom;
  20255. this._cache.orthoTop = this.orthoTop;
  20256. this._cache.renderWidth = engine.getRenderWidth();
  20257. this._cache.renderHeight = engine.getRenderHeight();
  20258. }
  20259. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20260. return this._projectionMatrix;
  20261. };
  20262. Camera.prototype.getTranformationMatrix = function () {
  20263. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20264. return this._transformMatrix;
  20265. };
  20266. Camera.prototype.updateFrustumPlanes = function () {
  20267. if (!this._refreshFrustumPlanes) {
  20268. return;
  20269. }
  20270. this.getTranformationMatrix();
  20271. if (!this._frustumPlanes) {
  20272. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20273. }
  20274. else {
  20275. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20276. }
  20277. this._refreshFrustumPlanes = false;
  20278. };
  20279. Camera.prototype.isInFrustum = function (target) {
  20280. this.updateFrustumPlanes();
  20281. return target.isInFrustum(this._frustumPlanes);
  20282. };
  20283. Camera.prototype.isCompletelyInFrustum = function (target) {
  20284. this.updateFrustumPlanes();
  20285. return target.isCompletelyInFrustum(this._frustumPlanes);
  20286. };
  20287. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20288. if (length === void 0) { length = 100; }
  20289. if (!transform) {
  20290. transform = this.getWorldMatrix();
  20291. }
  20292. if (!origin) {
  20293. origin = this.position;
  20294. }
  20295. var forward = new BABYLON.Vector3(0, 0, 1);
  20296. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20297. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20298. return new BABYLON.Ray(origin, direction, length);
  20299. };
  20300. /**
  20301. * Releases resources associated with this node.
  20302. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20303. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20304. */
  20305. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20306. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20307. // Observables
  20308. this.onViewMatrixChangedObservable.clear();
  20309. this.onProjectionMatrixChangedObservable.clear();
  20310. this.onAfterCheckInputsObservable.clear();
  20311. this.onRestoreStateObservable.clear();
  20312. // Inputs
  20313. if (this.inputs) {
  20314. this.inputs.clear();
  20315. }
  20316. // Animations
  20317. this.getScene().stopAnimation(this);
  20318. // Remove from scene
  20319. this.getScene().removeCamera(this);
  20320. while (this._rigCameras.length > 0) {
  20321. var camera = this._rigCameras.pop();
  20322. if (camera) {
  20323. camera.dispose();
  20324. }
  20325. }
  20326. // Postprocesses
  20327. if (this._rigPostProcess) {
  20328. this._rigPostProcess.dispose(this);
  20329. this._rigPostProcess = null;
  20330. this._postProcesses = [];
  20331. }
  20332. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20333. this._rigPostProcess = null;
  20334. this._postProcesses = [];
  20335. }
  20336. else {
  20337. var i = this._postProcesses.length;
  20338. while (--i >= 0) {
  20339. this._postProcesses[i].dispose(this);
  20340. }
  20341. }
  20342. // Render targets
  20343. var i = this.customRenderTargets.length;
  20344. while (--i >= 0) {
  20345. this.customRenderTargets[i].dispose();
  20346. }
  20347. this.customRenderTargets = [];
  20348. // Active Meshes
  20349. this._activeMeshes.dispose();
  20350. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20351. };
  20352. Object.defineProperty(Camera.prototype, "leftCamera", {
  20353. // ---- Camera rigs section ----
  20354. get: function () {
  20355. if (this._rigCameras.length < 1) {
  20356. return null;
  20357. }
  20358. return this._rigCameras[0];
  20359. },
  20360. enumerable: true,
  20361. configurable: true
  20362. });
  20363. Object.defineProperty(Camera.prototype, "rightCamera", {
  20364. get: function () {
  20365. if (this._rigCameras.length < 2) {
  20366. return null;
  20367. }
  20368. return this._rigCameras[1];
  20369. },
  20370. enumerable: true,
  20371. configurable: true
  20372. });
  20373. Camera.prototype.getLeftTarget = function () {
  20374. if (this._rigCameras.length < 1) {
  20375. return null;
  20376. }
  20377. return this._rigCameras[0].getTarget();
  20378. };
  20379. Camera.prototype.getRightTarget = function () {
  20380. if (this._rigCameras.length < 2) {
  20381. return null;
  20382. }
  20383. return this._rigCameras[1].getTarget();
  20384. };
  20385. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20386. if (this.cameraRigMode === mode) {
  20387. return;
  20388. }
  20389. while (this._rigCameras.length > 0) {
  20390. var camera = this._rigCameras.pop();
  20391. if (camera) {
  20392. camera.dispose();
  20393. }
  20394. }
  20395. this.cameraRigMode = mode;
  20396. this._cameraRigParams = {};
  20397. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20398. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20399. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20400. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20401. // create the rig cameras, unless none
  20402. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20403. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20404. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20405. if (leftCamera && rightCamera) {
  20406. this._rigCameras.push(leftCamera);
  20407. this._rigCameras.push(rightCamera);
  20408. }
  20409. }
  20410. switch (this.cameraRigMode) {
  20411. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20412. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20413. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20414. break;
  20415. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20416. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20417. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20418. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20419. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20420. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20421. break;
  20422. case Camera.RIG_MODE_VR:
  20423. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20424. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20425. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20426. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20427. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20428. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20429. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20430. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20431. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20432. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20433. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20434. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20435. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20436. if (metrics.compensateDistortion) {
  20437. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20438. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20439. }
  20440. break;
  20441. case Camera.RIG_MODE_WEBVR:
  20442. if (rigParams.vrDisplay) {
  20443. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20444. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20445. //Left eye
  20446. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20447. this._rigCameras[0].setCameraRigParameter("left", true);
  20448. //leaving this for future reference
  20449. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20450. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20451. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20452. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20453. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20454. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20455. this._rigCameras[0].parent = this;
  20456. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20457. //Right eye
  20458. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20459. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20460. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20461. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20462. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20463. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20464. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20465. this._rigCameras[1].parent = this;
  20466. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20467. if (Camera.UseAlternateWebVRRendering) {
  20468. this._rigCameras[1]._skipRendering = true;
  20469. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20470. }
  20471. }
  20472. break;
  20473. }
  20474. this._cascadePostProcessesToRigCams();
  20475. this.update();
  20476. };
  20477. Camera.prototype._getVRProjectionMatrix = function () {
  20478. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20479. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20480. return this._projectionMatrix;
  20481. };
  20482. Camera.prototype._updateCameraRotationMatrix = function () {
  20483. //Here for WebVR
  20484. };
  20485. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20486. //Here for WebVR
  20487. };
  20488. /**
  20489. * This function MUST be overwritten by the different WebVR cameras available.
  20490. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20491. */
  20492. Camera.prototype._getWebVRProjectionMatrix = function () {
  20493. return BABYLON.Matrix.Identity();
  20494. };
  20495. /**
  20496. * This function MUST be overwritten by the different WebVR cameras available.
  20497. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20498. */
  20499. Camera.prototype._getWebVRViewMatrix = function () {
  20500. return BABYLON.Matrix.Identity();
  20501. };
  20502. Camera.prototype.setCameraRigParameter = function (name, value) {
  20503. if (!this._cameraRigParams) {
  20504. this._cameraRigParams = {};
  20505. }
  20506. this._cameraRigParams[name] = value;
  20507. //provisionnally:
  20508. if (name === "interaxialDistance") {
  20509. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20510. }
  20511. };
  20512. /**
  20513. * needs to be overridden by children so sub has required properties to be copied
  20514. */
  20515. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20516. return null;
  20517. };
  20518. /**
  20519. * May need to be overridden by children
  20520. */
  20521. Camera.prototype._updateRigCameras = function () {
  20522. for (var i = 0; i < this._rigCameras.length; i++) {
  20523. this._rigCameras[i].minZ = this.minZ;
  20524. this._rigCameras[i].maxZ = this.maxZ;
  20525. this._rigCameras[i].fov = this.fov;
  20526. }
  20527. // only update viewport when ANAGLYPH
  20528. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20529. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20530. }
  20531. };
  20532. Camera.prototype._setupInputs = function () {
  20533. };
  20534. Camera.prototype.serialize = function () {
  20535. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20536. // Type
  20537. serializationObject.type = this.getClassName();
  20538. // Parent
  20539. if (this.parent) {
  20540. serializationObject.parentId = this.parent.id;
  20541. }
  20542. if (this.inputs) {
  20543. this.inputs.serialize(serializationObject);
  20544. }
  20545. // Animations
  20546. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20547. serializationObject.ranges = this.serializeAnimationRanges();
  20548. return serializationObject;
  20549. };
  20550. Camera.prototype.clone = function (name) {
  20551. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20552. };
  20553. Camera.prototype.getDirection = function (localAxis) {
  20554. var result = BABYLON.Vector3.Zero();
  20555. this.getDirectionToRef(localAxis, result);
  20556. return result;
  20557. };
  20558. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20559. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20560. };
  20561. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20562. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20563. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20564. switch (type) {
  20565. case "ArcRotateCamera":
  20566. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20567. case "DeviceOrientationCamera":
  20568. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20569. case "FollowCamera":
  20570. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20571. case "ArcFollowCamera":
  20572. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20573. case "GamepadCamera":
  20574. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20575. case "TouchCamera":
  20576. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20577. case "VirtualJoysticksCamera":
  20578. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20579. case "WebVRFreeCamera":
  20580. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20581. case "WebVRGamepadCamera":
  20582. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20583. case "VRDeviceOrientationFreeCamera":
  20584. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20585. case "VRDeviceOrientationGamepadCamera":
  20586. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20587. case "AnaglyphArcRotateCamera":
  20588. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20589. case "AnaglyphFreeCamera":
  20590. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20591. case "AnaglyphGamepadCamera":
  20592. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20593. case "AnaglyphUniversalCamera":
  20594. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20595. case "StereoscopicArcRotateCamera":
  20596. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20597. case "StereoscopicFreeCamera":
  20598. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20599. case "StereoscopicGamepadCamera":
  20600. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20601. case "StereoscopicUniversalCamera":
  20602. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20603. case "FreeCamera":// Forcing Universal here
  20604. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20605. default:// Universal Camera is the default value
  20606. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20607. }
  20608. };
  20609. Camera.prototype.computeWorldMatrix = function () {
  20610. return this.getWorldMatrix();
  20611. };
  20612. Camera.Parse = function (parsedCamera, scene) {
  20613. var type = parsedCamera.type;
  20614. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20615. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20616. // Parent
  20617. if (parsedCamera.parentId) {
  20618. camera._waitingParentId = parsedCamera.parentId;
  20619. }
  20620. //If camera has an input manager, let it parse inputs settings
  20621. if (camera.inputs) {
  20622. camera.inputs.parse(parsedCamera);
  20623. camera._setupInputs();
  20624. }
  20625. if (camera.setPosition) {
  20626. camera.position.copyFromFloats(0, 0, 0);
  20627. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20628. }
  20629. // Target
  20630. if (parsedCamera.target) {
  20631. if (camera.setTarget) {
  20632. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20633. }
  20634. }
  20635. // Apply 3d rig, when found
  20636. if (parsedCamera.cameraRigMode) {
  20637. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20638. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20639. }
  20640. // Animations
  20641. if (parsedCamera.animations) {
  20642. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20643. var parsedAnimation = parsedCamera.animations[animationIndex];
  20644. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20645. }
  20646. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20647. }
  20648. if (parsedCamera.autoAnimate) {
  20649. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20650. }
  20651. return camera;
  20652. };
  20653. // Statics
  20654. Camera._PERSPECTIVE_CAMERA = 0;
  20655. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20656. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20657. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20658. Camera._RIG_MODE_NONE = 0;
  20659. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20660. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20661. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20662. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20663. Camera._RIG_MODE_VR = 20;
  20664. Camera._RIG_MODE_WEBVR = 21;
  20665. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20666. Camera.UseAlternateWebVRRendering = false;
  20667. __decorate([
  20668. BABYLON.serializeAsVector3()
  20669. ], Camera.prototype, "position", void 0);
  20670. __decorate([
  20671. BABYLON.serializeAsVector3()
  20672. ], Camera.prototype, "upVector", void 0);
  20673. __decorate([
  20674. BABYLON.serialize()
  20675. ], Camera.prototype, "orthoLeft", void 0);
  20676. __decorate([
  20677. BABYLON.serialize()
  20678. ], Camera.prototype, "orthoRight", void 0);
  20679. __decorate([
  20680. BABYLON.serialize()
  20681. ], Camera.prototype, "orthoBottom", void 0);
  20682. __decorate([
  20683. BABYLON.serialize()
  20684. ], Camera.prototype, "orthoTop", void 0);
  20685. __decorate([
  20686. BABYLON.serialize()
  20687. ], Camera.prototype, "fov", void 0);
  20688. __decorate([
  20689. BABYLON.serialize()
  20690. ], Camera.prototype, "minZ", void 0);
  20691. __decorate([
  20692. BABYLON.serialize()
  20693. ], Camera.prototype, "maxZ", void 0);
  20694. __decorate([
  20695. BABYLON.serialize()
  20696. ], Camera.prototype, "inertia", void 0);
  20697. __decorate([
  20698. BABYLON.serialize()
  20699. ], Camera.prototype, "mode", void 0);
  20700. __decorate([
  20701. BABYLON.serialize()
  20702. ], Camera.prototype, "layerMask", void 0);
  20703. __decorate([
  20704. BABYLON.serialize()
  20705. ], Camera.prototype, "fovMode", void 0);
  20706. __decorate([
  20707. BABYLON.serialize()
  20708. ], Camera.prototype, "cameraRigMode", void 0);
  20709. __decorate([
  20710. BABYLON.serialize()
  20711. ], Camera.prototype, "interaxialDistance", void 0);
  20712. __decorate([
  20713. BABYLON.serialize()
  20714. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20715. return Camera;
  20716. }(BABYLON.Node));
  20717. BABYLON.Camera = Camera;
  20718. })(BABYLON || (BABYLON = {}));
  20719. //# sourceMappingURL=babylon.camera.js.map
  20720. var BABYLON;
  20721. (function (BABYLON) {
  20722. var RenderingManager = /** @class */ (function () {
  20723. function RenderingManager(scene) {
  20724. this._renderingGroups = new Array();
  20725. this._autoClearDepthStencil = {};
  20726. this._customOpaqueSortCompareFn = {};
  20727. this._customAlphaTestSortCompareFn = {};
  20728. this._customTransparentSortCompareFn = {};
  20729. this._renderinGroupInfo = null;
  20730. this._scene = scene;
  20731. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20732. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20733. }
  20734. }
  20735. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20736. if (depth === void 0) { depth = true; }
  20737. if (stencil === void 0) { stencil = true; }
  20738. if (this._depthStencilBufferAlreadyCleaned) {
  20739. return;
  20740. }
  20741. this._scene.getEngine().clear(null, false, depth, stencil);
  20742. this._depthStencilBufferAlreadyCleaned = true;
  20743. };
  20744. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20745. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20746. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20747. var info = null;
  20748. if (observable) {
  20749. if (!this._renderinGroupInfo) {
  20750. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20751. }
  20752. info = this._renderinGroupInfo;
  20753. info.scene = this._scene;
  20754. info.camera = this._scene.activeCamera;
  20755. }
  20756. // Dispatch sprites
  20757. if (renderSprites) {
  20758. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20759. var manager = this._scene.spriteManagers[index];
  20760. this.dispatchSprites(manager);
  20761. }
  20762. }
  20763. // Render
  20764. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20765. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20766. var renderingGroup = this._renderingGroups[index];
  20767. if (!renderingGroup && !observable)
  20768. continue;
  20769. var renderingGroupMask = 0;
  20770. // Fire PRECLEAR stage
  20771. if (observable && info) {
  20772. renderingGroupMask = Math.pow(2, index);
  20773. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20774. info.renderingGroupId = index;
  20775. observable.notifyObservers(info, renderingGroupMask);
  20776. }
  20777. // Clear depth/stencil if needed
  20778. if (RenderingManager.AUTOCLEAR) {
  20779. var autoClear = this._autoClearDepthStencil[index];
  20780. if (autoClear && autoClear.autoClear) {
  20781. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20782. }
  20783. }
  20784. if (observable && info) {
  20785. // Fire PREOPAQUE stage
  20786. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20787. observable.notifyObservers(info, renderingGroupMask);
  20788. // Fire PRETRANSPARENT stage
  20789. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20790. observable.notifyObservers(info, renderingGroupMask);
  20791. }
  20792. if (renderingGroup)
  20793. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20794. // Fire POSTTRANSPARENT stage
  20795. if (observable && info) {
  20796. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20797. observable.notifyObservers(info, renderingGroupMask);
  20798. }
  20799. }
  20800. };
  20801. RenderingManager.prototype.reset = function () {
  20802. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20803. var renderingGroup = this._renderingGroups[index];
  20804. if (renderingGroup) {
  20805. renderingGroup.prepare();
  20806. }
  20807. }
  20808. };
  20809. RenderingManager.prototype.dispose = function () {
  20810. this.freeRenderingGroups();
  20811. this._renderingGroups.length = 0;
  20812. };
  20813. /**
  20814. * Clear the info related to rendering groups preventing retention points during dispose.
  20815. */
  20816. RenderingManager.prototype.freeRenderingGroups = function () {
  20817. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20818. var renderingGroup = this._renderingGroups[index];
  20819. if (renderingGroup) {
  20820. renderingGroup.dispose();
  20821. }
  20822. }
  20823. };
  20824. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20825. if (this._renderingGroups[renderingGroupId] === undefined) {
  20826. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20827. }
  20828. };
  20829. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20830. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20831. this._prepareRenderingGroup(renderingGroupId);
  20832. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20833. };
  20834. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20835. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20836. this._prepareRenderingGroup(renderingGroupId);
  20837. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20838. };
  20839. /**
  20840. * @param subMesh The submesh to dispatch
  20841. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20842. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20843. */
  20844. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20845. if (mesh === undefined) {
  20846. mesh = subMesh.getMesh();
  20847. }
  20848. var renderingGroupId = mesh.renderingGroupId || 0;
  20849. this._prepareRenderingGroup(renderingGroupId);
  20850. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20851. };
  20852. /**
  20853. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20854. * This allowed control for front to back rendering or reversly depending of the special needs.
  20855. *
  20856. * @param renderingGroupId The rendering group id corresponding to its index
  20857. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20858. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20859. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20860. */
  20861. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20862. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20863. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20864. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20865. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20866. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20867. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20868. if (this._renderingGroups[renderingGroupId]) {
  20869. var group = this._renderingGroups[renderingGroupId];
  20870. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20871. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20872. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20873. }
  20874. };
  20875. /**
  20876. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20877. *
  20878. * @param renderingGroupId The rendering group id corresponding to its index
  20879. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20880. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20881. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20882. */
  20883. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20884. if (depth === void 0) { depth = true; }
  20885. if (stencil === void 0) { stencil = true; }
  20886. this._autoClearDepthStencil[renderingGroupId] = {
  20887. autoClear: autoClearDepthStencil,
  20888. depth: depth,
  20889. stencil: stencil
  20890. };
  20891. };
  20892. /**
  20893. * The max id used for rendering groups (not included)
  20894. */
  20895. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20896. /**
  20897. * The min id used for rendering groups (included)
  20898. */
  20899. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20900. /**
  20901. * Used to globally prevent autoclearing scenes.
  20902. */
  20903. RenderingManager.AUTOCLEAR = true;
  20904. return RenderingManager;
  20905. }());
  20906. BABYLON.RenderingManager = RenderingManager;
  20907. })(BABYLON || (BABYLON = {}));
  20908. //# sourceMappingURL=babylon.renderingManager.js.map
  20909. var BABYLON;
  20910. (function (BABYLON) {
  20911. var RenderingGroup = /** @class */ (function () {
  20912. /**
  20913. * Creates a new rendering group.
  20914. * @param index The rendering group index
  20915. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20916. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20917. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20918. */
  20919. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20920. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20921. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20922. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20923. this.index = index;
  20924. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20925. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20926. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20927. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20928. this._particleSystems = new BABYLON.SmartArray(256);
  20929. this._spriteManagers = new BABYLON.SmartArray(256);
  20930. this._edgesRenderers = new BABYLON.SmartArray(16);
  20931. this._scene = scene;
  20932. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20933. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20934. this.transparentSortCompareFn = transparentSortCompareFn;
  20935. }
  20936. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20937. /**
  20938. * Set the opaque sort comparison function.
  20939. * If null the sub meshes will be render in the order they were created
  20940. */
  20941. set: function (value) {
  20942. this._opaqueSortCompareFn = value;
  20943. if (value) {
  20944. this._renderOpaque = this.renderOpaqueSorted;
  20945. }
  20946. else {
  20947. this._renderOpaque = RenderingGroup.renderUnsorted;
  20948. }
  20949. },
  20950. enumerable: true,
  20951. configurable: true
  20952. });
  20953. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20954. /**
  20955. * Set the alpha test sort comparison function.
  20956. * If null the sub meshes will be render in the order they were created
  20957. */
  20958. set: function (value) {
  20959. this._alphaTestSortCompareFn = value;
  20960. if (value) {
  20961. this._renderAlphaTest = this.renderAlphaTestSorted;
  20962. }
  20963. else {
  20964. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20965. }
  20966. },
  20967. enumerable: true,
  20968. configurable: true
  20969. });
  20970. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20971. /**
  20972. * Set the transparent sort comparison function.
  20973. * If null the sub meshes will be render in the order they were created
  20974. */
  20975. set: function (value) {
  20976. if (value) {
  20977. this._transparentSortCompareFn = value;
  20978. }
  20979. else {
  20980. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20981. }
  20982. this._renderTransparent = this.renderTransparentSorted;
  20983. },
  20984. enumerable: true,
  20985. configurable: true
  20986. });
  20987. /**
  20988. * Render all the sub meshes contained in the group.
  20989. * @param customRenderFunction Used to override the default render behaviour of the group.
  20990. * @returns true if rendered some submeshes.
  20991. */
  20992. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20993. if (customRenderFunction) {
  20994. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20995. return;
  20996. }
  20997. var engine = this._scene.getEngine();
  20998. // Depth only
  20999. if (this._depthOnlySubMeshes.length !== 0) {
  21000. engine.setColorWrite(false);
  21001. this._renderAlphaTest(this._depthOnlySubMeshes);
  21002. engine.setColorWrite(true);
  21003. }
  21004. // Opaque
  21005. if (this._opaqueSubMeshes.length !== 0) {
  21006. this._renderOpaque(this._opaqueSubMeshes);
  21007. }
  21008. // Alpha test
  21009. if (this._alphaTestSubMeshes.length !== 0) {
  21010. this._renderAlphaTest(this._alphaTestSubMeshes);
  21011. }
  21012. var stencilState = engine.getStencilBuffer();
  21013. engine.setStencilBuffer(false);
  21014. // Sprites
  21015. if (renderSprites) {
  21016. this._renderSprites();
  21017. }
  21018. // Particles
  21019. if (renderParticles) {
  21020. this._renderParticles(activeMeshes);
  21021. }
  21022. if (this.onBeforeTransparentRendering) {
  21023. this.onBeforeTransparentRendering();
  21024. }
  21025. // Transparent
  21026. if (this._transparentSubMeshes.length !== 0) {
  21027. this._renderTransparent(this._transparentSubMeshes);
  21028. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21029. }
  21030. // Set back stencil to false in case it changes before the edge renderer.
  21031. engine.setStencilBuffer(false);
  21032. // Edges
  21033. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21034. this._edgesRenderers.data[edgesRendererIndex].render();
  21035. }
  21036. // Restore Stencil state.
  21037. engine.setStencilBuffer(stencilState);
  21038. };
  21039. /**
  21040. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21041. * @param subMeshes The submeshes to render
  21042. */
  21043. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21044. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21045. };
  21046. /**
  21047. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21048. * @param subMeshes The submeshes to render
  21049. */
  21050. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21051. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21052. };
  21053. /**
  21054. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21055. * @param subMeshes The submeshes to render
  21056. */
  21057. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21058. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21059. };
  21060. /**
  21061. * Renders the submeshes in a specified order.
  21062. * @param subMeshes The submeshes to sort before render
  21063. * @param sortCompareFn The comparison function use to sort
  21064. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21065. * @param transparent Specifies to activate blending if true
  21066. */
  21067. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21068. var subIndex = 0;
  21069. var subMesh;
  21070. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21071. for (; subIndex < subMeshes.length; subIndex++) {
  21072. subMesh = subMeshes.data[subIndex];
  21073. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21074. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21075. }
  21076. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21077. if (sortCompareFn) {
  21078. sortedArray.sort(sortCompareFn);
  21079. }
  21080. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21081. subMesh = sortedArray[subIndex];
  21082. if (transparent) {
  21083. var material = subMesh.getMaterial();
  21084. if (material && material.needDepthPrePass) {
  21085. var engine = material.getScene().getEngine();
  21086. engine.setColorWrite(false);
  21087. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21088. subMesh.render(false);
  21089. engine.setColorWrite(true);
  21090. }
  21091. }
  21092. subMesh.render(transparent);
  21093. }
  21094. };
  21095. /**
  21096. * Renders the submeshes in the order they were dispatched (no sort applied).
  21097. * @param subMeshes The submeshes to render
  21098. */
  21099. RenderingGroup.renderUnsorted = function (subMeshes) {
  21100. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21101. var submesh = subMeshes.data[subIndex];
  21102. submesh.render(false);
  21103. }
  21104. };
  21105. /**
  21106. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21107. * are rendered back to front if in the same alpha index.
  21108. *
  21109. * @param a The first submesh
  21110. * @param b The second submesh
  21111. * @returns The result of the comparison
  21112. */
  21113. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21114. // Alpha index first
  21115. if (a._alphaIndex > b._alphaIndex) {
  21116. return 1;
  21117. }
  21118. if (a._alphaIndex < b._alphaIndex) {
  21119. return -1;
  21120. }
  21121. // Then distance to camera
  21122. return RenderingGroup.backToFrontSortCompare(a, b);
  21123. };
  21124. /**
  21125. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21126. * are rendered back to front.
  21127. *
  21128. * @param a The first submesh
  21129. * @param b The second submesh
  21130. * @returns The result of the comparison
  21131. */
  21132. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21133. // Then distance to camera
  21134. if (a._distanceToCamera < b._distanceToCamera) {
  21135. return 1;
  21136. }
  21137. if (a._distanceToCamera > b._distanceToCamera) {
  21138. return -1;
  21139. }
  21140. return 0;
  21141. };
  21142. /**
  21143. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21144. * are rendered front to back (prevent overdraw).
  21145. *
  21146. * @param a The first submesh
  21147. * @param b The second submesh
  21148. * @returns The result of the comparison
  21149. */
  21150. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21151. // Then distance to camera
  21152. if (a._distanceToCamera < b._distanceToCamera) {
  21153. return -1;
  21154. }
  21155. if (a._distanceToCamera > b._distanceToCamera) {
  21156. return 1;
  21157. }
  21158. return 0;
  21159. };
  21160. /**
  21161. * Resets the different lists of submeshes to prepare a new frame.
  21162. */
  21163. RenderingGroup.prototype.prepare = function () {
  21164. this._opaqueSubMeshes.reset();
  21165. this._transparentSubMeshes.reset();
  21166. this._alphaTestSubMeshes.reset();
  21167. this._depthOnlySubMeshes.reset();
  21168. this._particleSystems.reset();
  21169. this._spriteManagers.reset();
  21170. this._edgesRenderers.reset();
  21171. };
  21172. RenderingGroup.prototype.dispose = function () {
  21173. this._opaqueSubMeshes.dispose();
  21174. this._transparentSubMeshes.dispose();
  21175. this._alphaTestSubMeshes.dispose();
  21176. this._depthOnlySubMeshes.dispose();
  21177. this._particleSystems.dispose();
  21178. this._spriteManagers.dispose();
  21179. this._edgesRenderers.dispose();
  21180. };
  21181. /**
  21182. * Inserts the submesh in its correct queue depending on its material.
  21183. * @param subMesh The submesh to dispatch
  21184. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21185. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21186. */
  21187. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21188. // Get mesh and materials if not provided
  21189. if (mesh === undefined) {
  21190. mesh = subMesh.getMesh();
  21191. }
  21192. if (material === undefined) {
  21193. material = subMesh.getMaterial();
  21194. }
  21195. if (material === null || material === undefined) {
  21196. return;
  21197. }
  21198. if (material.needAlphaBlendingForMesh(mesh)) {
  21199. this._transparentSubMeshes.push(subMesh);
  21200. }
  21201. else if (material.needAlphaTesting()) {
  21202. if (material.needDepthPrePass) {
  21203. this._depthOnlySubMeshes.push(subMesh);
  21204. }
  21205. this._alphaTestSubMeshes.push(subMesh);
  21206. }
  21207. else {
  21208. if (material.needDepthPrePass) {
  21209. this._depthOnlySubMeshes.push(subMesh);
  21210. }
  21211. this._opaqueSubMeshes.push(subMesh); // Opaque
  21212. }
  21213. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21214. this._edgesRenderers.push(mesh._edgesRenderer);
  21215. }
  21216. };
  21217. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21218. this._spriteManagers.push(spriteManager);
  21219. };
  21220. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21221. this._particleSystems.push(particleSystem);
  21222. };
  21223. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21224. if (this._particleSystems.length === 0) {
  21225. return;
  21226. }
  21227. // Particles
  21228. var activeCamera = this._scene.activeCamera;
  21229. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21230. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21231. var particleSystem = this._particleSystems.data[particleIndex];
  21232. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21233. continue;
  21234. }
  21235. var emitter = particleSystem.emitter;
  21236. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21237. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21238. }
  21239. }
  21240. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21241. };
  21242. RenderingGroup.prototype._renderSprites = function () {
  21243. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21244. return;
  21245. }
  21246. // Sprites
  21247. var activeCamera = this._scene.activeCamera;
  21248. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21249. for (var id = 0; id < this._spriteManagers.length; id++) {
  21250. var spriteManager = this._spriteManagers.data[id];
  21251. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21252. spriteManager.render();
  21253. }
  21254. }
  21255. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21256. };
  21257. return RenderingGroup;
  21258. }());
  21259. BABYLON.RenderingGroup = RenderingGroup;
  21260. })(BABYLON || (BABYLON = {}));
  21261. //# sourceMappingURL=babylon.renderingGroup.js.map
  21262. var BABYLON;
  21263. (function (BABYLON) {
  21264. var ClickInfo = /** @class */ (function () {
  21265. function ClickInfo() {
  21266. this._singleClick = false;
  21267. this._doubleClick = false;
  21268. this._hasSwiped = false;
  21269. this._ignore = false;
  21270. }
  21271. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21272. get: function () {
  21273. return this._singleClick;
  21274. },
  21275. set: function (b) {
  21276. this._singleClick = b;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21282. get: function () {
  21283. return this._doubleClick;
  21284. },
  21285. set: function (b) {
  21286. this._doubleClick = b;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21292. get: function () {
  21293. return this._hasSwiped;
  21294. },
  21295. set: function (b) {
  21296. this._hasSwiped = b;
  21297. },
  21298. enumerable: true,
  21299. configurable: true
  21300. });
  21301. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21302. get: function () {
  21303. return this._ignore;
  21304. },
  21305. set: function (b) {
  21306. this._ignore = b;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. return ClickInfo;
  21312. }());
  21313. /**
  21314. * This class is used by the onRenderingGroupObservable
  21315. */
  21316. var RenderingGroupInfo = /** @class */ (function () {
  21317. function RenderingGroupInfo() {
  21318. }
  21319. /**
  21320. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21321. * This stage will be fired no matter what
  21322. */
  21323. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21324. /**
  21325. * Called before opaque object are rendered.
  21326. * This stage will be fired only if there's 3D Opaque content to render
  21327. */
  21328. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21329. /**
  21330. * Called after the opaque objects are rendered and before the transparent ones
  21331. * This stage will be fired only if there's 3D transparent content to render
  21332. */
  21333. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21334. /**
  21335. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21336. * This stage will be fired no matter what
  21337. */
  21338. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21339. return RenderingGroupInfo;
  21340. }());
  21341. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21342. /**
  21343. * Represents a scene to be rendered by the engine.
  21344. * @see http://doc.babylonjs.com/page.php?p=21911
  21345. */
  21346. var Scene = /** @class */ (function () {
  21347. /**
  21348. * @constructor
  21349. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21350. */
  21351. function Scene(engine) {
  21352. // Members
  21353. this.autoClear = true;
  21354. this.autoClearDepthAndStencil = true;
  21355. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21356. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21357. this.forceWireframe = false;
  21358. this._forcePointsCloud = false;
  21359. this.forceShowBoundingBoxes = false;
  21360. this.animationsEnabled = true;
  21361. this.useConstantAnimationDeltaTime = false;
  21362. this.constantlyUpdateMeshUnderPointer = false;
  21363. this.hoverCursor = "pointer";
  21364. this.defaultCursor = "";
  21365. /**
  21366. * This is used to call preventDefault() on pointer down
  21367. * in order to block unwanted artifacts like system double clicks
  21368. */
  21369. this.preventDefaultOnPointerDown = true;
  21370. // Metadata
  21371. this.metadata = null;
  21372. /**
  21373. * An event triggered when the scene is disposed.
  21374. * @type {BABYLON.Observable}
  21375. */
  21376. this.onDisposeObservable = new BABYLON.Observable();
  21377. /**
  21378. * An event triggered before rendering the scene (right after animations and physics)
  21379. * @type {BABYLON.Observable}
  21380. */
  21381. this.onBeforeRenderObservable = new BABYLON.Observable();
  21382. /**
  21383. * An event triggered after rendering the scene
  21384. * @type {BABYLON.Observable}
  21385. */
  21386. this.onAfterRenderObservable = new BABYLON.Observable();
  21387. /**
  21388. * An event triggered before animating the scene
  21389. * @type {BABYLON.Observable}
  21390. */
  21391. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21392. /**
  21393. * An event triggered after animations processing
  21394. * @type {BABYLON.Observable}
  21395. */
  21396. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21397. /**
  21398. * An event triggered before draw calls are ready to be sent
  21399. * @type {BABYLON.Observable}
  21400. */
  21401. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21402. /**
  21403. * An event triggered after draw calls have been sent
  21404. * @type {BABYLON.Observable}
  21405. */
  21406. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21407. /**
  21408. * An event triggered when physic simulation is about to be run
  21409. * @type {BABYLON.Observable}
  21410. */
  21411. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21412. /**
  21413. * An event triggered when physic simulation has been done
  21414. * @type {BABYLON.Observable}
  21415. */
  21416. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21417. /**
  21418. * An event triggered when the scene is ready
  21419. * @type {BABYLON.Observable}
  21420. */
  21421. this.onReadyObservable = new BABYLON.Observable();
  21422. /**
  21423. * An event triggered before rendering a camera
  21424. * @type {BABYLON.Observable}
  21425. */
  21426. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21427. /**
  21428. * An event triggered after rendering a camera
  21429. * @type {BABYLON.Observable}
  21430. */
  21431. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21432. /**
  21433. * An event triggered when active meshes evaluation is about to start
  21434. * @type {BABYLON.Observable}
  21435. */
  21436. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21437. /**
  21438. * An event triggered when active meshes evaluation is done
  21439. * @type {BABYLON.Observable}
  21440. */
  21441. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21442. /**
  21443. * An event triggered when particles rendering is about to start
  21444. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21445. * @type {BABYLON.Observable}
  21446. */
  21447. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21448. /**
  21449. * An event triggered when particles rendering is done
  21450. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21451. * @type {BABYLON.Observable}
  21452. */
  21453. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21454. /**
  21455. * An event triggered when sprites rendering is about to start
  21456. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21457. * @type {BABYLON.Observable}
  21458. */
  21459. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21460. /**
  21461. * An event triggered when sprites rendering is done
  21462. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21463. * @type {BABYLON.Observable}
  21464. */
  21465. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21466. /**
  21467. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21468. * @type {BABYLON.Observable}
  21469. */
  21470. this.onDataLoadedObservable = new BABYLON.Observable();
  21471. /**
  21472. * An event triggered when a camera is created
  21473. * @type {BABYLON.Observable}
  21474. */
  21475. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21476. /**
  21477. * An event triggered when a camera is removed
  21478. * @type {BABYLON.Observable}
  21479. */
  21480. this.onCameraRemovedObservable = new BABYLON.Observable();
  21481. /**
  21482. * An event triggered when a light is created
  21483. * @type {BABYLON.Observable}
  21484. */
  21485. this.onNewLightAddedObservable = new BABYLON.Observable();
  21486. /**
  21487. * An event triggered when a light is removed
  21488. * @type {BABYLON.Observable}
  21489. */
  21490. this.onLightRemovedObservable = new BABYLON.Observable();
  21491. /**
  21492. * An event triggered when a geometry is created
  21493. * @type {BABYLON.Observable}
  21494. */
  21495. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21496. /**
  21497. * An event triggered when a geometry is removed
  21498. * @type {BABYLON.Observable}
  21499. */
  21500. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21501. /**
  21502. * An event triggered when a transform node is created
  21503. * @type {BABYLON.Observable}
  21504. */
  21505. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21506. /**
  21507. * An event triggered when a transform node is removed
  21508. * @type {BABYLON.Observable}
  21509. */
  21510. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21511. /**
  21512. * An event triggered when a mesh is created
  21513. * @type {BABYLON.Observable}
  21514. */
  21515. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21516. /**
  21517. * An event triggered when a mesh is removed
  21518. * @type {BABYLON.Observable}
  21519. */
  21520. this.onMeshRemovedObservable = new BABYLON.Observable();
  21521. /**
  21522. * An event triggered when render targets are about to be rendered
  21523. * Can happen multiple times per frame.
  21524. * @type {BABYLON.Observable}
  21525. */
  21526. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21527. /**
  21528. * An event triggered when render targets were rendered.
  21529. * Can happen multiple times per frame.
  21530. * @type {BABYLON.Observable}
  21531. */
  21532. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21533. /**
  21534. * An event triggered before calculating deterministic simulation step
  21535. * @type {BABYLON.Observable}
  21536. */
  21537. this.onBeforeStepObservable = new BABYLON.Observable();
  21538. /**
  21539. * An event triggered after calculating deterministic simulation step
  21540. * @type {BABYLON.Observable}
  21541. */
  21542. this.onAfterStepObservable = new BABYLON.Observable();
  21543. /**
  21544. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21545. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21546. * 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)
  21547. */
  21548. this.onRenderingGroupObservable = new BABYLON.Observable();
  21549. // Animations
  21550. this.animations = [];
  21551. /**
  21552. * 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).
  21553. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21554. */
  21555. this.onPrePointerObservable = new BABYLON.Observable();
  21556. /**
  21557. * Observable event triggered each time an input event is received from the rendering canvas
  21558. */
  21559. this.onPointerObservable = new BABYLON.Observable();
  21560. this._meshPickProceed = false;
  21561. this._currentPickResult = null;
  21562. this._previousPickResult = null;
  21563. this._totalPointersPressed = 0;
  21564. this._doubleClickOccured = false;
  21565. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21566. this.cameraToUseForPointers = null;
  21567. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21568. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21569. this._startingPointerTime = 0;
  21570. this._previousStartingPointerTime = 0;
  21571. // Deterministic lockstep
  21572. this._timeAccumulator = 0;
  21573. this._currentStepId = 0;
  21574. this._currentInternalStep = 0;
  21575. // Keyboard
  21576. /**
  21577. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21578. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21579. */
  21580. this.onPreKeyboardObservable = new BABYLON.Observable();
  21581. /**
  21582. * Observable event triggered each time an keyboard event is received from the hosting window
  21583. */
  21584. this.onKeyboardObservable = new BABYLON.Observable();
  21585. // Coordinate system
  21586. /**
  21587. * use right-handed coordinate system on this scene.
  21588. * @type {boolean}
  21589. */
  21590. this._useRightHandedSystem = false;
  21591. // Fog
  21592. this._fogEnabled = true;
  21593. this._fogMode = Scene.FOGMODE_NONE;
  21594. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21595. this.fogDensity = 0.1;
  21596. this.fogStart = 0;
  21597. this.fogEnd = 1000.0;
  21598. // Lights
  21599. /**
  21600. * is shadow enabled on this scene.
  21601. * @type {boolean}
  21602. */
  21603. this._shadowsEnabled = true;
  21604. /**
  21605. * is light enabled on this scene.
  21606. * @type {boolean}
  21607. */
  21608. this._lightsEnabled = true;
  21609. /**
  21610. * All of the lights added to this scene.
  21611. * @see BABYLON.Light
  21612. * @type {BABYLON.Light[]}
  21613. */
  21614. this.lights = new Array();
  21615. // Cameras
  21616. /** All of the cameras added to this scene. */
  21617. this.cameras = new Array();
  21618. /** All of the active cameras added to this scene. */
  21619. this.activeCameras = new Array();
  21620. // Meshes
  21621. /**
  21622. * All of the tranform nodes added to this scene.
  21623. * @see BABYLON.TransformNode
  21624. * @type {BABYLON.TransformNode[]}
  21625. */
  21626. this.transformNodes = new Array();
  21627. /**
  21628. * All of the (abstract) meshes added to this scene.
  21629. * @see BABYLON.AbstractMesh
  21630. * @type {BABYLON.AbstractMesh[]}
  21631. */
  21632. this.meshes = new Array();
  21633. /**
  21634. * All of the animation groups added to this scene.
  21635. * @see BABYLON.AnimationGroup
  21636. * @type {BABYLON.AnimationGroup[]}
  21637. */
  21638. this.animationGroups = new Array();
  21639. // Geometries
  21640. this._geometries = new Array();
  21641. this.materials = new Array();
  21642. this.multiMaterials = new Array();
  21643. // Textures
  21644. this._texturesEnabled = true;
  21645. this.textures = new Array();
  21646. // Particles
  21647. this.particlesEnabled = true;
  21648. this.particleSystems = new Array();
  21649. // Sprites
  21650. this.spritesEnabled = true;
  21651. this.spriteManagers = new Array();
  21652. /**
  21653. * The list of layers (background and foreground) of the scene.
  21654. */
  21655. this.layers = new Array();
  21656. /**
  21657. * The list of effect layers (highlights/glow) contained in the scene.
  21658. */
  21659. this.effectLayers = new Array();
  21660. // Skeletons
  21661. this._skeletonsEnabled = true;
  21662. this.skeletons = new Array();
  21663. // Morph targets
  21664. this.morphTargetManagers = new Array();
  21665. // Lens flares
  21666. this.lensFlaresEnabled = true;
  21667. this.lensFlareSystems = new Array();
  21668. // Collisions
  21669. this.collisionsEnabled = true;
  21670. /** Defines the gravity applied to this scene */
  21671. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21672. // Postprocesses
  21673. this.postProcesses = new Array();
  21674. this.postProcessesEnabled = true;
  21675. // Customs render targets
  21676. this.renderTargetsEnabled = true;
  21677. this.dumpNextRenderTargets = false;
  21678. this.customRenderTargets = new Array();
  21679. // Imported meshes
  21680. this.importedMeshesFiles = new Array();
  21681. // Probes
  21682. this.probesEnabled = true;
  21683. this.reflectionProbes = new Array();
  21684. this._actionManagers = new Array();
  21685. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21686. // Procedural textures
  21687. this.proceduralTexturesEnabled = true;
  21688. this._proceduralTextures = new Array();
  21689. this.soundTracks = new Array();
  21690. this._audioEnabled = true;
  21691. this._headphone = false;
  21692. // Performance counters
  21693. this._totalVertices = new BABYLON.PerfCounter();
  21694. this._activeIndices = new BABYLON.PerfCounter();
  21695. this._activeParticles = new BABYLON.PerfCounter();
  21696. this._activeBones = new BABYLON.PerfCounter();
  21697. this._animationTime = 0;
  21698. this.animationTimeScale = 1;
  21699. this._renderId = 0;
  21700. this._executeWhenReadyTimeoutId = -1;
  21701. this._intermediateRendering = false;
  21702. this._viewUpdateFlag = -1;
  21703. this._projectionUpdateFlag = -1;
  21704. this._alternateViewUpdateFlag = -1;
  21705. this._alternateProjectionUpdateFlag = -1;
  21706. this._toBeDisposed = new BABYLON.SmartArray(256);
  21707. this._activeRequests = new Array();
  21708. this._pendingData = new Array();
  21709. this._isDisposed = false;
  21710. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21711. this._activeMeshes = new BABYLON.SmartArray(256);
  21712. this._processedMaterials = new BABYLON.SmartArray(256);
  21713. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21714. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21715. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21716. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21717. this._activeAnimatables = new Array();
  21718. this._transformMatrix = BABYLON.Matrix.Zero();
  21719. this._useAlternateCameraConfiguration = false;
  21720. this._alternateRendering = false;
  21721. this.requireLightSorting = false;
  21722. this._depthRenderer = {};
  21723. this._activeMeshesFrozen = false;
  21724. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21725. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21726. this._engine.scenes.push(this);
  21727. this._uid = null;
  21728. this._renderingManager = new BABYLON.RenderingManager(this);
  21729. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21730. if (BABYLON.OutlineRenderer) {
  21731. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21732. }
  21733. if (BABYLON.Tools.IsWindowObjectExist()) {
  21734. this.attachControl();
  21735. }
  21736. //simplification queue
  21737. if (BABYLON.SimplificationQueue) {
  21738. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21739. }
  21740. //collision coordinator initialization. For now legacy per default.
  21741. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21742. // Uniform Buffer
  21743. this._createUbo();
  21744. // Default Image processing definition.
  21745. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21746. }
  21747. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21748. /** The fog is deactivated */
  21749. get: function () {
  21750. return Scene._FOGMODE_NONE;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21756. /** The fog density is following an exponential function */
  21757. get: function () {
  21758. return Scene._FOGMODE_EXP;
  21759. },
  21760. enumerable: true,
  21761. configurable: true
  21762. });
  21763. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21764. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21765. get: function () {
  21766. return Scene._FOGMODE_EXP2;
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21772. /** The fog density is following a linear function. */
  21773. get: function () {
  21774. return Scene._FOGMODE_LINEAR;
  21775. },
  21776. enumerable: true,
  21777. configurable: true
  21778. });
  21779. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21780. /**
  21781. * Texture used in all pbr material as the reflection texture.
  21782. * As in the majority of the scene they are the same (exception for multi room and so on),
  21783. * this is easier to reference from here than from all the materials.
  21784. */
  21785. get: function () {
  21786. return this._environmentTexture;
  21787. },
  21788. /**
  21789. * Texture used in all pbr material as the reflection texture.
  21790. * As in the majority of the scene they are the same (exception for multi room and so on),
  21791. * this is easier to set here than in all the materials.
  21792. */
  21793. set: function (value) {
  21794. if (this._environmentTexture === value) {
  21795. return;
  21796. }
  21797. this._environmentTexture = value;
  21798. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21804. /**
  21805. * Default image processing configuration used either in the rendering
  21806. * Forward main pass or through the imageProcessingPostProcess if present.
  21807. * As in the majority of the scene they are the same (exception for multi camera),
  21808. * this is easier to reference from here than from all the materials and post process.
  21809. *
  21810. * No setter as we it is a shared configuration, you can set the values instead.
  21811. */
  21812. get: function () {
  21813. return this._imageProcessingConfiguration;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21819. get: function () {
  21820. return this._forcePointsCloud;
  21821. },
  21822. set: function (value) {
  21823. if (this._forcePointsCloud === value) {
  21824. return;
  21825. }
  21826. this._forcePointsCloud = value;
  21827. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Scene.prototype, "onDispose", {
  21833. /** A function to be executed when this scene is disposed. */
  21834. set: function (callback) {
  21835. if (this._onDisposeObserver) {
  21836. this.onDisposeObservable.remove(this._onDisposeObserver);
  21837. }
  21838. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21839. },
  21840. enumerable: true,
  21841. configurable: true
  21842. });
  21843. Object.defineProperty(Scene.prototype, "beforeRender", {
  21844. /** A function to be executed before rendering this scene */
  21845. set: function (callback) {
  21846. if (this._onBeforeRenderObserver) {
  21847. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21848. }
  21849. if (callback) {
  21850. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21851. }
  21852. },
  21853. enumerable: true,
  21854. configurable: true
  21855. });
  21856. Object.defineProperty(Scene.prototype, "afterRender", {
  21857. /** A function to be executed after rendering this scene */
  21858. set: function (callback) {
  21859. if (this._onAfterRenderObserver) {
  21860. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21861. }
  21862. if (callback) {
  21863. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21864. }
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21870. set: function (callback) {
  21871. if (this._onBeforeCameraRenderObserver) {
  21872. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21873. }
  21874. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21880. set: function (callback) {
  21881. if (this._onAfterCameraRenderObserver) {
  21882. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21883. }
  21884. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21890. get: function () {
  21891. if (!this._gamepadManager) {
  21892. this._gamepadManager = new BABYLON.GamepadManager(this);
  21893. }
  21894. return this._gamepadManager;
  21895. },
  21896. enumerable: true,
  21897. configurable: true
  21898. });
  21899. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21900. get: function () {
  21901. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21902. },
  21903. enumerable: true,
  21904. configurable: true
  21905. });
  21906. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21907. get: function () {
  21908. return this._useRightHandedSystem;
  21909. },
  21910. set: function (value) {
  21911. if (this._useRightHandedSystem === value) {
  21912. return;
  21913. }
  21914. this._useRightHandedSystem = value;
  21915. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21916. },
  21917. enumerable: true,
  21918. configurable: true
  21919. });
  21920. Scene.prototype.setStepId = function (newStepId) {
  21921. this._currentStepId = newStepId;
  21922. };
  21923. ;
  21924. Scene.prototype.getStepId = function () {
  21925. return this._currentStepId;
  21926. };
  21927. ;
  21928. Scene.prototype.getInternalStep = function () {
  21929. return this._currentInternalStep;
  21930. };
  21931. ;
  21932. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21933. get: function () {
  21934. return this._fogEnabled;
  21935. },
  21936. /**
  21937. * is fog enabled on this scene.
  21938. */
  21939. set: function (value) {
  21940. if (this._fogEnabled === value) {
  21941. return;
  21942. }
  21943. this._fogEnabled = value;
  21944. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21945. },
  21946. enumerable: true,
  21947. configurable: true
  21948. });
  21949. Object.defineProperty(Scene.prototype, "fogMode", {
  21950. get: function () {
  21951. return this._fogMode;
  21952. },
  21953. set: function (value) {
  21954. if (this._fogMode === value) {
  21955. return;
  21956. }
  21957. this._fogMode = value;
  21958. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21964. get: function () {
  21965. return this._shadowsEnabled;
  21966. },
  21967. set: function (value) {
  21968. if (this._shadowsEnabled === value) {
  21969. return;
  21970. }
  21971. this._shadowsEnabled = value;
  21972. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21973. },
  21974. enumerable: true,
  21975. configurable: true
  21976. });
  21977. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21978. get: function () {
  21979. return this._lightsEnabled;
  21980. },
  21981. set: function (value) {
  21982. if (this._lightsEnabled === value) {
  21983. return;
  21984. }
  21985. this._lightsEnabled = value;
  21986. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21992. /** The default material used on meshes when no material is affected */
  21993. get: function () {
  21994. if (!this._defaultMaterial) {
  21995. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21996. }
  21997. return this._defaultMaterial;
  21998. },
  21999. /** The default material used on meshes when no material is affected */
  22000. set: function (value) {
  22001. this._defaultMaterial = value;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22007. get: function () {
  22008. return this._texturesEnabled;
  22009. },
  22010. set: function (value) {
  22011. if (this._texturesEnabled === value) {
  22012. return;
  22013. }
  22014. this._texturesEnabled = value;
  22015. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22016. },
  22017. enumerable: true,
  22018. configurable: true
  22019. });
  22020. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22021. get: function () {
  22022. return this._skeletonsEnabled;
  22023. },
  22024. set: function (value) {
  22025. if (this._skeletonsEnabled === value) {
  22026. return;
  22027. }
  22028. this._skeletonsEnabled = value;
  22029. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22035. get: function () {
  22036. if (!this._postProcessRenderPipelineManager) {
  22037. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22038. }
  22039. return this._postProcessRenderPipelineManager;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22045. get: function () {
  22046. if (!this._mainSoundTrack) {
  22047. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22048. }
  22049. return this._mainSoundTrack;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22055. get: function () {
  22056. return this._alternateRendering;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22062. get: function () {
  22063. return this._frustumPlanes;
  22064. },
  22065. enumerable: true,
  22066. configurable: true
  22067. });
  22068. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22069. /**
  22070. * Gets the current geometry buffer associated to the scene.
  22071. */
  22072. get: function () {
  22073. return this._geometryBufferRenderer;
  22074. },
  22075. /**
  22076. * Sets the current geometry buffer for the scene.
  22077. */
  22078. set: function (geometryBufferRenderer) {
  22079. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22080. this._geometryBufferRenderer = geometryBufferRenderer;
  22081. }
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Object.defineProperty(Scene.prototype, "debugLayer", {
  22087. // Properties
  22088. get: function () {
  22089. if (!this._debugLayer) {
  22090. this._debugLayer = new BABYLON.DebugLayer(this);
  22091. }
  22092. return this._debugLayer;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22098. get: function () {
  22099. return this._workerCollisions;
  22100. },
  22101. set: function (enabled) {
  22102. if (!BABYLON.CollisionCoordinatorLegacy) {
  22103. return;
  22104. }
  22105. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22106. this._workerCollisions = enabled;
  22107. if (this.collisionCoordinator) {
  22108. this.collisionCoordinator.destroy();
  22109. }
  22110. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22111. this.collisionCoordinator.init(this);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22117. get: function () {
  22118. return this._selectionOctree;
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22124. /**
  22125. * The mesh that is currently under the pointer.
  22126. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22127. */
  22128. get: function () {
  22129. return this._pointerOverMesh;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. Object.defineProperty(Scene.prototype, "pointerX", {
  22135. /**
  22136. * Current on-screen X position of the pointer
  22137. * @return {number} X position of the pointer
  22138. */
  22139. get: function () {
  22140. return this._pointerX;
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Object.defineProperty(Scene.prototype, "pointerY", {
  22146. /**
  22147. * Current on-screen Y position of the pointer
  22148. * @return {number} Y position of the pointer
  22149. */
  22150. get: function () {
  22151. return this._pointerY;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Scene.prototype.getCachedMaterial = function () {
  22157. return this._cachedMaterial;
  22158. };
  22159. Scene.prototype.getCachedEffect = function () {
  22160. return this._cachedEffect;
  22161. };
  22162. Scene.prototype.getCachedVisibility = function () {
  22163. return this._cachedVisibility;
  22164. };
  22165. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22166. if (visibility === void 0) { visibility = 1; }
  22167. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22168. };
  22169. Scene.prototype.getBoundingBoxRenderer = function () {
  22170. if (!this._boundingBoxRenderer) {
  22171. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22172. }
  22173. return this._boundingBoxRenderer;
  22174. };
  22175. Scene.prototype.getOutlineRenderer = function () {
  22176. return this._outlineRenderer;
  22177. };
  22178. Scene.prototype.getEngine = function () {
  22179. return this._engine;
  22180. };
  22181. Scene.prototype.getTotalVertices = function () {
  22182. return this._totalVertices.current;
  22183. };
  22184. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22185. get: function () {
  22186. return this._totalVertices;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Scene.prototype.getActiveIndices = function () {
  22192. return this._activeIndices.current;
  22193. };
  22194. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22195. get: function () {
  22196. return this._activeIndices;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Scene.prototype.getActiveParticles = function () {
  22202. return this._activeParticles.current;
  22203. };
  22204. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22205. get: function () {
  22206. return this._activeParticles;
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. Scene.prototype.getActiveBones = function () {
  22212. return this._activeBones.current;
  22213. };
  22214. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22215. get: function () {
  22216. return this._activeBones;
  22217. },
  22218. enumerable: true,
  22219. configurable: true
  22220. });
  22221. // Stats
  22222. Scene.prototype.getInterFramePerfCounter = function () {
  22223. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22224. return 0;
  22225. };
  22226. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22227. get: function () {
  22228. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22229. return null;
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Scene.prototype.getLastFrameDuration = function () {
  22235. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22236. return 0;
  22237. };
  22238. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22239. get: function () {
  22240. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22241. return null;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22247. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22248. return 0;
  22249. };
  22250. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22251. get: function () {
  22252. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22253. return null;
  22254. },
  22255. enumerable: true,
  22256. configurable: true
  22257. });
  22258. Scene.prototype.getActiveMeshes = function () {
  22259. return this._activeMeshes;
  22260. };
  22261. Scene.prototype.getRenderTargetsDuration = function () {
  22262. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22263. return 0;
  22264. };
  22265. Scene.prototype.getRenderDuration = function () {
  22266. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22267. return 0;
  22268. };
  22269. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22270. get: function () {
  22271. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22272. return null;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Scene.prototype.getParticlesDuration = function () {
  22278. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22279. return 0;
  22280. };
  22281. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22282. get: function () {
  22283. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22284. return null;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Scene.prototype.getSpritesDuration = function () {
  22290. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22291. return 0;
  22292. };
  22293. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22294. get: function () {
  22295. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22296. return null;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Scene.prototype.getAnimationRatio = function () {
  22302. return this._animationRatio;
  22303. };
  22304. Scene.prototype.getRenderId = function () {
  22305. return this._renderId;
  22306. };
  22307. Scene.prototype.incrementRenderId = function () {
  22308. this._renderId++;
  22309. };
  22310. Scene.prototype._updatePointerPosition = function (evt) {
  22311. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22312. if (!canvasRect) {
  22313. return;
  22314. }
  22315. this._pointerX = evt.clientX - canvasRect.left;
  22316. this._pointerY = evt.clientY - canvasRect.top;
  22317. this._unTranslatedPointerX = this._pointerX;
  22318. this._unTranslatedPointerY = this._pointerY;
  22319. };
  22320. Scene.prototype._createUbo = function () {
  22321. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22322. this._sceneUbo.addUniform("viewProjection", 16);
  22323. this._sceneUbo.addUniform("view", 16);
  22324. };
  22325. Scene.prototype._createAlternateUbo = function () {
  22326. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22327. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22328. this._alternateSceneUbo.addUniform("view", 16);
  22329. };
  22330. // Pointers handling
  22331. /**
  22332. * Use this method to simulate a pointer move on a mesh
  22333. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22334. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22335. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22336. */
  22337. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22338. var evt = new PointerEvent("pointermove", pointerEventInit);
  22339. return this._processPointerMove(pickResult, evt);
  22340. };
  22341. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22342. var canvas = this._engine.getRenderingCanvas();
  22343. if (!canvas) {
  22344. return this;
  22345. }
  22346. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22347. this.setPointerOverSprite(null);
  22348. this.setPointerOverMesh(pickResult.pickedMesh);
  22349. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22350. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22351. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22352. }
  22353. else {
  22354. canvas.style.cursor = this.hoverCursor;
  22355. }
  22356. }
  22357. else {
  22358. canvas.style.cursor = this.defaultCursor;
  22359. }
  22360. }
  22361. else {
  22362. this.setPointerOverMesh(null);
  22363. // Sprites
  22364. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22365. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22366. this.setPointerOverSprite(pickResult.pickedSprite);
  22367. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22368. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22369. }
  22370. else {
  22371. canvas.style.cursor = this.hoverCursor;
  22372. }
  22373. }
  22374. else {
  22375. this.setPointerOverSprite(null);
  22376. // Restore pointer
  22377. canvas.style.cursor = this.defaultCursor;
  22378. }
  22379. }
  22380. if (pickResult) {
  22381. if (this.onPointerMove) {
  22382. this.onPointerMove(evt, pickResult);
  22383. }
  22384. if (this.onPointerObservable.hasObservers()) {
  22385. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22386. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22387. this.onPointerObservable.notifyObservers(pi, type);
  22388. }
  22389. }
  22390. return this;
  22391. };
  22392. /**
  22393. * Use this method to simulate a pointer down on a mesh
  22394. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22395. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22396. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22397. */
  22398. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22399. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22400. return this._processPointerDown(pickResult, evt);
  22401. };
  22402. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22403. var _this = this;
  22404. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22405. this._pickedDownMesh = pickResult.pickedMesh;
  22406. var actionManager = pickResult.pickedMesh.actionManager;
  22407. if (actionManager) {
  22408. if (actionManager.hasPickTriggers) {
  22409. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22410. switch (evt.button) {
  22411. case 0:
  22412. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22413. break;
  22414. case 1:
  22415. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22416. break;
  22417. case 2:
  22418. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22419. break;
  22420. }
  22421. }
  22422. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22423. window.setTimeout(function () {
  22424. 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);
  22425. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22426. if (_this._totalPointersPressed !== 0 &&
  22427. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22428. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22429. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22430. _this._startingPointerTime = 0;
  22431. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22432. }
  22433. }
  22434. }, Scene.LongPressDelay);
  22435. }
  22436. }
  22437. }
  22438. if (pickResult) {
  22439. if (this.onPointerDown) {
  22440. this.onPointerDown(evt, pickResult);
  22441. }
  22442. if (this.onPointerObservable.hasObservers()) {
  22443. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22444. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22445. this.onPointerObservable.notifyObservers(pi, type);
  22446. }
  22447. }
  22448. return this;
  22449. };
  22450. /**
  22451. * Use this method to simulate a pointer up on a mesh
  22452. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22453. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22454. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22455. */
  22456. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22457. var evt = new PointerEvent("pointerup", pointerEventInit);
  22458. var clickInfo = new ClickInfo();
  22459. clickInfo.singleClick = true;
  22460. clickInfo.ignore = true;
  22461. return this._processPointerUp(pickResult, evt, clickInfo);
  22462. };
  22463. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22464. if (pickResult && pickResult && pickResult.pickedMesh) {
  22465. this._pickedUpMesh = pickResult.pickedMesh;
  22466. if (this._pickedDownMesh === this._pickedUpMesh) {
  22467. if (this.onPointerPick) {
  22468. this.onPointerPick(evt, pickResult);
  22469. }
  22470. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22471. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22472. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22473. this.onPointerObservable.notifyObservers(pi, type);
  22474. }
  22475. }
  22476. if (pickResult.pickedMesh.actionManager) {
  22477. if (clickInfo.ignore) {
  22478. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22479. }
  22480. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22481. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22482. }
  22483. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22484. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22485. }
  22486. }
  22487. }
  22488. if (this._pickedDownMesh &&
  22489. this._pickedDownMesh.actionManager &&
  22490. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22491. this._pickedDownMesh !== this._pickedUpMesh) {
  22492. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22493. }
  22494. if (this.onPointerUp) {
  22495. this.onPointerUp(evt, pickResult);
  22496. }
  22497. if (this.onPointerObservable.hasObservers()) {
  22498. if (!clickInfo.ignore) {
  22499. if (!clickInfo.hasSwiped) {
  22500. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22501. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22502. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22503. this.onPointerObservable.notifyObservers(pi, type);
  22504. }
  22505. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22506. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22507. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22508. this.onPointerObservable.notifyObservers(pi, type);
  22509. }
  22510. }
  22511. }
  22512. else {
  22513. var type = BABYLON.PointerEventTypes.POINTERUP;
  22514. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22515. this.onPointerObservable.notifyObservers(pi, type);
  22516. }
  22517. }
  22518. return this;
  22519. };
  22520. /**
  22521. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22522. * @param attachUp defines if you want to attach events to pointerup
  22523. * @param attachDown defines if you want to attach events to pointerdown
  22524. * @param attachMove defines if you want to attach events to pointermove
  22525. */
  22526. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22527. var _this = this;
  22528. if (attachUp === void 0) { attachUp = true; }
  22529. if (attachDown === void 0) { attachDown = true; }
  22530. if (attachMove === void 0) { attachMove = true; }
  22531. this._initActionManager = function (act, clickInfo) {
  22532. if (!_this._meshPickProceed) {
  22533. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22534. _this._currentPickResult = pickResult;
  22535. if (pickResult) {
  22536. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22537. }
  22538. _this._meshPickProceed = true;
  22539. }
  22540. return act;
  22541. };
  22542. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22543. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22544. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22545. btn !== _this._previousButtonPressed) {
  22546. _this._doubleClickOccured = false;
  22547. clickInfo.singleClick = true;
  22548. clickInfo.ignore = false;
  22549. cb(clickInfo, _this._currentPickResult);
  22550. }
  22551. };
  22552. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22553. var clickInfo = new ClickInfo();
  22554. _this._currentPickResult = null;
  22555. var act = null;
  22556. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22557. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22558. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22559. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22560. act = _this._initActionManager(act, clickInfo);
  22561. if (act)
  22562. checkPicking = act.hasPickTriggers;
  22563. }
  22564. if (checkPicking) {
  22565. var btn = evt.button;
  22566. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22567. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22568. if (!clickInfo.hasSwiped) {
  22569. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22570. if (!checkSingleClickImmediately) {
  22571. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22572. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22573. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22574. act = _this._initActionManager(act, clickInfo);
  22575. if (act)
  22576. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22577. }
  22578. }
  22579. if (checkSingleClickImmediately) {
  22580. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22581. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22582. btn !== _this._previousButtonPressed) {
  22583. clickInfo.singleClick = true;
  22584. cb(clickInfo, _this._currentPickResult);
  22585. }
  22586. }
  22587. else {
  22588. // wait that no double click has been raised during the double click delay
  22589. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22590. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22591. }
  22592. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22593. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22594. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22595. act = _this._initActionManager(act, clickInfo);
  22596. if (act)
  22597. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22598. }
  22599. if (checkDoubleClick) {
  22600. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22601. if (btn === _this._previousButtonPressed &&
  22602. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22603. !_this._doubleClickOccured) {
  22604. // pointer has not moved for 2 clicks, it's a double click
  22605. if (!clickInfo.hasSwiped &&
  22606. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22607. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22608. _this._previousStartingPointerTime = 0;
  22609. _this._doubleClickOccured = true;
  22610. clickInfo.doubleClick = true;
  22611. clickInfo.ignore = false;
  22612. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22613. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22614. }
  22615. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22616. cb(clickInfo, _this._currentPickResult);
  22617. }
  22618. else {
  22619. _this._doubleClickOccured = false;
  22620. _this._previousStartingPointerTime = _this._startingPointerTime;
  22621. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22622. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22623. _this._previousButtonPressed = btn;
  22624. if (Scene.ExclusiveDoubleClickMode) {
  22625. if (_this._previousDelayedSimpleClickTimeout) {
  22626. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22627. }
  22628. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22629. cb(clickInfo, _this._previousPickResult);
  22630. }
  22631. else {
  22632. cb(clickInfo, _this._currentPickResult);
  22633. }
  22634. }
  22635. }
  22636. else {
  22637. _this._doubleClickOccured = false;
  22638. _this._previousStartingPointerTime = _this._startingPointerTime;
  22639. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22640. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22641. _this._previousButtonPressed = btn;
  22642. }
  22643. }
  22644. }
  22645. }
  22646. clickInfo.ignore = true;
  22647. cb(clickInfo, _this._currentPickResult);
  22648. };
  22649. this._spritePredicate = function (sprite) {
  22650. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22651. };
  22652. this._onPointerMove = function (evt) {
  22653. _this._updatePointerPosition(evt);
  22654. // PreObservable support
  22655. if (_this.onPrePointerObservable.hasObservers()) {
  22656. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22657. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22658. _this.onPrePointerObservable.notifyObservers(pi, type);
  22659. if (pi.skipOnPointerObservable) {
  22660. return;
  22661. }
  22662. }
  22663. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22664. return;
  22665. }
  22666. if (!_this.pointerMovePredicate) {
  22667. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22668. }
  22669. // Meshes
  22670. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22671. _this._processPointerMove(pickResult, evt);
  22672. };
  22673. this._onPointerDown = function (evt) {
  22674. _this._totalPointersPressed++;
  22675. _this._pickedDownMesh = null;
  22676. _this._meshPickProceed = false;
  22677. _this._updatePointerPosition(evt);
  22678. if (_this.preventDefaultOnPointerDown && canvas) {
  22679. evt.preventDefault();
  22680. canvas.focus();
  22681. }
  22682. // PreObservable support
  22683. if (_this.onPrePointerObservable.hasObservers()) {
  22684. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22685. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22686. _this.onPrePointerObservable.notifyObservers(pi, type);
  22687. if (pi.skipOnPointerObservable) {
  22688. return;
  22689. }
  22690. }
  22691. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22692. return;
  22693. }
  22694. _this._startingPointerPosition.x = _this._pointerX;
  22695. _this._startingPointerPosition.y = _this._pointerY;
  22696. _this._startingPointerTime = new Date().getTime();
  22697. if (!_this.pointerDownPredicate) {
  22698. _this.pointerDownPredicate = function (mesh) {
  22699. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22700. };
  22701. }
  22702. // Meshes
  22703. _this._pickedDownMesh = null;
  22704. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22705. _this._processPointerDown(pickResult, evt);
  22706. // Sprites
  22707. _this._pickedDownSprite = null;
  22708. if (_this.spriteManagers.length > 0) {
  22709. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22710. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22711. if (pickResult.pickedSprite.actionManager) {
  22712. _this._pickedDownSprite = pickResult.pickedSprite;
  22713. switch (evt.button) {
  22714. case 0:
  22715. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22716. break;
  22717. case 1:
  22718. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22719. break;
  22720. case 2:
  22721. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22722. break;
  22723. }
  22724. if (pickResult.pickedSprite.actionManager) {
  22725. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22726. }
  22727. }
  22728. }
  22729. }
  22730. };
  22731. this._onPointerUp = function (evt) {
  22732. if (_this._totalPointersPressed === 0) {
  22733. return; // So we need to test it the pointer down was pressed before.
  22734. }
  22735. _this._totalPointersPressed--;
  22736. _this._pickedUpMesh = null;
  22737. _this._meshPickProceed = false;
  22738. _this._updatePointerPosition(evt);
  22739. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22740. // PreObservable support
  22741. if (_this.onPrePointerObservable.hasObservers()) {
  22742. if (!clickInfo.ignore) {
  22743. if (!clickInfo.hasSwiped) {
  22744. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22745. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22746. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22747. _this.onPrePointerObservable.notifyObservers(pi, type);
  22748. if (pi.skipOnPointerObservable) {
  22749. return;
  22750. }
  22751. }
  22752. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22753. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  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. }
  22762. else {
  22763. var type = BABYLON.PointerEventTypes.POINTERUP;
  22764. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22765. _this.onPrePointerObservable.notifyObservers(pi, type);
  22766. if (pi.skipOnPointerObservable) {
  22767. return;
  22768. }
  22769. }
  22770. }
  22771. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22772. return;
  22773. }
  22774. if (!_this.pointerUpPredicate) {
  22775. _this.pointerUpPredicate = function (mesh) {
  22776. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22777. };
  22778. }
  22779. // Meshes
  22780. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22781. _this._initActionManager(null, clickInfo);
  22782. }
  22783. if (!pickResult) {
  22784. pickResult = _this._currentPickResult;
  22785. }
  22786. _this._processPointerUp(pickResult, evt, clickInfo);
  22787. // Sprites
  22788. if (_this.spriteManagers.length > 0) {
  22789. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22790. if (spritePickResult) {
  22791. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22792. if (spritePickResult.pickedSprite.actionManager) {
  22793. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22794. if (spritePickResult.pickedSprite.actionManager) {
  22795. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22796. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22797. }
  22798. }
  22799. }
  22800. }
  22801. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22802. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22803. }
  22804. }
  22805. }
  22806. _this._previousPickResult = _this._currentPickResult;
  22807. });
  22808. };
  22809. this._onKeyDown = function (evt) {
  22810. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22811. if (_this.onPreKeyboardObservable.hasObservers()) {
  22812. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22813. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22814. if (pi.skipOnPointerObservable) {
  22815. return;
  22816. }
  22817. }
  22818. if (_this.onKeyboardObservable.hasObservers()) {
  22819. var pi = new BABYLON.KeyboardInfo(type, evt);
  22820. _this.onKeyboardObservable.notifyObservers(pi, type);
  22821. }
  22822. if (_this.actionManager) {
  22823. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22824. }
  22825. };
  22826. this._onKeyUp = function (evt) {
  22827. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22828. if (_this.onPreKeyboardObservable.hasObservers()) {
  22829. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22830. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22831. if (pi.skipOnPointerObservable) {
  22832. return;
  22833. }
  22834. }
  22835. if (_this.onKeyboardObservable.hasObservers()) {
  22836. var pi = new BABYLON.KeyboardInfo(type, evt);
  22837. _this.onKeyboardObservable.notifyObservers(pi, type);
  22838. }
  22839. if (_this.actionManager) {
  22840. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22841. }
  22842. };
  22843. var engine = this.getEngine();
  22844. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22845. if (!canvas) {
  22846. return;
  22847. }
  22848. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22849. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22850. });
  22851. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22852. if (!canvas) {
  22853. return;
  22854. }
  22855. canvas.removeEventListener("keydown", _this._onKeyDown);
  22856. canvas.removeEventListener("keyup", _this._onKeyUp);
  22857. });
  22858. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22859. var canvas = this._engine.getRenderingCanvas();
  22860. if (!canvas) {
  22861. return;
  22862. }
  22863. if (attachMove) {
  22864. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22865. // Wheel
  22866. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22867. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22868. }
  22869. if (attachDown) {
  22870. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22871. }
  22872. if (attachUp) {
  22873. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22874. }
  22875. canvas.tabIndex = 1;
  22876. };
  22877. Scene.prototype.detachControl = function () {
  22878. var engine = this.getEngine();
  22879. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22880. var canvas = engine.getRenderingCanvas();
  22881. if (!canvas) {
  22882. return;
  22883. }
  22884. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22885. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22886. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22887. if (this._onCanvasBlurObserver) {
  22888. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22889. }
  22890. if (this._onCanvasFocusObserver) {
  22891. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22892. }
  22893. // Wheel
  22894. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22895. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22896. // Keyboard
  22897. canvas.removeEventListener("keydown", this._onKeyDown);
  22898. canvas.removeEventListener("keyup", this._onKeyUp);
  22899. // Observables
  22900. this.onKeyboardObservable.clear();
  22901. this.onPreKeyboardObservable.clear();
  22902. this.onPointerObservable.clear();
  22903. this.onPrePointerObservable.clear();
  22904. };
  22905. /**
  22906. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22907. * Delay loaded resources are not taking in account
  22908. * @return true if all required resources are ready
  22909. */
  22910. Scene.prototype.isReady = function () {
  22911. if (this._isDisposed) {
  22912. return false;
  22913. }
  22914. if (this._pendingData.length > 0) {
  22915. return false;
  22916. }
  22917. var index;
  22918. var engine = this.getEngine();
  22919. // Geometries
  22920. for (index = 0; index < this._geometries.length; index++) {
  22921. var geometry = this._geometries[index];
  22922. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22923. return false;
  22924. }
  22925. }
  22926. // Meshes
  22927. for (index = 0; index < this.meshes.length; index++) {
  22928. var mesh = this.meshes[index];
  22929. if (!mesh.isEnabled()) {
  22930. continue;
  22931. }
  22932. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22933. continue;
  22934. }
  22935. if (!mesh.isReady(true)) {
  22936. return false;
  22937. }
  22938. // Effect layers
  22939. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22940. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22941. var layer = _a[_i];
  22942. if (!layer.hasMesh(mesh)) {
  22943. continue;
  22944. }
  22945. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22946. var subMesh = _c[_b];
  22947. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22948. return false;
  22949. }
  22950. }
  22951. }
  22952. }
  22953. return true;
  22954. };
  22955. Scene.prototype.resetCachedMaterial = function () {
  22956. this._cachedMaterial = null;
  22957. this._cachedEffect = null;
  22958. this._cachedVisibility = null;
  22959. };
  22960. Scene.prototype.registerBeforeRender = function (func) {
  22961. this.onBeforeRenderObservable.add(func);
  22962. };
  22963. Scene.prototype.unregisterBeforeRender = function (func) {
  22964. this.onBeforeRenderObservable.removeCallback(func);
  22965. };
  22966. Scene.prototype.registerAfterRender = function (func) {
  22967. this.onAfterRenderObservable.add(func);
  22968. };
  22969. Scene.prototype.unregisterAfterRender = function (func) {
  22970. this.onAfterRenderObservable.removeCallback(func);
  22971. };
  22972. Scene.prototype._executeOnceBeforeRender = function (func) {
  22973. var _this = this;
  22974. var execFunc = function () {
  22975. func();
  22976. setTimeout(function () {
  22977. _this.unregisterBeforeRender(execFunc);
  22978. });
  22979. };
  22980. this.registerBeforeRender(execFunc);
  22981. };
  22982. /**
  22983. * The provided function will run before render once and will be disposed afterwards.
  22984. * A timeout delay can be provided so that the function will be executed in N ms.
  22985. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22986. * @param func The function to be executed.
  22987. * @param timeout optional delay in ms
  22988. */
  22989. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22990. var _this = this;
  22991. if (timeout !== undefined) {
  22992. setTimeout(function () {
  22993. _this._executeOnceBeforeRender(func);
  22994. }, timeout);
  22995. }
  22996. else {
  22997. this._executeOnceBeforeRender(func);
  22998. }
  22999. };
  23000. Scene.prototype._addPendingData = function (data) {
  23001. this._pendingData.push(data);
  23002. };
  23003. Scene.prototype._removePendingData = function (data) {
  23004. var wasLoading = this.isLoading;
  23005. var index = this._pendingData.indexOf(data);
  23006. if (index !== -1) {
  23007. this._pendingData.splice(index, 1);
  23008. }
  23009. if (wasLoading && !this.isLoading) {
  23010. this.onDataLoadedObservable.notifyObservers(this);
  23011. }
  23012. };
  23013. Scene.prototype.getWaitingItemsCount = function () {
  23014. return this._pendingData.length;
  23015. };
  23016. Object.defineProperty(Scene.prototype, "isLoading", {
  23017. get: function () {
  23018. return this._pendingData.length > 0;
  23019. },
  23020. enumerable: true,
  23021. configurable: true
  23022. });
  23023. /**
  23024. * Registers a function to be executed when the scene is ready.
  23025. * @param {Function} func - the function to be executed.
  23026. */
  23027. Scene.prototype.executeWhenReady = function (func) {
  23028. var _this = this;
  23029. this.onReadyObservable.add(func);
  23030. if (this._executeWhenReadyTimeoutId !== -1) {
  23031. return;
  23032. }
  23033. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23034. _this._checkIsReady();
  23035. }, 150);
  23036. };
  23037. /**
  23038. * Returns a promise that resolves when the scene is ready.
  23039. * @returns A promise that resolves when the scene is ready.
  23040. */
  23041. Scene.prototype.whenReadyAsync = function () {
  23042. var _this = this;
  23043. return new Promise(function (resolve) {
  23044. _this.executeWhenReady(function () {
  23045. resolve();
  23046. });
  23047. });
  23048. };
  23049. Scene.prototype._checkIsReady = function () {
  23050. var _this = this;
  23051. if (this.isReady()) {
  23052. this.onReadyObservable.notifyObservers(this);
  23053. this.onReadyObservable.clear();
  23054. this._executeWhenReadyTimeoutId = -1;
  23055. return;
  23056. }
  23057. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23058. _this._checkIsReady();
  23059. }, 150);
  23060. };
  23061. // Animations
  23062. /**
  23063. * Will start the animation sequence of a given target
  23064. * @param target - the target
  23065. * @param {number} from - from which frame should animation start
  23066. * @param {number} to - till which frame should animation run.
  23067. * @param {boolean} [loop] - should the animation loop
  23068. * @param {number} [speedRatio] - the speed in which to run the animation
  23069. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23070. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23071. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23072. * See BABYLON.Animatable
  23073. */
  23074. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23075. if (speedRatio === void 0) { speedRatio = 1.0; }
  23076. if (from > to && speedRatio > 0) {
  23077. speedRatio *= -1;
  23078. }
  23079. this.stopAnimation(target);
  23080. if (!animatable) {
  23081. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23082. }
  23083. // Local animations
  23084. if (target.animations) {
  23085. animatable.appendAnimations(target, target.animations);
  23086. }
  23087. // Children animations
  23088. if (target.getAnimatables) {
  23089. var animatables = target.getAnimatables();
  23090. for (var index = 0; index < animatables.length; index++) {
  23091. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23092. }
  23093. }
  23094. animatable.reset();
  23095. return animatable;
  23096. };
  23097. /**
  23098. * Begin a new animation on a given node
  23099. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23100. * @param {BABYLON.Animation[]} defines the list of animations to start
  23101. * @param {number} from defines the initial value
  23102. * @param {number} to defines the final value
  23103. * @param {boolean} loop defines if you want animation to loop (off by default)
  23104. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23105. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23106. * @returns the list of created animatables
  23107. */
  23108. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23109. if (speedRatio === undefined) {
  23110. speedRatio = 1.0;
  23111. }
  23112. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23113. return animatable;
  23114. };
  23115. /**
  23116. * Begin a new animation on a given node and its hierarchy
  23117. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23118. * @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.
  23119. * @param {BABYLON.Animation[]} defines the list of animations to start
  23120. * @param {number} from defines the initial value
  23121. * @param {number} to defines the final value
  23122. * @param {boolean} loop defines if you want animation to loop (off by default)
  23123. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23124. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23125. * @returns the list of animatables created for all nodes
  23126. */
  23127. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23128. var children = target.getDescendants(directDescendantsOnly);
  23129. var result = [];
  23130. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23131. var child = children_1[_i];
  23132. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23133. }
  23134. return result;
  23135. };
  23136. Scene.prototype.getAnimatableByTarget = function (target) {
  23137. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23138. if (this._activeAnimatables[index].target === target) {
  23139. return this._activeAnimatables[index];
  23140. }
  23141. }
  23142. return null;
  23143. };
  23144. Object.defineProperty(Scene.prototype, "animatables", {
  23145. get: function () {
  23146. return this._activeAnimatables;
  23147. },
  23148. enumerable: true,
  23149. configurable: true
  23150. });
  23151. /**
  23152. * Will stop the animation of the given target
  23153. * @param target - the target
  23154. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23155. * @see beginAnimation
  23156. */
  23157. Scene.prototype.stopAnimation = function (target, animationName) {
  23158. var animatable = this.getAnimatableByTarget(target);
  23159. if (animatable) {
  23160. animatable.stop(animationName);
  23161. }
  23162. };
  23163. /**
  23164. * Stops and removes all animations that have been applied to the scene
  23165. */
  23166. Scene.prototype.stopAllAnimations = function () {
  23167. if (this._activeAnimatables) {
  23168. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23169. this._activeAnimatables[i].stop();
  23170. }
  23171. this._activeAnimatables = [];
  23172. }
  23173. };
  23174. Scene.prototype._animate = function () {
  23175. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23176. return;
  23177. }
  23178. // Getting time
  23179. var now = BABYLON.Tools.Now;
  23180. if (!this._animationTimeLast) {
  23181. if (this._pendingData.length > 0) {
  23182. return;
  23183. }
  23184. this._animationTimeLast = now;
  23185. }
  23186. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23187. this._animationTime += deltaTime;
  23188. this._animationTimeLast = now;
  23189. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23190. this._activeAnimatables[index]._animate(this._animationTime);
  23191. }
  23192. };
  23193. // Matrix
  23194. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23195. this._useAlternateCameraConfiguration = active;
  23196. };
  23197. Scene.prototype.getViewMatrix = function () {
  23198. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23199. };
  23200. Scene.prototype.getProjectionMatrix = function () {
  23201. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23202. };
  23203. Scene.prototype.getTransformMatrix = function () {
  23204. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23205. };
  23206. Scene.prototype.setTransformMatrix = function (view, projection) {
  23207. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23208. return;
  23209. }
  23210. this._viewUpdateFlag = view.updateFlag;
  23211. this._projectionUpdateFlag = projection.updateFlag;
  23212. this._viewMatrix = view;
  23213. this._projectionMatrix = projection;
  23214. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23215. // Update frustum
  23216. if (!this._frustumPlanes) {
  23217. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23218. }
  23219. else {
  23220. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23221. }
  23222. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23223. var otherCamera = this.activeCamera._alternateCamera;
  23224. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23225. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23226. }
  23227. if (this._sceneUbo.useUbo) {
  23228. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23229. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23230. this._sceneUbo.update();
  23231. }
  23232. };
  23233. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23234. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23235. return;
  23236. }
  23237. this._alternateViewUpdateFlag = view.updateFlag;
  23238. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23239. this._alternateViewMatrix = view;
  23240. this._alternateProjectionMatrix = projection;
  23241. if (!this._alternateTransformMatrix) {
  23242. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23243. }
  23244. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23245. if (!this._alternateSceneUbo) {
  23246. this._createAlternateUbo();
  23247. }
  23248. if (this._alternateSceneUbo.useUbo) {
  23249. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23250. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23251. this._alternateSceneUbo.update();
  23252. }
  23253. };
  23254. Scene.prototype.getSceneUniformBuffer = function () {
  23255. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23256. };
  23257. // Methods
  23258. Scene.prototype.getUniqueId = function () {
  23259. var result = Scene._uniqueIdCounter;
  23260. Scene._uniqueIdCounter++;
  23261. return result;
  23262. };
  23263. Scene.prototype.addMesh = function (newMesh) {
  23264. this.meshes.push(newMesh);
  23265. //notify the collision coordinator
  23266. if (this.collisionCoordinator) {
  23267. this.collisionCoordinator.onMeshAdded(newMesh);
  23268. }
  23269. newMesh._resyncLightSources();
  23270. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23271. };
  23272. Scene.prototype.removeMesh = function (toRemove) {
  23273. var index = this.meshes.indexOf(toRemove);
  23274. if (index !== -1) {
  23275. // Remove from the scene if mesh found
  23276. this.meshes.splice(index, 1);
  23277. }
  23278. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23279. return index;
  23280. };
  23281. Scene.prototype.addTransformNode = function (newTransformNode) {
  23282. this.transformNodes.push(newTransformNode);
  23283. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23284. };
  23285. Scene.prototype.removeTransformNode = function (toRemove) {
  23286. var index = this.transformNodes.indexOf(toRemove);
  23287. if (index !== -1) {
  23288. // Remove from the scene if found
  23289. this.transformNodes.splice(index, 1);
  23290. }
  23291. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23292. return index;
  23293. };
  23294. Scene.prototype.removeSkeleton = function (toRemove) {
  23295. var index = this.skeletons.indexOf(toRemove);
  23296. if (index !== -1) {
  23297. // Remove from the scene if found
  23298. this.skeletons.splice(index, 1);
  23299. }
  23300. return index;
  23301. };
  23302. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23303. var index = this.morphTargetManagers.indexOf(toRemove);
  23304. if (index !== -1) {
  23305. // Remove from the scene if found
  23306. this.morphTargetManagers.splice(index, 1);
  23307. }
  23308. return index;
  23309. };
  23310. Scene.prototype.removeLight = function (toRemove) {
  23311. var index = this.lights.indexOf(toRemove);
  23312. if (index !== -1) {
  23313. // Remove from meshes
  23314. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23315. var mesh = _a[_i];
  23316. mesh._removeLightSource(toRemove);
  23317. }
  23318. // Remove from the scene if mesh found
  23319. this.lights.splice(index, 1);
  23320. this.sortLightsByPriority();
  23321. }
  23322. this.onLightRemovedObservable.notifyObservers(toRemove);
  23323. return index;
  23324. };
  23325. Scene.prototype.removeCamera = function (toRemove) {
  23326. var index = this.cameras.indexOf(toRemove);
  23327. if (index !== -1) {
  23328. // Remove from the scene if mesh found
  23329. this.cameras.splice(index, 1);
  23330. }
  23331. // Remove from activeCameras
  23332. var index2 = this.activeCameras.indexOf(toRemove);
  23333. if (index2 !== -1) {
  23334. // Remove from the scene if mesh found
  23335. this.activeCameras.splice(index2, 1);
  23336. }
  23337. // Reset the activeCamera
  23338. if (this.activeCamera === toRemove) {
  23339. if (this.cameras.length > 0) {
  23340. this.activeCamera = this.cameras[0];
  23341. }
  23342. else {
  23343. this.activeCamera = null;
  23344. }
  23345. }
  23346. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23347. return index;
  23348. };
  23349. Scene.prototype.removeParticleSystem = function (toRemove) {
  23350. var index = this.particleSystems.indexOf(toRemove);
  23351. if (index !== -1) {
  23352. this.particleSystems.splice(index, 1);
  23353. }
  23354. return index;
  23355. };
  23356. ;
  23357. Scene.prototype.removeAnimation = function (toRemove) {
  23358. var index = this.animations.indexOf(toRemove);
  23359. if (index !== -1) {
  23360. this.animations.splice(index, 1);
  23361. }
  23362. return index;
  23363. };
  23364. ;
  23365. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23366. var index = this.multiMaterials.indexOf(toRemove);
  23367. if (index !== -1) {
  23368. this.multiMaterials.splice(index, 1);
  23369. }
  23370. return index;
  23371. };
  23372. ;
  23373. Scene.prototype.removeMaterial = function (toRemove) {
  23374. var index = this.materials.indexOf(toRemove);
  23375. if (index !== -1) {
  23376. this.materials.splice(index, 1);
  23377. }
  23378. return index;
  23379. };
  23380. ;
  23381. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23382. var index = this.lensFlareSystems.indexOf(toRemove);
  23383. if (index !== -1) {
  23384. this.lensFlareSystems.splice(index, 1);
  23385. }
  23386. return index;
  23387. };
  23388. ;
  23389. Scene.prototype.removeActionManager = function (toRemove) {
  23390. var index = this._actionManagers.indexOf(toRemove);
  23391. if (index !== -1) {
  23392. this._actionManagers.splice(index, 1);
  23393. }
  23394. return index;
  23395. };
  23396. ;
  23397. Scene.prototype.addLight = function (newLight) {
  23398. this.lights.push(newLight);
  23399. this.sortLightsByPriority();
  23400. // Add light to all meshes (To support if the light is removed and then readded)
  23401. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23402. var mesh = _a[_i];
  23403. if (mesh._lightSources.indexOf(newLight) === -1) {
  23404. mesh._lightSources.push(newLight);
  23405. mesh._resyncLightSources();
  23406. }
  23407. }
  23408. this.onNewLightAddedObservable.notifyObservers(newLight);
  23409. };
  23410. Scene.prototype.sortLightsByPriority = function () {
  23411. if (this.requireLightSorting) {
  23412. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23413. }
  23414. };
  23415. Scene.prototype.addCamera = function (newCamera) {
  23416. this.cameras.push(newCamera);
  23417. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23418. };
  23419. Scene.prototype.addSkeleton = function (newSkeleton) {
  23420. this.skeletons.push(newSkeleton);
  23421. };
  23422. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23423. this.particleSystems.push(newParticleSystem);
  23424. };
  23425. Scene.prototype.addAnimation = function (newAnimation) {
  23426. this.animations.push(newAnimation);
  23427. };
  23428. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23429. this.multiMaterials.push(newMultiMaterial);
  23430. };
  23431. Scene.prototype.addMaterial = function (newMaterial) {
  23432. this.materials.push(newMaterial);
  23433. };
  23434. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23435. this.morphTargetManagers.push(newMorphTargetManager);
  23436. };
  23437. Scene.prototype.addGeometry = function (newGeometrie) {
  23438. this._geometries.push(newGeometrie);
  23439. };
  23440. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23441. this.lensFlareSystems.push(newLensFlareSystem);
  23442. };
  23443. Scene.prototype.addActionManager = function (newActionManager) {
  23444. this._actionManagers.push(newActionManager);
  23445. };
  23446. /**
  23447. * Switch active camera
  23448. * @param {Camera} newCamera - new active camera
  23449. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23450. */
  23451. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23452. if (attachControl === void 0) { attachControl = true; }
  23453. var canvas = this._engine.getRenderingCanvas();
  23454. if (!canvas) {
  23455. return;
  23456. }
  23457. if (this.activeCamera) {
  23458. this.activeCamera.detachControl(canvas);
  23459. }
  23460. this.activeCamera = newCamera;
  23461. if (attachControl) {
  23462. newCamera.attachControl(canvas);
  23463. }
  23464. };
  23465. /**
  23466. * sets the active camera of the scene using its ID
  23467. * @param {string} id - the camera's ID
  23468. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23469. * @see activeCamera
  23470. */
  23471. Scene.prototype.setActiveCameraByID = function (id) {
  23472. var camera = this.getCameraByID(id);
  23473. if (camera) {
  23474. this.activeCamera = camera;
  23475. return camera;
  23476. }
  23477. return null;
  23478. };
  23479. /**
  23480. * sets the active camera of the scene using its name
  23481. * @param {string} name - the camera's name
  23482. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23483. * @see activeCamera
  23484. */
  23485. Scene.prototype.setActiveCameraByName = function (name) {
  23486. var camera = this.getCameraByName(name);
  23487. if (camera) {
  23488. this.activeCamera = camera;
  23489. return camera;
  23490. }
  23491. return null;
  23492. };
  23493. /**
  23494. * get an animation group using its name
  23495. * @param {string} the material's name
  23496. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23497. */
  23498. Scene.prototype.getAnimationGroupByName = function (name) {
  23499. for (var index = 0; index < this.animationGroups.length; index++) {
  23500. if (this.animationGroups[index].name === name) {
  23501. return this.animationGroups[index];
  23502. }
  23503. }
  23504. return null;
  23505. };
  23506. /**
  23507. * get a material using its id
  23508. * @param {string} the material's ID
  23509. * @return {BABYLON.Material|null} the material or null if none found.
  23510. */
  23511. Scene.prototype.getMaterialByID = function (id) {
  23512. for (var index = 0; index < this.materials.length; index++) {
  23513. if (this.materials[index].id === id) {
  23514. return this.materials[index];
  23515. }
  23516. }
  23517. return null;
  23518. };
  23519. /**
  23520. * get a material using its name
  23521. * @param {string} the material's name
  23522. * @return {BABYLON.Material|null} the material or null if none found.
  23523. */
  23524. Scene.prototype.getMaterialByName = function (name) {
  23525. for (var index = 0; index < this.materials.length; index++) {
  23526. if (this.materials[index].name === name) {
  23527. return this.materials[index];
  23528. }
  23529. }
  23530. return null;
  23531. };
  23532. Scene.prototype.getLensFlareSystemByName = function (name) {
  23533. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23534. if (this.lensFlareSystems[index].name === name) {
  23535. return this.lensFlareSystems[index];
  23536. }
  23537. }
  23538. return null;
  23539. };
  23540. Scene.prototype.getLensFlareSystemByID = function (id) {
  23541. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23542. if (this.lensFlareSystems[index].id === id) {
  23543. return this.lensFlareSystems[index];
  23544. }
  23545. }
  23546. return null;
  23547. };
  23548. Scene.prototype.getCameraByID = function (id) {
  23549. for (var index = 0; index < this.cameras.length; index++) {
  23550. if (this.cameras[index].id === id) {
  23551. return this.cameras[index];
  23552. }
  23553. }
  23554. return null;
  23555. };
  23556. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23557. for (var index = 0; index < this.cameras.length; index++) {
  23558. if (this.cameras[index].uniqueId === uniqueId) {
  23559. return this.cameras[index];
  23560. }
  23561. }
  23562. return null;
  23563. };
  23564. /**
  23565. * get a camera using its name
  23566. * @param {string} the camera's name
  23567. * @return {BABYLON.Camera|null} the camera or null if none found.
  23568. */
  23569. Scene.prototype.getCameraByName = function (name) {
  23570. for (var index = 0; index < this.cameras.length; index++) {
  23571. if (this.cameras[index].name === name) {
  23572. return this.cameras[index];
  23573. }
  23574. }
  23575. return null;
  23576. };
  23577. /**
  23578. * get a bone using its id
  23579. * @param {string} the bone's id
  23580. * @return {BABYLON.Bone|null} the bone or null if not found
  23581. */
  23582. Scene.prototype.getBoneByID = function (id) {
  23583. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23584. var skeleton = this.skeletons[skeletonIndex];
  23585. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23586. if (skeleton.bones[boneIndex].id === id) {
  23587. return skeleton.bones[boneIndex];
  23588. }
  23589. }
  23590. }
  23591. return null;
  23592. };
  23593. /**
  23594. * get a bone using its id
  23595. * @param {string} the bone's name
  23596. * @return {BABYLON.Bone|null} the bone or null if not found
  23597. */
  23598. Scene.prototype.getBoneByName = function (name) {
  23599. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23600. var skeleton = this.skeletons[skeletonIndex];
  23601. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23602. if (skeleton.bones[boneIndex].name === name) {
  23603. return skeleton.bones[boneIndex];
  23604. }
  23605. }
  23606. }
  23607. return null;
  23608. };
  23609. /**
  23610. * get a light node using its name
  23611. * @param {string} the light's name
  23612. * @return {BABYLON.Light|null} the light or null if none found.
  23613. */
  23614. Scene.prototype.getLightByName = function (name) {
  23615. for (var index = 0; index < this.lights.length; index++) {
  23616. if (this.lights[index].name === name) {
  23617. return this.lights[index];
  23618. }
  23619. }
  23620. return null;
  23621. };
  23622. /**
  23623. * get a light node using its ID
  23624. * @param {string} the light's id
  23625. * @return {BABYLON.Light|null} the light or null if none found.
  23626. */
  23627. Scene.prototype.getLightByID = function (id) {
  23628. for (var index = 0; index < this.lights.length; index++) {
  23629. if (this.lights[index].id === id) {
  23630. return this.lights[index];
  23631. }
  23632. }
  23633. return null;
  23634. };
  23635. /**
  23636. * get a light node using its scene-generated unique ID
  23637. * @param {number} the light's unique id
  23638. * @return {BABYLON.Light|null} the light or null if none found.
  23639. */
  23640. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23641. for (var index = 0; index < this.lights.length; index++) {
  23642. if (this.lights[index].uniqueId === uniqueId) {
  23643. return this.lights[index];
  23644. }
  23645. }
  23646. return null;
  23647. };
  23648. /**
  23649. * get a particle system by id
  23650. * @param id {number} the particle system id
  23651. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23652. */
  23653. Scene.prototype.getParticleSystemByID = function (id) {
  23654. for (var index = 0; index < this.particleSystems.length; index++) {
  23655. if (this.particleSystems[index].id === id) {
  23656. return this.particleSystems[index];
  23657. }
  23658. }
  23659. return null;
  23660. };
  23661. /**
  23662. * get a geometry using its ID
  23663. * @param {string} the geometry's id
  23664. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23665. */
  23666. Scene.prototype.getGeometryByID = function (id) {
  23667. for (var index = 0; index < this._geometries.length; index++) {
  23668. if (this._geometries[index].id === id) {
  23669. return this._geometries[index];
  23670. }
  23671. }
  23672. return null;
  23673. };
  23674. /**
  23675. * add a new geometry to this scene.
  23676. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23677. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23678. * @return {boolean} was the geometry added or not
  23679. */
  23680. Scene.prototype.pushGeometry = function (geometry, force) {
  23681. if (!force && this.getGeometryByID(geometry.id)) {
  23682. return false;
  23683. }
  23684. this._geometries.push(geometry);
  23685. //notify the collision coordinator
  23686. if (this.collisionCoordinator) {
  23687. this.collisionCoordinator.onGeometryAdded(geometry);
  23688. }
  23689. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23690. return true;
  23691. };
  23692. /**
  23693. * Removes an existing geometry
  23694. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23695. * @return {boolean} was the geometry removed or not
  23696. */
  23697. Scene.prototype.removeGeometry = function (geometry) {
  23698. var index = this._geometries.indexOf(geometry);
  23699. if (index > -1) {
  23700. this._geometries.splice(index, 1);
  23701. //notify the collision coordinator
  23702. if (this.collisionCoordinator) {
  23703. this.collisionCoordinator.onGeometryDeleted(geometry);
  23704. }
  23705. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23706. return true;
  23707. }
  23708. return false;
  23709. };
  23710. Scene.prototype.getGeometries = function () {
  23711. return this._geometries;
  23712. };
  23713. /**
  23714. * Get the first added mesh found of a given ID
  23715. * @param {string} id - the id to search for
  23716. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23717. */
  23718. Scene.prototype.getMeshByID = function (id) {
  23719. for (var index = 0; index < this.meshes.length; index++) {
  23720. if (this.meshes[index].id === id) {
  23721. return this.meshes[index];
  23722. }
  23723. }
  23724. return null;
  23725. };
  23726. Scene.prototype.getMeshesByID = function (id) {
  23727. return this.meshes.filter(function (m) {
  23728. return m.id === id;
  23729. });
  23730. };
  23731. /**
  23732. * Get the first added transform node found of a given ID
  23733. * @param {string} id - the id to search for
  23734. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23735. */
  23736. Scene.prototype.getTransformNodeByID = function (id) {
  23737. for (var index = 0; index < this.transformNodes.length; index++) {
  23738. if (this.transformNodes[index].id === id) {
  23739. return this.transformNodes[index];
  23740. }
  23741. }
  23742. return null;
  23743. };
  23744. Scene.prototype.getTransformNodesByID = function (id) {
  23745. return this.transformNodes.filter(function (m) {
  23746. return m.id === id;
  23747. });
  23748. };
  23749. /**
  23750. * Get a mesh with its auto-generated unique id
  23751. * @param {number} uniqueId - the unique id to search for
  23752. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23753. */
  23754. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23755. for (var index = 0; index < this.meshes.length; index++) {
  23756. if (this.meshes[index].uniqueId === uniqueId) {
  23757. return this.meshes[index];
  23758. }
  23759. }
  23760. return null;
  23761. };
  23762. /**
  23763. * Get a the last added mesh found of a given ID
  23764. * @param {string} id - the id to search for
  23765. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23766. */
  23767. Scene.prototype.getLastMeshByID = function (id) {
  23768. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23769. if (this.meshes[index].id === id) {
  23770. return this.meshes[index];
  23771. }
  23772. }
  23773. return null;
  23774. };
  23775. /**
  23776. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23777. * @param {string} id - the id to search for
  23778. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23779. */
  23780. Scene.prototype.getLastEntryByID = function (id) {
  23781. var index;
  23782. for (index = this.meshes.length - 1; index >= 0; index--) {
  23783. if (this.meshes[index].id === id) {
  23784. return this.meshes[index];
  23785. }
  23786. }
  23787. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23788. if (this.transformNodes[index].id === id) {
  23789. return this.transformNodes[index];
  23790. }
  23791. }
  23792. for (index = this.cameras.length - 1; index >= 0; index--) {
  23793. if (this.cameras[index].id === id) {
  23794. return this.cameras[index];
  23795. }
  23796. }
  23797. for (index = this.lights.length - 1; index >= 0; index--) {
  23798. if (this.lights[index].id === id) {
  23799. return this.lights[index];
  23800. }
  23801. }
  23802. return null;
  23803. };
  23804. Scene.prototype.getNodeByID = function (id) {
  23805. var mesh = this.getMeshByID(id);
  23806. if (mesh) {
  23807. return mesh;
  23808. }
  23809. var light = this.getLightByID(id);
  23810. if (light) {
  23811. return light;
  23812. }
  23813. var camera = this.getCameraByID(id);
  23814. if (camera) {
  23815. return camera;
  23816. }
  23817. var bone = this.getBoneByID(id);
  23818. return bone;
  23819. };
  23820. Scene.prototype.getNodeByName = function (name) {
  23821. var mesh = this.getMeshByName(name);
  23822. if (mesh) {
  23823. return mesh;
  23824. }
  23825. var light = this.getLightByName(name);
  23826. if (light) {
  23827. return light;
  23828. }
  23829. var camera = this.getCameraByName(name);
  23830. if (camera) {
  23831. return camera;
  23832. }
  23833. var bone = this.getBoneByName(name);
  23834. return bone;
  23835. };
  23836. Scene.prototype.getMeshByName = function (name) {
  23837. for (var index = 0; index < this.meshes.length; index++) {
  23838. if (this.meshes[index].name === name) {
  23839. return this.meshes[index];
  23840. }
  23841. }
  23842. return null;
  23843. };
  23844. Scene.prototype.getTransformNodeByName = function (name) {
  23845. for (var index = 0; index < this.transformNodes.length; index++) {
  23846. if (this.transformNodes[index].name === name) {
  23847. return this.transformNodes[index];
  23848. }
  23849. }
  23850. return null;
  23851. };
  23852. Scene.prototype.getSoundByName = function (name) {
  23853. var index;
  23854. if (BABYLON.AudioEngine) {
  23855. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23856. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23857. return this.mainSoundTrack.soundCollection[index];
  23858. }
  23859. }
  23860. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23861. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23862. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23863. return this.soundTracks[sdIndex].soundCollection[index];
  23864. }
  23865. }
  23866. }
  23867. }
  23868. return null;
  23869. };
  23870. Scene.prototype.getLastSkeletonByID = function (id) {
  23871. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23872. if (this.skeletons[index].id === id) {
  23873. return this.skeletons[index];
  23874. }
  23875. }
  23876. return null;
  23877. };
  23878. Scene.prototype.getSkeletonById = function (id) {
  23879. for (var index = 0; index < this.skeletons.length; index++) {
  23880. if (this.skeletons[index].id === id) {
  23881. return this.skeletons[index];
  23882. }
  23883. }
  23884. return null;
  23885. };
  23886. Scene.prototype.getSkeletonByName = function (name) {
  23887. for (var index = 0; index < this.skeletons.length; index++) {
  23888. if (this.skeletons[index].name === name) {
  23889. return this.skeletons[index];
  23890. }
  23891. }
  23892. return null;
  23893. };
  23894. Scene.prototype.getMorphTargetManagerById = function (id) {
  23895. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23896. if (this.morphTargetManagers[index].uniqueId === id) {
  23897. return this.morphTargetManagers[index];
  23898. }
  23899. }
  23900. return null;
  23901. };
  23902. Scene.prototype.isActiveMesh = function (mesh) {
  23903. return (this._activeMeshes.indexOf(mesh) !== -1);
  23904. };
  23905. /**
  23906. * Return a the first highlight layer of the scene with a given name.
  23907. * @param name The name of the highlight layer to look for.
  23908. * @return The highlight layer if found otherwise null.
  23909. */
  23910. Scene.prototype.getHighlightLayerByName = function (name) {
  23911. for (var index = 0; index < this.effectLayers.length; index++) {
  23912. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23913. return this.effectLayers[index];
  23914. }
  23915. }
  23916. return null;
  23917. };
  23918. /**
  23919. * Return a the first highlight layer of the scene with a given name.
  23920. * @param name The name of the highlight layer to look for.
  23921. * @return The highlight layer if found otherwise null.
  23922. */
  23923. Scene.prototype.getGlowLayerByName = function (name) {
  23924. for (var index = 0; index < this.effectLayers.length; index++) {
  23925. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23926. return this.effectLayers[index];
  23927. }
  23928. }
  23929. return null;
  23930. };
  23931. Object.defineProperty(Scene.prototype, "uid", {
  23932. /**
  23933. * Return a unique id as a string which can serve as an identifier for the scene
  23934. */
  23935. get: function () {
  23936. if (!this._uid) {
  23937. this._uid = BABYLON.Tools.RandomId();
  23938. }
  23939. return this._uid;
  23940. },
  23941. enumerable: true,
  23942. configurable: true
  23943. });
  23944. /**
  23945. * Add an externaly attached data from its key.
  23946. * This method call will fail and return false, if such key already exists.
  23947. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23948. * @param key the unique key that identifies the data
  23949. * @param data the data object to associate to the key for this Engine instance
  23950. * @return true if no such key were already present and the data was added successfully, false otherwise
  23951. */
  23952. Scene.prototype.addExternalData = function (key, data) {
  23953. if (!this._externalData) {
  23954. this._externalData = new BABYLON.StringDictionary();
  23955. }
  23956. return this._externalData.add(key, data);
  23957. };
  23958. /**
  23959. * Get an externaly attached data from its key
  23960. * @param key the unique key that identifies the data
  23961. * @return the associated data, if present (can be null), or undefined if not present
  23962. */
  23963. Scene.prototype.getExternalData = function (key) {
  23964. if (!this._externalData) {
  23965. return null;
  23966. }
  23967. return this._externalData.get(key);
  23968. };
  23969. /**
  23970. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23971. * @param key the unique key that identifies the data
  23972. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23973. * @return the associated data, can be null if the factory returned null.
  23974. */
  23975. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23976. if (!this._externalData) {
  23977. this._externalData = new BABYLON.StringDictionary();
  23978. }
  23979. return this._externalData.getOrAddWithFactory(key, factory);
  23980. };
  23981. /**
  23982. * Remove an externaly attached data from the Engine instance
  23983. * @param key the unique key that identifies the data
  23984. * @return true if the data was successfully removed, false if it doesn't exist
  23985. */
  23986. Scene.prototype.removeExternalData = function (key) {
  23987. return this._externalData.remove(key);
  23988. };
  23989. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23990. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23991. if (mesh.showSubMeshesBoundingBox) {
  23992. var boundingInfo = subMesh.getBoundingInfo();
  23993. if (boundingInfo !== null && boundingInfo !== undefined) {
  23994. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23995. }
  23996. }
  23997. var material = subMesh.getMaterial();
  23998. if (material !== null && material !== undefined) {
  23999. // Render targets
  24000. if (material.getRenderTargetTextures !== undefined) {
  24001. if (this._processedMaterials.indexOf(material) === -1) {
  24002. this._processedMaterials.push(material);
  24003. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24004. }
  24005. }
  24006. // Dispatch
  24007. this._activeIndices.addCount(subMesh.indexCount, false);
  24008. this._renderingManager.dispatch(subMesh, mesh, material);
  24009. }
  24010. }
  24011. };
  24012. /**
  24013. * Clear the processed materials smart array preventing retention point in material dispose.
  24014. */
  24015. Scene.prototype.freeProcessedMaterials = function () {
  24016. this._processedMaterials.dispose();
  24017. };
  24018. /**
  24019. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24020. */
  24021. Scene.prototype.freeActiveMeshes = function () {
  24022. this._activeMeshes.dispose();
  24023. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24024. this.activeCamera._activeMeshes.dispose();
  24025. }
  24026. if (this.activeCameras) {
  24027. for (var i = 0; i < this.activeCameras.length; i++) {
  24028. var activeCamera = this.activeCameras[i];
  24029. if (activeCamera && activeCamera._activeMeshes) {
  24030. activeCamera._activeMeshes.dispose();
  24031. }
  24032. }
  24033. }
  24034. };
  24035. /**
  24036. * Clear the info related to rendering groups preventing retention points during dispose.
  24037. */
  24038. Scene.prototype.freeRenderingGroups = function () {
  24039. if (this._renderingManager) {
  24040. this._renderingManager.freeRenderingGroups();
  24041. }
  24042. if (this.textures) {
  24043. for (var i = 0; i < this.textures.length; i++) {
  24044. var texture = this.textures[i];
  24045. if (texture && texture.isRenderTarget) {
  24046. texture.freeRenderingGroups();
  24047. }
  24048. }
  24049. }
  24050. };
  24051. Scene.prototype._isInIntermediateRendering = function () {
  24052. return this._intermediateRendering;
  24053. };
  24054. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24055. this._activeMeshCandidateProvider = provider;
  24056. };
  24057. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24058. return this._activeMeshCandidateProvider;
  24059. };
  24060. /**
  24061. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24062. */
  24063. Scene.prototype.freezeActiveMeshes = function () {
  24064. this._evaluateActiveMeshes();
  24065. this._activeMeshesFrozen = true;
  24066. return this;
  24067. };
  24068. /**
  24069. * Use this function to restart evaluating active meshes on every frame
  24070. */
  24071. Scene.prototype.unfreezeActiveMeshes = function () {
  24072. this._activeMeshesFrozen = false;
  24073. return this;
  24074. };
  24075. Scene.prototype._evaluateActiveMeshes = function () {
  24076. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24077. return;
  24078. }
  24079. if (!this.activeCamera) {
  24080. return;
  24081. }
  24082. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24083. this.activeCamera._activeMeshes.reset();
  24084. this._activeMeshes.reset();
  24085. this._renderingManager.reset();
  24086. this._processedMaterials.reset();
  24087. this._activeParticleSystems.reset();
  24088. this._activeSkeletons.reset();
  24089. this._softwareSkinnedMeshes.reset();
  24090. if (this._boundingBoxRenderer) {
  24091. this._boundingBoxRenderer.reset();
  24092. }
  24093. // Meshes
  24094. var meshes;
  24095. var len;
  24096. var checkIsEnabled = true;
  24097. // Determine mesh candidates
  24098. if (this._activeMeshCandidateProvider !== undefined) {
  24099. // Use _activeMeshCandidateProvider
  24100. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24101. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24102. if (meshes !== undefined) {
  24103. len = meshes.length;
  24104. }
  24105. else {
  24106. len = 0;
  24107. }
  24108. }
  24109. else if (this._selectionOctree !== undefined) {
  24110. // Octree
  24111. var selection = this._selectionOctree.select(this._frustumPlanes);
  24112. meshes = selection.data;
  24113. len = selection.length;
  24114. }
  24115. else {
  24116. // Full scene traversal
  24117. len = this.meshes.length;
  24118. meshes = this.meshes;
  24119. }
  24120. // Check each mesh
  24121. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24122. mesh = meshes[meshIndex];
  24123. if (mesh.isBlocked) {
  24124. continue;
  24125. }
  24126. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24127. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24128. continue;
  24129. }
  24130. mesh.computeWorldMatrix();
  24131. // Intersections
  24132. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24133. this._meshesForIntersections.pushNoDuplicate(mesh);
  24134. }
  24135. // Switch to current LOD
  24136. meshLOD = mesh.getLOD(this.activeCamera);
  24137. if (meshLOD === undefined || meshLOD === null) {
  24138. continue;
  24139. }
  24140. mesh._preActivate();
  24141. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24142. this._activeMeshes.push(mesh);
  24143. this.activeCamera._activeMeshes.push(mesh);
  24144. mesh._activate(this._renderId);
  24145. if (meshLOD !== mesh) {
  24146. meshLOD._activate(this._renderId);
  24147. }
  24148. this._activeMesh(mesh, meshLOD);
  24149. }
  24150. }
  24151. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24152. // Particle systems
  24153. if (this.particlesEnabled) {
  24154. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24155. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24156. var particleSystem = this.particleSystems[particleIndex];
  24157. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24158. continue;
  24159. }
  24160. var emitter = particleSystem.emitter;
  24161. if (!emitter.position || emitter.isEnabled()) {
  24162. this._activeParticleSystems.push(particleSystem);
  24163. particleSystem.animate();
  24164. this._renderingManager.dispatchParticles(particleSystem);
  24165. }
  24166. }
  24167. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24168. }
  24169. };
  24170. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24171. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24172. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24173. mesh.skeleton.prepare();
  24174. }
  24175. if (!mesh.computeBonesUsingShaders) {
  24176. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24177. }
  24178. }
  24179. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24180. var boundingInfo = sourceMesh.getBoundingInfo();
  24181. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24182. }
  24183. if (mesh !== undefined && mesh !== null
  24184. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24185. // Submeshes Octrees
  24186. var len;
  24187. var subMeshes;
  24188. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24189. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24190. len = intersections.length;
  24191. subMeshes = intersections.data;
  24192. }
  24193. else {
  24194. subMeshes = mesh.subMeshes;
  24195. len = subMeshes.length;
  24196. }
  24197. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24198. subMesh = subMeshes[subIndex];
  24199. this._evaluateSubMesh(subMesh, mesh);
  24200. }
  24201. }
  24202. };
  24203. Scene.prototype.updateTransformMatrix = function (force) {
  24204. if (!this.activeCamera) {
  24205. return;
  24206. }
  24207. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24208. };
  24209. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24210. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24211. };
  24212. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24213. if (camera && camera._skipRendering) {
  24214. return;
  24215. }
  24216. var engine = this._engine;
  24217. this.activeCamera = camera;
  24218. if (!this.activeCamera)
  24219. throw new Error("Active camera not set");
  24220. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24221. // Viewport
  24222. engine.setViewport(this.activeCamera.viewport);
  24223. // Camera
  24224. this.resetCachedMaterial();
  24225. this._renderId++;
  24226. this.updateTransformMatrix();
  24227. if (camera._alternateCamera) {
  24228. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24229. this._alternateRendering = true;
  24230. }
  24231. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24232. // Meshes
  24233. this._evaluateActiveMeshes();
  24234. // Software skinning
  24235. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24236. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24237. mesh.applySkeleton(mesh.skeleton);
  24238. }
  24239. // Render targets
  24240. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24241. var needsRestoreFrameBuffer = false;
  24242. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24243. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24244. }
  24245. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24246. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24247. }
  24248. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24249. this._intermediateRendering = true;
  24250. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24251. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24252. var renderTarget = this._renderTargets.data[renderIndex];
  24253. if (renderTarget._shouldRender()) {
  24254. this._renderId++;
  24255. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24256. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24257. }
  24258. }
  24259. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24260. this._intermediateRendering = false;
  24261. this._renderId++;
  24262. needsRestoreFrameBuffer = true; // Restore back buffer
  24263. }
  24264. // Render EffecttLayer Texture
  24265. var stencilState = this._engine.getStencilBuffer();
  24266. var renderEffects = false;
  24267. var needStencil = false;
  24268. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24269. this._intermediateRendering = true;
  24270. for (var i = 0; i < this.effectLayers.length; i++) {
  24271. var effectLayer = this.effectLayers[i];
  24272. if (effectLayer.shouldRender() &&
  24273. (!effectLayer.camera ||
  24274. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24275. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24276. renderEffects = true;
  24277. needStencil = needStencil || effectLayer.needStencil();
  24278. var renderTarget = effectLayer._mainTexture;
  24279. if (renderTarget._shouldRender()) {
  24280. this._renderId++;
  24281. renderTarget.render(false, false);
  24282. needsRestoreFrameBuffer = true;
  24283. }
  24284. }
  24285. }
  24286. this._intermediateRendering = false;
  24287. this._renderId++;
  24288. }
  24289. if (needsRestoreFrameBuffer) {
  24290. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24291. }
  24292. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24293. // Prepare Frame
  24294. this.postProcessManager._prepareFrame();
  24295. // Backgrounds
  24296. var layerIndex;
  24297. var layer;
  24298. if (this.layers.length) {
  24299. engine.setDepthBuffer(false);
  24300. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24301. layer = this.layers[layerIndex];
  24302. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24303. layer.render();
  24304. }
  24305. }
  24306. engine.setDepthBuffer(true);
  24307. }
  24308. // Activate effect Layer stencil
  24309. if (needStencil) {
  24310. this._engine.setStencilBuffer(true);
  24311. }
  24312. // Render
  24313. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24314. this._renderingManager.render(null, null, true, true);
  24315. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24316. // Restore effect Layer stencil
  24317. if (needStencil) {
  24318. this._engine.setStencilBuffer(stencilState);
  24319. }
  24320. // Bounding boxes
  24321. if (this._boundingBoxRenderer) {
  24322. this._boundingBoxRenderer.render();
  24323. }
  24324. // Lens flares
  24325. if (this.lensFlaresEnabled) {
  24326. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24327. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24328. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24329. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24330. lensFlareSystem.render();
  24331. }
  24332. }
  24333. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24334. }
  24335. // Foregrounds
  24336. if (this.layers.length) {
  24337. engine.setDepthBuffer(false);
  24338. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24339. layer = this.layers[layerIndex];
  24340. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24341. layer.render();
  24342. }
  24343. }
  24344. engine.setDepthBuffer(true);
  24345. }
  24346. // Effect Layer
  24347. if (renderEffects) {
  24348. engine.setDepthBuffer(false);
  24349. for (var i = 0; i < this.effectLayers.length; i++) {
  24350. if (this.effectLayers[i].shouldRender()) {
  24351. this.effectLayers[i].render();
  24352. }
  24353. }
  24354. engine.setDepthBuffer(true);
  24355. }
  24356. // Finalize frame
  24357. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24358. // Reset some special arrays
  24359. this._renderTargets.reset();
  24360. this._alternateRendering = false;
  24361. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24362. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24363. };
  24364. Scene.prototype._processSubCameras = function (camera) {
  24365. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24366. this._renderForCamera(camera);
  24367. return;
  24368. }
  24369. // rig cameras
  24370. for (var index = 0; index < camera._rigCameras.length; index++) {
  24371. this._renderForCamera(camera._rigCameras[index], camera);
  24372. }
  24373. this.activeCamera = camera;
  24374. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24375. };
  24376. Scene.prototype._checkIntersections = function () {
  24377. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24378. var sourceMesh = this._meshesForIntersections.data[index];
  24379. if (!sourceMesh.actionManager) {
  24380. continue;
  24381. }
  24382. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24383. var action = sourceMesh.actionManager.actions[actionIndex];
  24384. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24385. var parameters = action.getTriggerParameter();
  24386. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24387. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24388. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24389. if (areIntersecting && currentIntersectionInProgress === -1) {
  24390. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24391. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24392. sourceMesh._intersectionsInProgress.push(otherMesh);
  24393. }
  24394. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24395. sourceMesh._intersectionsInProgress.push(otherMesh);
  24396. }
  24397. }
  24398. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24399. //They intersected, and now they don't.
  24400. //is this trigger an exit trigger? execute an event.
  24401. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24402. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24403. }
  24404. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24405. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24406. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24407. }
  24408. }
  24409. }
  24410. }
  24411. }
  24412. };
  24413. Scene.prototype.render = function () {
  24414. if (this.isDisposed) {
  24415. return;
  24416. }
  24417. this._activeParticles.fetchNewFrame();
  24418. this._totalVertices.fetchNewFrame();
  24419. this._activeIndices.fetchNewFrame();
  24420. this._activeBones.fetchNewFrame();
  24421. this._meshesForIntersections.reset();
  24422. this.resetCachedMaterial();
  24423. this.onBeforeAnimationsObservable.notifyObservers(this);
  24424. // Actions
  24425. if (this.actionManager) {
  24426. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24427. }
  24428. //Simplification Queue
  24429. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24430. this.simplificationQueue.executeNext();
  24431. }
  24432. if (this._engine.isDeterministicLockStep()) {
  24433. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24434. var defaultFPS = (60.0 / 1000.0);
  24435. var defaultFrameTime = 1000 / 60; // frame time in MS
  24436. if (this._physicsEngine) {
  24437. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24438. }
  24439. var stepsTaken = 0;
  24440. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24441. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24442. internalSteps = Math.min(internalSteps, maxSubSteps);
  24443. do {
  24444. this.onBeforeStepObservable.notifyObservers(this);
  24445. // Animations
  24446. this._animationRatio = defaultFrameTime * defaultFPS;
  24447. this._animate();
  24448. this.onAfterAnimationsObservable.notifyObservers(this);
  24449. // Physics
  24450. if (this._physicsEngine) {
  24451. this.onBeforePhysicsObservable.notifyObservers(this);
  24452. this._physicsEngine._step(defaultFrameTime / 1000);
  24453. this.onAfterPhysicsObservable.notifyObservers(this);
  24454. }
  24455. this.onAfterStepObservable.notifyObservers(this);
  24456. this._currentStepId++;
  24457. stepsTaken++;
  24458. deltaTime -= defaultFrameTime;
  24459. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24460. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24461. }
  24462. else {
  24463. // Animations
  24464. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24465. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24466. this._animate();
  24467. this.onAfterAnimationsObservable.notifyObservers(this);
  24468. // Physics
  24469. if (this._physicsEngine) {
  24470. this.onBeforePhysicsObservable.notifyObservers(this);
  24471. this._physicsEngine._step(deltaTime / 1000.0);
  24472. this.onAfterPhysicsObservable.notifyObservers(this);
  24473. }
  24474. }
  24475. // update gamepad manager
  24476. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24477. this._gamepadManager._checkGamepadsStatus();
  24478. }
  24479. // Update Cameras
  24480. if (this.activeCameras.length > 0) {
  24481. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24482. var camera = this.activeCameras[cameraIndex];
  24483. camera.update();
  24484. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24485. // rig cameras
  24486. for (var index = 0; index < camera._rigCameras.length; index++) {
  24487. camera._rigCameras[index].update();
  24488. }
  24489. }
  24490. }
  24491. }
  24492. else if (this.activeCamera) {
  24493. this.activeCamera.update();
  24494. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24495. // rig cameras
  24496. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24497. this.activeCamera._rigCameras[index].update();
  24498. }
  24499. }
  24500. }
  24501. // Before render
  24502. this.onBeforeRenderObservable.notifyObservers(this);
  24503. // Customs render targets
  24504. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24505. var engine = this.getEngine();
  24506. var currentActiveCamera = this.activeCamera;
  24507. if (this.renderTargetsEnabled) {
  24508. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24509. this._intermediateRendering = true;
  24510. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24511. var renderTarget = this.customRenderTargets[customIndex];
  24512. if (renderTarget._shouldRender()) {
  24513. this._renderId++;
  24514. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24515. if (!this.activeCamera)
  24516. throw new Error("Active camera not set");
  24517. // Viewport
  24518. engine.setViewport(this.activeCamera.viewport);
  24519. // Camera
  24520. this.updateTransformMatrix();
  24521. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24522. }
  24523. }
  24524. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24525. this._intermediateRendering = false;
  24526. this._renderId++;
  24527. }
  24528. // Restore back buffer
  24529. if (this.customRenderTargets.length > 0) {
  24530. engine.restoreDefaultFramebuffer();
  24531. }
  24532. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24533. this.activeCamera = currentActiveCamera;
  24534. // Procedural textures
  24535. if (this.proceduralTexturesEnabled) {
  24536. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24537. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24538. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24539. if (proceduralTexture._shouldRender()) {
  24540. proceduralTexture.render();
  24541. }
  24542. }
  24543. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24544. }
  24545. // Clear
  24546. if (this.autoClearDepthAndStencil || this.autoClear) {
  24547. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24548. }
  24549. // Shadows
  24550. if (this.shadowsEnabled) {
  24551. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24552. var light = this.lights[lightIndex];
  24553. var shadowGenerator = light.getShadowGenerator();
  24554. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24555. var shadowMap = (shadowGenerator.getShadowMap());
  24556. if (this.textures.indexOf(shadowMap) !== -1) {
  24557. this._renderTargets.push(shadowMap);
  24558. }
  24559. }
  24560. }
  24561. }
  24562. // Depth renderer
  24563. for (var key in this._depthRenderer) {
  24564. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24565. }
  24566. // Geometry renderer
  24567. if (this._geometryBufferRenderer) {
  24568. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24569. }
  24570. // RenderPipeline
  24571. if (this._postProcessRenderPipelineManager) {
  24572. this._postProcessRenderPipelineManager.update();
  24573. }
  24574. // Multi-cameras?
  24575. if (this.activeCameras.length > 0) {
  24576. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24577. if (cameraIndex > 0) {
  24578. this._engine.clear(null, false, true, true);
  24579. }
  24580. this._processSubCameras(this.activeCameras[cameraIndex]);
  24581. }
  24582. }
  24583. else {
  24584. if (!this.activeCamera) {
  24585. throw new Error("No camera defined");
  24586. }
  24587. this._processSubCameras(this.activeCamera);
  24588. }
  24589. // Intersection checks
  24590. this._checkIntersections();
  24591. // Update the audio listener attached to the camera
  24592. if (BABYLON.AudioEngine) {
  24593. this._updateAudioParameters();
  24594. }
  24595. // After render
  24596. if (this.afterRender) {
  24597. this.afterRender();
  24598. }
  24599. this.onAfterRenderObservable.notifyObservers(this);
  24600. // Cleaning
  24601. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24602. var data = this._toBeDisposed.data[index];
  24603. if (data) {
  24604. data.dispose();
  24605. }
  24606. this._toBeDisposed[index] = null;
  24607. }
  24608. this._toBeDisposed.reset();
  24609. if (this.dumpNextRenderTargets) {
  24610. this.dumpNextRenderTargets = false;
  24611. }
  24612. this._activeBones.addCount(0, true);
  24613. this._activeIndices.addCount(0, true);
  24614. this._activeParticles.addCount(0, true);
  24615. };
  24616. Scene.prototype._updateAudioParameters = function () {
  24617. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24618. return;
  24619. }
  24620. var listeningCamera;
  24621. var audioEngine = BABYLON.Engine.audioEngine;
  24622. if (this.activeCameras.length > 0) {
  24623. listeningCamera = this.activeCameras[0];
  24624. }
  24625. else {
  24626. listeningCamera = this.activeCamera;
  24627. }
  24628. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24629. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24630. // for VR cameras
  24631. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24632. listeningCamera = listeningCamera.rigCameras[0];
  24633. }
  24634. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24635. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24636. cameraDirection.normalize();
  24637. // To avoid some errors on GearVR
  24638. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24639. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24640. }
  24641. var i;
  24642. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24643. var sound = this.mainSoundTrack.soundCollection[i];
  24644. if (sound.useCustomAttenuation) {
  24645. sound.updateDistanceFromListener();
  24646. }
  24647. }
  24648. for (i = 0; i < this.soundTracks.length; i++) {
  24649. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24650. sound = this.soundTracks[i].soundCollection[j];
  24651. if (sound.useCustomAttenuation) {
  24652. sound.updateDistanceFromListener();
  24653. }
  24654. }
  24655. }
  24656. }
  24657. };
  24658. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24659. // Audio
  24660. get: function () {
  24661. return this._audioEnabled;
  24662. },
  24663. set: function (value) {
  24664. this._audioEnabled = value;
  24665. if (BABYLON.AudioEngine) {
  24666. if (this._audioEnabled) {
  24667. this._enableAudio();
  24668. }
  24669. else {
  24670. this._disableAudio();
  24671. }
  24672. }
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Scene.prototype._disableAudio = function () {
  24678. var i;
  24679. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24680. this.mainSoundTrack.soundCollection[i].pause();
  24681. }
  24682. for (i = 0; i < this.soundTracks.length; i++) {
  24683. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24684. this.soundTracks[i].soundCollection[j].pause();
  24685. }
  24686. }
  24687. };
  24688. Scene.prototype._enableAudio = function () {
  24689. var i;
  24690. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24691. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24692. this.mainSoundTrack.soundCollection[i].play();
  24693. }
  24694. }
  24695. for (i = 0; i < this.soundTracks.length; i++) {
  24696. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24697. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24698. this.soundTracks[i].soundCollection[j].play();
  24699. }
  24700. }
  24701. }
  24702. };
  24703. Object.defineProperty(Scene.prototype, "headphone", {
  24704. get: function () {
  24705. return this._headphone;
  24706. },
  24707. set: function (value) {
  24708. this._headphone = value;
  24709. if (BABYLON.AudioEngine) {
  24710. if (this._headphone) {
  24711. this._switchAudioModeForHeadphones();
  24712. }
  24713. else {
  24714. this._switchAudioModeForNormalSpeakers();
  24715. }
  24716. }
  24717. },
  24718. enumerable: true,
  24719. configurable: true
  24720. });
  24721. Scene.prototype._switchAudioModeForHeadphones = function () {
  24722. this.mainSoundTrack.switchPanningModelToHRTF();
  24723. for (var i = 0; i < this.soundTracks.length; i++) {
  24724. this.soundTracks[i].switchPanningModelToHRTF();
  24725. }
  24726. };
  24727. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24728. this.mainSoundTrack.switchPanningModelToEqualPower();
  24729. for (var i = 0; i < this.soundTracks.length; i++) {
  24730. this.soundTracks[i].switchPanningModelToEqualPower();
  24731. }
  24732. };
  24733. /**
  24734. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24735. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24736. * @returns the created depth renderer
  24737. */
  24738. Scene.prototype.enableDepthRenderer = function (camera) {
  24739. camera = camera || this.activeCamera;
  24740. if (!camera) {
  24741. throw "No camera available to enable depth renderer";
  24742. }
  24743. if (!this._depthRenderer[camera.id]) {
  24744. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24745. }
  24746. return this._depthRenderer[camera.id];
  24747. };
  24748. /**
  24749. * Disables a depth renderer for a given camera
  24750. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24751. */
  24752. Scene.prototype.disableDepthRenderer = function (camera) {
  24753. camera = camera || this.activeCamera;
  24754. if (!camera || !this._depthRenderer[camera.id]) {
  24755. return;
  24756. }
  24757. this._depthRenderer[camera.id].dispose();
  24758. delete this._depthRenderer[camera.id];
  24759. };
  24760. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24761. if (ratio === void 0) { ratio = 1; }
  24762. if (this._geometryBufferRenderer) {
  24763. return this._geometryBufferRenderer;
  24764. }
  24765. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24766. if (!this._geometryBufferRenderer.isSupported) {
  24767. this._geometryBufferRenderer = null;
  24768. }
  24769. return this._geometryBufferRenderer;
  24770. };
  24771. Scene.prototype.disableGeometryBufferRenderer = function () {
  24772. if (!this._geometryBufferRenderer) {
  24773. return;
  24774. }
  24775. this._geometryBufferRenderer.dispose();
  24776. this._geometryBufferRenderer = null;
  24777. };
  24778. Scene.prototype.freezeMaterials = function () {
  24779. for (var i = 0; i < this.materials.length; i++) {
  24780. this.materials[i].freeze();
  24781. }
  24782. };
  24783. Scene.prototype.unfreezeMaterials = function () {
  24784. for (var i = 0; i < this.materials.length; i++) {
  24785. this.materials[i].unfreeze();
  24786. }
  24787. };
  24788. Scene.prototype.dispose = function () {
  24789. this.beforeRender = null;
  24790. this.afterRender = null;
  24791. this.skeletons = [];
  24792. this.morphTargetManagers = [];
  24793. this.importedMeshesFiles = new Array();
  24794. this.stopAllAnimations();
  24795. this.resetCachedMaterial();
  24796. for (var key in this._depthRenderer) {
  24797. this._depthRenderer[key].dispose();
  24798. }
  24799. if (this._gamepadManager) {
  24800. this._gamepadManager.dispose();
  24801. this._gamepadManager = null;
  24802. }
  24803. // Smart arrays
  24804. if (this.activeCamera) {
  24805. this.activeCamera._activeMeshes.dispose();
  24806. this.activeCamera = null;
  24807. }
  24808. this._activeMeshes.dispose();
  24809. this._renderingManager.dispose();
  24810. this._processedMaterials.dispose();
  24811. this._activeParticleSystems.dispose();
  24812. this._activeSkeletons.dispose();
  24813. this._softwareSkinnedMeshes.dispose();
  24814. this._renderTargets.dispose();
  24815. if (this._boundingBoxRenderer) {
  24816. this._boundingBoxRenderer.dispose();
  24817. }
  24818. this._meshesForIntersections.dispose();
  24819. this._toBeDisposed.dispose();
  24820. // Abort active requests
  24821. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24822. var request = _a[_i];
  24823. request.abort();
  24824. }
  24825. // Debug layer
  24826. if (this._debugLayer) {
  24827. this._debugLayer.hide();
  24828. }
  24829. // Events
  24830. this.onDisposeObservable.notifyObservers(this);
  24831. this.onDisposeObservable.clear();
  24832. this.onBeforeRenderObservable.clear();
  24833. this.onAfterRenderObservable.clear();
  24834. this.OnBeforeRenderTargetsRenderObservable.clear();
  24835. this.OnAfterRenderTargetsRenderObservable.clear();
  24836. this.onAfterStepObservable.clear();
  24837. this.onBeforeStepObservable.clear();
  24838. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24839. this.onAfterActiveMeshesEvaluationObservable.clear();
  24840. this.onBeforeParticlesRenderingObservable.clear();
  24841. this.onAfterParticlesRenderingObservable.clear();
  24842. this.onBeforeSpritesRenderingObservable.clear();
  24843. this.onAfterSpritesRenderingObservable.clear();
  24844. this.onBeforeDrawPhaseObservable.clear();
  24845. this.onAfterDrawPhaseObservable.clear();
  24846. this.onBeforePhysicsObservable.clear();
  24847. this.onAfterPhysicsObservable.clear();
  24848. this.onBeforeAnimationsObservable.clear();
  24849. this.onAfterAnimationsObservable.clear();
  24850. this.onDataLoadedObservable.clear();
  24851. this.detachControl();
  24852. // Release sounds & sounds tracks
  24853. if (BABYLON.AudioEngine) {
  24854. this.disposeSounds();
  24855. }
  24856. // VR Helper
  24857. if (this.VRHelper) {
  24858. this.VRHelper.dispose();
  24859. }
  24860. // Detach cameras
  24861. var canvas = this._engine.getRenderingCanvas();
  24862. if (canvas) {
  24863. var index;
  24864. for (index = 0; index < this.cameras.length; index++) {
  24865. this.cameras[index].detachControl(canvas);
  24866. }
  24867. }
  24868. // Release animation groups
  24869. while (this.animationGroups.length) {
  24870. this.animationGroups[0].dispose();
  24871. }
  24872. // Release lights
  24873. while (this.lights.length) {
  24874. this.lights[0].dispose();
  24875. }
  24876. // Release meshes
  24877. while (this.meshes.length) {
  24878. this.meshes[0].dispose(true);
  24879. }
  24880. while (this.transformNodes.length) {
  24881. this.removeTransformNode(this.transformNodes[0]);
  24882. }
  24883. // Release cameras
  24884. while (this.cameras.length) {
  24885. this.cameras[0].dispose();
  24886. }
  24887. // Release materials
  24888. if (this.defaultMaterial) {
  24889. this.defaultMaterial.dispose();
  24890. }
  24891. while (this.multiMaterials.length) {
  24892. this.multiMaterials[0].dispose();
  24893. }
  24894. while (this.materials.length) {
  24895. this.materials[0].dispose();
  24896. }
  24897. // Release particles
  24898. while (this.particleSystems.length) {
  24899. this.particleSystems[0].dispose();
  24900. }
  24901. // Release sprites
  24902. while (this.spriteManagers.length) {
  24903. this.spriteManagers[0].dispose();
  24904. }
  24905. // Release postProcesses
  24906. while (this.postProcesses.length) {
  24907. this.postProcesses[0].dispose();
  24908. }
  24909. // Release layers
  24910. while (this.layers.length) {
  24911. this.layers[0].dispose();
  24912. }
  24913. while (this.effectLayers.length) {
  24914. this.effectLayers[0].dispose();
  24915. }
  24916. // Release textures
  24917. while (this.textures.length) {
  24918. this.textures[0].dispose();
  24919. }
  24920. // Release UBO
  24921. this._sceneUbo.dispose();
  24922. if (this._alternateSceneUbo) {
  24923. this._alternateSceneUbo.dispose();
  24924. }
  24925. // Post-processes
  24926. this.postProcessManager.dispose();
  24927. if (this._postProcessRenderPipelineManager) {
  24928. this._postProcessRenderPipelineManager.dispose();
  24929. }
  24930. // Physics
  24931. if (this._physicsEngine) {
  24932. this.disablePhysicsEngine();
  24933. }
  24934. // Remove from engine
  24935. index = this._engine.scenes.indexOf(this);
  24936. if (index > -1) {
  24937. this._engine.scenes.splice(index, 1);
  24938. }
  24939. this._engine.wipeCaches(true);
  24940. this._isDisposed = true;
  24941. };
  24942. Object.defineProperty(Scene.prototype, "isDisposed", {
  24943. get: function () {
  24944. return this._isDisposed;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. // Release sounds & sounds tracks
  24950. Scene.prototype.disposeSounds = function () {
  24951. if (!this._mainSoundTrack) {
  24952. return;
  24953. }
  24954. this.mainSoundTrack.dispose();
  24955. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24956. this.soundTracks[scIndex].dispose();
  24957. }
  24958. };
  24959. // Octrees
  24960. /**
  24961. * Get the world extend vectors with an optional filter
  24962. *
  24963. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24964. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24965. */
  24966. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24967. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24968. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24969. filterPredicate = filterPredicate || (function () { return true; });
  24970. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24971. mesh.computeWorldMatrix(true);
  24972. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24973. return;
  24974. }
  24975. var boundingInfo = mesh.getBoundingInfo();
  24976. var minBox = boundingInfo.boundingBox.minimumWorld;
  24977. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24978. BABYLON.Tools.CheckExtends(minBox, min, max);
  24979. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24980. });
  24981. return {
  24982. min: min,
  24983. max: max
  24984. };
  24985. };
  24986. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24987. if (maxCapacity === void 0) { maxCapacity = 64; }
  24988. if (maxDepth === void 0) { maxDepth = 2; }
  24989. if (!this._selectionOctree) {
  24990. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24991. }
  24992. var worldExtends = this.getWorldExtends();
  24993. // Update octree
  24994. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24995. return this._selectionOctree;
  24996. };
  24997. // Picking
  24998. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24999. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25000. var result = BABYLON.Ray.Zero();
  25001. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25002. return result;
  25003. };
  25004. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25005. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25006. var engine = this._engine;
  25007. if (!camera) {
  25008. if (!this.activeCamera)
  25009. throw new Error("Active camera not set");
  25010. camera = this.activeCamera;
  25011. }
  25012. var cameraViewport = camera.viewport;
  25013. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25014. // Moving coordinates to local viewport world
  25015. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25016. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25017. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25018. return this;
  25019. };
  25020. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25021. var result = BABYLON.Ray.Zero();
  25022. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25023. return result;
  25024. };
  25025. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25026. if (!BABYLON.PickingInfo) {
  25027. return this;
  25028. }
  25029. var engine = this._engine;
  25030. if (!camera) {
  25031. if (!this.activeCamera)
  25032. throw new Error("Active camera not set");
  25033. camera = this.activeCamera;
  25034. }
  25035. var cameraViewport = camera.viewport;
  25036. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25037. var identity = BABYLON.Matrix.Identity();
  25038. // Moving coordinates to local viewport world
  25039. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25040. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25041. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25042. return this;
  25043. };
  25044. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25045. if (!BABYLON.PickingInfo) {
  25046. return null;
  25047. }
  25048. var pickingInfo = null;
  25049. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25050. var mesh = this.meshes[meshIndex];
  25051. if (predicate) {
  25052. if (!predicate(mesh)) {
  25053. continue;
  25054. }
  25055. }
  25056. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25057. continue;
  25058. }
  25059. var world = mesh.getWorldMatrix();
  25060. var ray = rayFunction(world);
  25061. var result = mesh.intersects(ray, fastCheck);
  25062. if (!result || !result.hit)
  25063. continue;
  25064. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25065. continue;
  25066. pickingInfo = result;
  25067. if (fastCheck) {
  25068. break;
  25069. }
  25070. }
  25071. return pickingInfo || new BABYLON.PickingInfo();
  25072. };
  25073. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25074. if (!BABYLON.PickingInfo) {
  25075. return null;
  25076. }
  25077. var pickingInfos = new Array();
  25078. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25079. var mesh = this.meshes[meshIndex];
  25080. if (predicate) {
  25081. if (!predicate(mesh)) {
  25082. continue;
  25083. }
  25084. }
  25085. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25086. continue;
  25087. }
  25088. var world = mesh.getWorldMatrix();
  25089. var ray = rayFunction(world);
  25090. var result = mesh.intersects(ray, false);
  25091. if (!result || !result.hit)
  25092. continue;
  25093. pickingInfos.push(result);
  25094. }
  25095. return pickingInfos;
  25096. };
  25097. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25098. if (!BABYLON.PickingInfo) {
  25099. return null;
  25100. }
  25101. var pickingInfo = null;
  25102. if (!camera) {
  25103. if (!this.activeCamera) {
  25104. return null;
  25105. }
  25106. camera = this.activeCamera;
  25107. }
  25108. if (this.spriteManagers.length > 0) {
  25109. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25110. var spriteManager = this.spriteManagers[spriteIndex];
  25111. if (!spriteManager.isPickable) {
  25112. continue;
  25113. }
  25114. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25115. if (!result || !result.hit)
  25116. continue;
  25117. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25118. continue;
  25119. pickingInfo = result;
  25120. if (fastCheck) {
  25121. break;
  25122. }
  25123. }
  25124. }
  25125. return pickingInfo || new BABYLON.PickingInfo();
  25126. };
  25127. /** Launch a ray to try to pick a mesh in the scene
  25128. * @param x position on screen
  25129. * @param y position on screen
  25130. * @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
  25131. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25132. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25133. */
  25134. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25135. var _this = this;
  25136. if (!BABYLON.PickingInfo) {
  25137. return null;
  25138. }
  25139. return this._internalPick(function (world) {
  25140. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25141. return _this._tempPickingRay;
  25142. }, predicate, fastCheck);
  25143. };
  25144. /** Launch a ray to try to pick a sprite in the scene
  25145. * @param x position on screen
  25146. * @param y position on screen
  25147. * @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
  25148. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25149. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25150. */
  25151. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25152. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25153. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25154. };
  25155. /** Use the given ray to pick a mesh in the scene
  25156. * @param ray The ray to use to pick meshes
  25157. * @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
  25158. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25159. */
  25160. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25161. var _this = this;
  25162. return this._internalPick(function (world) {
  25163. if (!_this._pickWithRayInverseMatrix) {
  25164. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25165. }
  25166. world.invertToRef(_this._pickWithRayInverseMatrix);
  25167. if (!_this._cachedRayForTransform) {
  25168. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25169. }
  25170. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25171. return _this._cachedRayForTransform;
  25172. }, predicate, fastCheck);
  25173. };
  25174. /**
  25175. * Launch a ray to try to pick a mesh in the scene
  25176. * @param x X position on screen
  25177. * @param y Y position on screen
  25178. * @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
  25179. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25180. */
  25181. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25182. var _this = this;
  25183. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25184. };
  25185. /**
  25186. * Launch a ray to try to pick a mesh in the scene
  25187. * @param ray Ray to use
  25188. * @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
  25189. */
  25190. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25191. var _this = this;
  25192. return this._internalMultiPick(function (world) {
  25193. if (!_this._pickWithRayInverseMatrix) {
  25194. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25195. }
  25196. world.invertToRef(_this._pickWithRayInverseMatrix);
  25197. if (!_this._cachedRayForTransform) {
  25198. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25199. }
  25200. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25201. return _this._cachedRayForTransform;
  25202. }, predicate);
  25203. };
  25204. Scene.prototype.setPointerOverMesh = function (mesh) {
  25205. if (this._pointerOverMesh === mesh) {
  25206. return;
  25207. }
  25208. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25209. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25210. }
  25211. this._pointerOverMesh = mesh;
  25212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25213. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25214. }
  25215. };
  25216. Scene.prototype.getPointerOverMesh = function () {
  25217. return this._pointerOverMesh;
  25218. };
  25219. Scene.prototype.setPointerOverSprite = function (sprite) {
  25220. if (this._pointerOverSprite === sprite) {
  25221. return;
  25222. }
  25223. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25224. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25225. }
  25226. this._pointerOverSprite = sprite;
  25227. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25228. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25229. }
  25230. };
  25231. Scene.prototype.getPointerOverSprite = function () {
  25232. return this._pointerOverSprite;
  25233. };
  25234. // Physics
  25235. Scene.prototype.getPhysicsEngine = function () {
  25236. return this._physicsEngine;
  25237. };
  25238. /**
  25239. * Enables physics to the current scene
  25240. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25241. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25242. * @return {boolean} was the physics engine initialized
  25243. */
  25244. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25245. if (gravity === void 0) { gravity = null; }
  25246. if (this._physicsEngine) {
  25247. return true;
  25248. }
  25249. try {
  25250. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25251. return true;
  25252. }
  25253. catch (e) {
  25254. BABYLON.Tools.Error(e.message);
  25255. return false;
  25256. }
  25257. };
  25258. Scene.prototype.disablePhysicsEngine = function () {
  25259. if (!this._physicsEngine) {
  25260. return;
  25261. }
  25262. this._physicsEngine.dispose();
  25263. this._physicsEngine = null;
  25264. };
  25265. Scene.prototype.isPhysicsEnabled = function () {
  25266. return this._physicsEngine !== undefined;
  25267. };
  25268. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25269. var mesh = compound.parts[0].mesh;
  25270. if (mesh.physicsImpostor) {
  25271. mesh.physicsImpostor.dispose();
  25272. mesh.physicsImpostor = null;
  25273. }
  25274. };
  25275. // Misc.
  25276. Scene.prototype._rebuildGeometries = function () {
  25277. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25278. var geometry = _a[_i];
  25279. geometry._rebuild();
  25280. }
  25281. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25282. var mesh = _c[_b];
  25283. mesh._rebuild();
  25284. }
  25285. if (this.postProcessManager) {
  25286. this.postProcessManager._rebuild();
  25287. }
  25288. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25289. var layer = _e[_d];
  25290. layer._rebuild();
  25291. }
  25292. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25293. var effectLayer = _g[_f];
  25294. effectLayer._rebuild();
  25295. }
  25296. if (this._boundingBoxRenderer) {
  25297. this._boundingBoxRenderer._rebuild();
  25298. }
  25299. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25300. var system = _j[_h];
  25301. system.rebuild();
  25302. }
  25303. if (this._postProcessRenderPipelineManager) {
  25304. this._postProcessRenderPipelineManager._rebuild();
  25305. }
  25306. };
  25307. Scene.prototype._rebuildTextures = function () {
  25308. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25309. var texture = _a[_i];
  25310. texture._rebuild();
  25311. }
  25312. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25313. };
  25314. /**
  25315. * Creates a default light for the scene.
  25316. * @param replace Whether to replace the existing lights in the scene.
  25317. */
  25318. Scene.prototype.createDefaultLight = function (replace) {
  25319. if (replace === void 0) { replace = false; }
  25320. // Dispose existing light in replace mode.
  25321. if (replace) {
  25322. if (this.lights) {
  25323. for (var i = 0; i < this.lights.length; i++) {
  25324. this.lights[i].dispose();
  25325. }
  25326. }
  25327. }
  25328. // Light
  25329. if (this.lights.length === 0) {
  25330. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25331. }
  25332. };
  25333. /**
  25334. * Creates a default camera for the scene.
  25335. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25336. * @param replace Whether to replace the existing active camera in the scene.
  25337. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25338. */
  25339. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25340. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25341. if (replace === void 0) { replace = false; }
  25342. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25343. // Dispose existing camera in replace mode.
  25344. if (replace) {
  25345. if (this.activeCamera) {
  25346. this.activeCamera.dispose();
  25347. this.activeCamera = null;
  25348. }
  25349. }
  25350. // Camera
  25351. if (!this.activeCamera) {
  25352. var worldExtends = this.getWorldExtends();
  25353. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25354. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25355. var camera;
  25356. var radius = worldSize.length() * 1.5;
  25357. // empty scene scenario!
  25358. if (!isFinite(radius)) {
  25359. radius = 1;
  25360. worldCenter.copyFromFloats(0, 0, 0);
  25361. }
  25362. if (createArcRotateCamera) {
  25363. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25364. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25365. arcRotateCamera.wheelPrecision = 100 / radius;
  25366. camera = arcRotateCamera;
  25367. }
  25368. else {
  25369. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25370. freeCamera.setTarget(worldCenter);
  25371. camera = freeCamera;
  25372. }
  25373. camera.minZ = radius * 0.01;
  25374. camera.maxZ = radius * 1000;
  25375. camera.speed = radius * 0.2;
  25376. this.activeCamera = camera;
  25377. var canvas = this.getEngine().getRenderingCanvas();
  25378. if (attachCameraControls && canvas) {
  25379. camera.attachControl(canvas);
  25380. }
  25381. }
  25382. };
  25383. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25384. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25385. if (replace === void 0) { replace = false; }
  25386. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25387. this.createDefaultLight(replace);
  25388. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25389. };
  25390. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25391. if (pbr === void 0) { pbr = false; }
  25392. if (scale === void 0) { scale = 1000; }
  25393. if (blur === void 0) { blur = 0; }
  25394. if (environmentTexture) {
  25395. this.environmentTexture = environmentTexture;
  25396. }
  25397. if (!this.environmentTexture) {
  25398. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25399. return null;
  25400. }
  25401. // Skybox
  25402. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25403. if (pbr) {
  25404. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25405. hdrSkyboxMaterial.backFaceCulling = false;
  25406. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25407. if (hdrSkyboxMaterial.reflectionTexture) {
  25408. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25409. }
  25410. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25411. hdrSkyboxMaterial.disableLighting = true;
  25412. hdrSkyboxMaterial.twoSidedLighting = true;
  25413. hdrSkybox.infiniteDistance = true;
  25414. hdrSkybox.material = hdrSkyboxMaterial;
  25415. }
  25416. else {
  25417. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25418. skyboxMaterial.backFaceCulling = false;
  25419. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25420. if (skyboxMaterial.reflectionTexture) {
  25421. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25422. }
  25423. skyboxMaterial.disableLighting = true;
  25424. hdrSkybox.infiniteDistance = true;
  25425. hdrSkybox.material = skyboxMaterial;
  25426. }
  25427. return hdrSkybox;
  25428. };
  25429. Scene.prototype.createDefaultEnvironment = function (options) {
  25430. if (BABYLON.EnvironmentHelper) {
  25431. return new BABYLON.EnvironmentHelper(options, this);
  25432. }
  25433. return null;
  25434. };
  25435. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25436. if (webVROptions === void 0) { webVROptions = {}; }
  25437. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25438. };
  25439. // Tags
  25440. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25441. if (tagsQuery === undefined) {
  25442. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25443. return list;
  25444. }
  25445. var listByTags = [];
  25446. forEach = forEach || (function (item) { return; });
  25447. for (var i in list) {
  25448. var item = list[i];
  25449. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25450. listByTags.push(item);
  25451. forEach(item);
  25452. }
  25453. }
  25454. return listByTags;
  25455. };
  25456. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25457. return this._getByTags(this.meshes, tagsQuery, forEach);
  25458. };
  25459. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25460. return this._getByTags(this.cameras, tagsQuery, forEach);
  25461. };
  25462. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25463. return this._getByTags(this.lights, tagsQuery, forEach);
  25464. };
  25465. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25466. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25467. };
  25468. /**
  25469. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25470. * This allowed control for front to back rendering or reversly depending of the special needs.
  25471. *
  25472. * @param renderingGroupId The rendering group id corresponding to its index
  25473. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25474. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25475. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25476. */
  25477. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25478. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25479. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25480. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25481. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25482. };
  25483. /**
  25484. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25485. *
  25486. * @param renderingGroupId The rendering group id corresponding to its index
  25487. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25488. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25489. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25490. */
  25491. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25492. if (depth === void 0) { depth = true; }
  25493. if (stencil === void 0) { stencil = true; }
  25494. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25495. };
  25496. /**
  25497. * Will flag all materials as dirty to trigger new shader compilation
  25498. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25499. */
  25500. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25501. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25502. var material = _a[_i];
  25503. if (predicate && !predicate(material)) {
  25504. continue;
  25505. }
  25506. material.markAsDirty(flag);
  25507. }
  25508. };
  25509. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25510. var _this = this;
  25511. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25512. this._activeRequests.push(request);
  25513. request.onCompleteObservable.add(function (request) {
  25514. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25515. });
  25516. return request;
  25517. };
  25518. /** @ignore */
  25519. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25520. var _this = this;
  25521. return new Promise(function (resolve, reject) {
  25522. _this._loadFile(url, function (data) {
  25523. resolve(data);
  25524. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25525. reject(exception);
  25526. });
  25527. });
  25528. };
  25529. // Statics
  25530. Scene._FOGMODE_NONE = 0;
  25531. Scene._FOGMODE_EXP = 1;
  25532. Scene._FOGMODE_EXP2 = 2;
  25533. Scene._FOGMODE_LINEAR = 3;
  25534. Scene._uniqueIdCounter = 0;
  25535. Scene.MinDeltaTime = 1.0;
  25536. Scene.MaxDeltaTime = 1000.0;
  25537. /** The distance in pixel that you have to move to prevent some events */
  25538. Scene.DragMovementThreshold = 10; // in pixels
  25539. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25540. Scene.LongPressDelay = 500; // in milliseconds
  25541. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25542. Scene.DoubleClickDelay = 300; // in milliseconds
  25543. /** If you need to check double click without raising a single click at first click, enable this flag */
  25544. Scene.ExclusiveDoubleClickMode = false;
  25545. return Scene;
  25546. }());
  25547. BABYLON.Scene = Scene;
  25548. })(BABYLON || (BABYLON = {}));
  25549. //# sourceMappingURL=babylon.scene.js.map
  25550. var BABYLON;
  25551. (function (BABYLON) {
  25552. /**
  25553. * Set of assets to keep when moving a scene into an asset container.
  25554. */
  25555. var KeepAssets = /** @class */ (function () {
  25556. function KeepAssets() {
  25557. /**
  25558. * Cameras to keep.
  25559. */
  25560. this.cameras = new Array();
  25561. /**
  25562. * Lights to keep.
  25563. */
  25564. this.lights = new Array();
  25565. /**
  25566. * Meshes to keep.
  25567. */
  25568. this.meshes = new Array();
  25569. /**
  25570. * Skeletons to keep.
  25571. */
  25572. this.skeletons = new Array();
  25573. /**
  25574. * ParticleSystems to keep.
  25575. */
  25576. this.particleSystems = new Array();
  25577. /**
  25578. * Animations to keep.
  25579. */
  25580. this.animations = new Array();
  25581. /**
  25582. * MultiMaterials to keep.
  25583. */
  25584. this.multiMaterials = new Array();
  25585. /**
  25586. * Materials to keep.
  25587. */
  25588. this.materials = new Array();
  25589. /**
  25590. * MorphTargetManagers to keep.
  25591. */
  25592. this.morphTargetManagers = new Array();
  25593. /**
  25594. * Geometries to keep.
  25595. */
  25596. this.geometries = new Array();
  25597. /**
  25598. * TransformNodes to keep.
  25599. */
  25600. this.transformNodes = new Array();
  25601. /**
  25602. * LensFlareSystems to keep.
  25603. */
  25604. this.lensFlareSystems = new Array();
  25605. /**
  25606. * ShadowGenerators to keep.
  25607. */
  25608. this.shadowGenerators = new Array();
  25609. /**
  25610. * ActionManagers to keep.
  25611. */
  25612. this.actionManagers = new Array();
  25613. /**
  25614. * Sounds to keep.
  25615. */
  25616. this.sounds = new Array();
  25617. }
  25618. return KeepAssets;
  25619. }());
  25620. BABYLON.KeepAssets = KeepAssets;
  25621. /**
  25622. * Container with a set of assets that can be added or removed from a scene.
  25623. */
  25624. var AssetContainer = /** @class */ (function () {
  25625. /**
  25626. * Instantiates an AssetContainer.
  25627. * @param scene The scene the AssetContainer belongs to.
  25628. */
  25629. function AssetContainer(scene) {
  25630. // Objects
  25631. /**
  25632. * Cameras populated in the container.
  25633. */
  25634. this.cameras = new Array();
  25635. /**
  25636. * Lights populated in the container.
  25637. */
  25638. this.lights = new Array();
  25639. /**
  25640. * Meshes populated in the container.
  25641. */
  25642. this.meshes = new Array();
  25643. /**
  25644. * Skeletons populated in the container.
  25645. */
  25646. this.skeletons = new Array();
  25647. /**
  25648. * ParticleSystems populated in the container.
  25649. */
  25650. this.particleSystems = new Array();
  25651. /**
  25652. * Animations populated in the container.
  25653. */
  25654. this.animations = new Array();
  25655. /**
  25656. * MultiMaterials populated in the container.
  25657. */
  25658. this.multiMaterials = new Array();
  25659. /**
  25660. * Materials populated in the container.
  25661. */
  25662. this.materials = new Array();
  25663. /**
  25664. * MorphTargetManagers populated in the container.
  25665. */
  25666. this.morphTargetManagers = new Array();
  25667. /**
  25668. * Geometries populated in the container.
  25669. */
  25670. this.geometries = new Array();
  25671. /**
  25672. * TransformNodes populated in the container.
  25673. */
  25674. this.transformNodes = new Array();
  25675. /**
  25676. * LensFlareSystems populated in the container.
  25677. */
  25678. this.lensFlareSystems = new Array();
  25679. /**
  25680. * ShadowGenerators populated in the container.
  25681. */
  25682. this.shadowGenerators = new Array();
  25683. /**
  25684. * ActionManagers populated in the container.
  25685. */
  25686. this.actionManagers = new Array();
  25687. /**
  25688. * Sounds populated in the container.
  25689. */
  25690. this.sounds = new Array();
  25691. this.scene = scene;
  25692. }
  25693. /**
  25694. * Adds all the assets from the container to the scene.
  25695. */
  25696. AssetContainer.prototype.addAllToScene = function () {
  25697. var _this = this;
  25698. this.cameras.forEach(function (o) {
  25699. _this.scene.addCamera(o);
  25700. });
  25701. this.lights.forEach(function (o) {
  25702. _this.scene.addLight(o);
  25703. });
  25704. this.meshes.forEach(function (o) {
  25705. _this.scene.addMesh(o);
  25706. });
  25707. this.skeletons.forEach(function (o) {
  25708. _this.scene.addSkeleton(o);
  25709. });
  25710. this.particleSystems.forEach(function (o) {
  25711. _this.scene.addParticleSystem(o);
  25712. });
  25713. this.animations.forEach(function (o) {
  25714. _this.scene.addAnimation(o);
  25715. });
  25716. this.multiMaterials.forEach(function (o) {
  25717. _this.scene.addMultiMaterial(o);
  25718. });
  25719. this.materials.forEach(function (o) {
  25720. _this.scene.addMaterial(o);
  25721. });
  25722. this.morphTargetManagers.forEach(function (o) {
  25723. _this.scene.addMorphTargetManager(o);
  25724. });
  25725. this.geometries.forEach(function (o) {
  25726. _this.scene.addGeometry(o);
  25727. });
  25728. this.transformNodes.forEach(function (o) {
  25729. _this.scene.addTransformNode(o);
  25730. });
  25731. this.lensFlareSystems.forEach(function (o) {
  25732. _this.scene.addLensFlareSystem(o);
  25733. });
  25734. this.actionManagers.forEach(function (o) {
  25735. _this.scene.addActionManager(o);
  25736. });
  25737. this.sounds.forEach(function (o) {
  25738. o.play();
  25739. o.autoplay = true;
  25740. _this.scene.mainSoundTrack.AddSound(o);
  25741. });
  25742. };
  25743. /**
  25744. * Removes all the assets in the container from the scene
  25745. */
  25746. AssetContainer.prototype.removeAllFromScene = function () {
  25747. var _this = this;
  25748. this.cameras.forEach(function (o) {
  25749. _this.scene.removeCamera(o);
  25750. });
  25751. this.lights.forEach(function (o) {
  25752. _this.scene.removeLight(o);
  25753. });
  25754. this.meshes.forEach(function (o) {
  25755. _this.scene.removeMesh(o);
  25756. });
  25757. this.skeletons.forEach(function (o) {
  25758. _this.scene.removeSkeleton(o);
  25759. });
  25760. this.particleSystems.forEach(function (o) {
  25761. _this.scene.removeParticleSystem(o);
  25762. });
  25763. this.animations.forEach(function (o) {
  25764. _this.scene.removeAnimation(o);
  25765. });
  25766. this.multiMaterials.forEach(function (o) {
  25767. _this.scene.removeMultiMaterial(o);
  25768. });
  25769. this.materials.forEach(function (o) {
  25770. _this.scene.removeMaterial(o);
  25771. });
  25772. this.morphTargetManagers.forEach(function (o) {
  25773. _this.scene.removeMorphTargetManager(o);
  25774. });
  25775. this.geometries.forEach(function (o) {
  25776. _this.scene.removeGeometry(o);
  25777. });
  25778. this.transformNodes.forEach(function (o) {
  25779. _this.scene.removeTransformNode(o);
  25780. });
  25781. this.lensFlareSystems.forEach(function (o) {
  25782. _this.scene.removeLensFlareSystem(o);
  25783. });
  25784. this.actionManagers.forEach(function (o) {
  25785. _this.scene.removeActionManager(o);
  25786. });
  25787. this.sounds.forEach(function (o) {
  25788. o.stop();
  25789. o.autoplay = false;
  25790. _this.scene.mainSoundTrack.RemoveSound(o);
  25791. });
  25792. };
  25793. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25794. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25795. var asset = sourceAssets_1[_i];
  25796. var move = true;
  25797. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25798. var keepAsset = keepAssets_1[_a];
  25799. if (asset === keepAsset) {
  25800. move = false;
  25801. break;
  25802. }
  25803. }
  25804. if (move) {
  25805. targetAssets.push(asset);
  25806. }
  25807. }
  25808. };
  25809. /**
  25810. * Removes all the assets contained in the scene and adds them to the container.
  25811. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25812. */
  25813. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25814. if (keepAssets === undefined) {
  25815. keepAssets = new KeepAssets();
  25816. }
  25817. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25818. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25819. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25820. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25821. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25822. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25823. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25824. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25825. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25826. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25827. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25828. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25829. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25830. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25831. this.removeAllFromScene();
  25832. };
  25833. return AssetContainer;
  25834. }());
  25835. BABYLON.AssetContainer = AssetContainer;
  25836. })(BABYLON || (BABYLON = {}));
  25837. //# sourceMappingURL=babylon.assetContainer.js.map
  25838. var BABYLON;
  25839. (function (BABYLON) {
  25840. var Buffer = /** @class */ (function () {
  25841. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25842. if (instanced === void 0) { instanced = false; }
  25843. if (engine instanceof BABYLON.Mesh) {
  25844. this._engine = engine.getScene().getEngine();
  25845. }
  25846. else {
  25847. this._engine = engine;
  25848. }
  25849. this._updatable = updatable;
  25850. this._instanced = instanced;
  25851. this._data = data;
  25852. this._strideSize = stride;
  25853. if (!postponeInternalCreation) {
  25854. this.create();
  25855. }
  25856. }
  25857. /**
  25858. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25859. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25860. * @param offset defines offset in the buffer (0 by default)
  25861. * @param size defines the size in floats of attributes (position is 3 for instance)
  25862. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25863. * @param instanced defines if the vertex buffer contains indexed data
  25864. * @returns the new vertex buffer
  25865. */
  25866. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25867. // a lot of these parameters are ignored as they are overriden by the buffer
  25868. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25869. };
  25870. // Properties
  25871. Buffer.prototype.isUpdatable = function () {
  25872. return this._updatable;
  25873. };
  25874. Buffer.prototype.getData = function () {
  25875. return this._data;
  25876. };
  25877. Buffer.prototype.getBuffer = function () {
  25878. return this._buffer;
  25879. };
  25880. Buffer.prototype.getStrideSize = function () {
  25881. return this._strideSize;
  25882. };
  25883. // public getIsInstanced(): boolean {
  25884. // return this._instanced;
  25885. // }
  25886. // public get instanceDivisor(): number {
  25887. // return this._instanceDivisor;
  25888. // }
  25889. // public set instanceDivisor(value: number) {
  25890. // this._instanceDivisor = value;
  25891. // if (value == 0) {
  25892. // this._instanced = false;
  25893. // } else {
  25894. // this._instanced = true;
  25895. // }
  25896. // }
  25897. // Methods
  25898. Buffer.prototype.create = function (data) {
  25899. if (data === void 0) { data = null; }
  25900. if (!data && this._buffer) {
  25901. return; // nothing to do
  25902. }
  25903. data = data || this._data;
  25904. if (!data) {
  25905. return;
  25906. }
  25907. if (!this._buffer) {
  25908. if (this._updatable) {
  25909. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25910. this._data = data;
  25911. }
  25912. else {
  25913. this._buffer = this._engine.createVertexBuffer(data);
  25914. }
  25915. }
  25916. else if (this._updatable) {
  25917. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25918. this._data = data;
  25919. }
  25920. };
  25921. Buffer.prototype._rebuild = function () {
  25922. this._buffer = null;
  25923. this.create(this._data);
  25924. };
  25925. Buffer.prototype.update = function (data) {
  25926. this.create(data);
  25927. };
  25928. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25929. if (!this._buffer) {
  25930. return;
  25931. }
  25932. if (this._updatable) {
  25933. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25934. this._data = null;
  25935. }
  25936. };
  25937. Buffer.prototype.dispose = function () {
  25938. if (!this._buffer) {
  25939. return;
  25940. }
  25941. if (this._engine._releaseBuffer(this._buffer)) {
  25942. this._buffer = null;
  25943. }
  25944. };
  25945. return Buffer;
  25946. }());
  25947. BABYLON.Buffer = Buffer;
  25948. })(BABYLON || (BABYLON = {}));
  25949. //# sourceMappingURL=babylon.buffer.js.map
  25950. var BABYLON;
  25951. (function (BABYLON) {
  25952. var VertexBuffer = /** @class */ (function () {
  25953. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25954. if (data instanceof BABYLON.Buffer) {
  25955. if (!stride) {
  25956. stride = data.getStrideSize();
  25957. }
  25958. this._buffer = data;
  25959. this._ownsBuffer = false;
  25960. }
  25961. else {
  25962. if (!stride) {
  25963. stride = VertexBuffer.DeduceStride(kind);
  25964. }
  25965. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25966. this._ownsBuffer = true;
  25967. }
  25968. this._stride = stride;
  25969. this._instanced = instanced !== undefined ? instanced : false;
  25970. this._instanceDivisor = instanced ? 1 : 0;
  25971. this._offset = offset ? offset : 0;
  25972. this._size = size ? size : stride;
  25973. this._kind = kind;
  25974. }
  25975. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25976. /**
  25977. * Gets or sets the instance divisor when in instanced mode
  25978. */
  25979. get: function () {
  25980. return this._instanceDivisor;
  25981. },
  25982. set: function (value) {
  25983. this._instanceDivisor = value;
  25984. if (value == 0) {
  25985. this._instanced = false;
  25986. }
  25987. else {
  25988. this._instanced = true;
  25989. }
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. VertexBuffer.prototype._rebuild = function () {
  25995. if (!this._buffer) {
  25996. return;
  25997. }
  25998. this._buffer._rebuild();
  25999. };
  26000. /**
  26001. * Returns the kind of the VertexBuffer (string).
  26002. */
  26003. VertexBuffer.prototype.getKind = function () {
  26004. return this._kind;
  26005. };
  26006. // Properties
  26007. /**
  26008. * Boolean : is the VertexBuffer updatable ?
  26009. */
  26010. VertexBuffer.prototype.isUpdatable = function () {
  26011. return this._buffer.isUpdatable();
  26012. };
  26013. /**
  26014. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26015. */
  26016. VertexBuffer.prototype.getData = function () {
  26017. return this._buffer.getData();
  26018. };
  26019. /**
  26020. * Returns the WebGLBuffer associated to the VertexBuffer.
  26021. */
  26022. VertexBuffer.prototype.getBuffer = function () {
  26023. return this._buffer.getBuffer();
  26024. };
  26025. /**
  26026. * Returns the stride of the VertexBuffer (integer).
  26027. */
  26028. VertexBuffer.prototype.getStrideSize = function () {
  26029. return this._stride;
  26030. };
  26031. /**
  26032. * Returns the offset (integer).
  26033. */
  26034. VertexBuffer.prototype.getOffset = function () {
  26035. return this._offset;
  26036. };
  26037. /**
  26038. * Returns the VertexBuffer total size (integer).
  26039. */
  26040. VertexBuffer.prototype.getSize = function () {
  26041. return this._size;
  26042. };
  26043. /**
  26044. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26045. */
  26046. VertexBuffer.prototype.getIsInstanced = function () {
  26047. return this._instanced;
  26048. };
  26049. /**
  26050. * Returns the instancing divisor, zero for non-instanced (integer).
  26051. */
  26052. VertexBuffer.prototype.getInstanceDivisor = function () {
  26053. return this._instanceDivisor;
  26054. };
  26055. // Methods
  26056. /**
  26057. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26058. * Returns the created WebGLBuffer.
  26059. */
  26060. VertexBuffer.prototype.create = function (data) {
  26061. return this._buffer.create(data);
  26062. };
  26063. /**
  26064. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26065. * This function will create a new buffer if the current one is not updatable
  26066. * Returns the updated WebGLBuffer.
  26067. */
  26068. VertexBuffer.prototype.update = function (data) {
  26069. return this._buffer.update(data);
  26070. };
  26071. /**
  26072. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26073. * Returns the directly updated WebGLBuffer.
  26074. */
  26075. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26076. return this._buffer.updateDirectly(data, offset);
  26077. };
  26078. /**
  26079. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26080. */
  26081. VertexBuffer.prototype.dispose = function () {
  26082. if (this._ownsBuffer) {
  26083. this._buffer.dispose();
  26084. }
  26085. };
  26086. Object.defineProperty(VertexBuffer, "PositionKind", {
  26087. get: function () {
  26088. return VertexBuffer._PositionKind;
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. Object.defineProperty(VertexBuffer, "NormalKind", {
  26094. get: function () {
  26095. return VertexBuffer._NormalKind;
  26096. },
  26097. enumerable: true,
  26098. configurable: true
  26099. });
  26100. Object.defineProperty(VertexBuffer, "TangentKind", {
  26101. get: function () {
  26102. return VertexBuffer._TangentKind;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. Object.defineProperty(VertexBuffer, "UVKind", {
  26108. get: function () {
  26109. return VertexBuffer._UVKind;
  26110. },
  26111. enumerable: true,
  26112. configurable: true
  26113. });
  26114. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26115. get: function () {
  26116. return VertexBuffer._UV2Kind;
  26117. },
  26118. enumerable: true,
  26119. configurable: true
  26120. });
  26121. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26122. get: function () {
  26123. return VertexBuffer._UV3Kind;
  26124. },
  26125. enumerable: true,
  26126. configurable: true
  26127. });
  26128. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26129. get: function () {
  26130. return VertexBuffer._UV4Kind;
  26131. },
  26132. enumerable: true,
  26133. configurable: true
  26134. });
  26135. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26136. get: function () {
  26137. return VertexBuffer._UV5Kind;
  26138. },
  26139. enumerable: true,
  26140. configurable: true
  26141. });
  26142. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26143. get: function () {
  26144. return VertexBuffer._UV6Kind;
  26145. },
  26146. enumerable: true,
  26147. configurable: true
  26148. });
  26149. Object.defineProperty(VertexBuffer, "ColorKind", {
  26150. get: function () {
  26151. return VertexBuffer._ColorKind;
  26152. },
  26153. enumerable: true,
  26154. configurable: true
  26155. });
  26156. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26157. get: function () {
  26158. return VertexBuffer._MatricesIndicesKind;
  26159. },
  26160. enumerable: true,
  26161. configurable: true
  26162. });
  26163. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26164. get: function () {
  26165. return VertexBuffer._MatricesWeightsKind;
  26166. },
  26167. enumerable: true,
  26168. configurable: true
  26169. });
  26170. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26171. get: function () {
  26172. return VertexBuffer._MatricesIndicesExtraKind;
  26173. },
  26174. enumerable: true,
  26175. configurable: true
  26176. });
  26177. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26178. get: function () {
  26179. return VertexBuffer._MatricesWeightsExtraKind;
  26180. },
  26181. enumerable: true,
  26182. configurable: true
  26183. });
  26184. /**
  26185. * Deduces the stride given a kind.
  26186. * @param kind The kind string to deduce
  26187. * @returns The deduced stride
  26188. */
  26189. VertexBuffer.DeduceStride = function (kind) {
  26190. switch (kind) {
  26191. case VertexBuffer.UVKind:
  26192. case VertexBuffer.UV2Kind:
  26193. case VertexBuffer.UV3Kind:
  26194. case VertexBuffer.UV4Kind:
  26195. case VertexBuffer.UV5Kind:
  26196. case VertexBuffer.UV6Kind:
  26197. return 2;
  26198. case VertexBuffer.NormalKind:
  26199. case VertexBuffer.PositionKind:
  26200. return 3;
  26201. case VertexBuffer.ColorKind:
  26202. case VertexBuffer.MatricesIndicesKind:
  26203. case VertexBuffer.MatricesIndicesExtraKind:
  26204. case VertexBuffer.MatricesWeightsKind:
  26205. case VertexBuffer.MatricesWeightsExtraKind:
  26206. case VertexBuffer.TangentKind:
  26207. return 4;
  26208. default:
  26209. throw new Error("Invalid kind '" + kind + "'");
  26210. }
  26211. };
  26212. // Enums
  26213. VertexBuffer._PositionKind = "position";
  26214. VertexBuffer._NormalKind = "normal";
  26215. VertexBuffer._TangentKind = "tangent";
  26216. VertexBuffer._UVKind = "uv";
  26217. VertexBuffer._UV2Kind = "uv2";
  26218. VertexBuffer._UV3Kind = "uv3";
  26219. VertexBuffer._UV4Kind = "uv4";
  26220. VertexBuffer._UV5Kind = "uv5";
  26221. VertexBuffer._UV6Kind = "uv6";
  26222. VertexBuffer._ColorKind = "color";
  26223. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26224. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26225. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26226. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26227. return VertexBuffer;
  26228. }());
  26229. BABYLON.VertexBuffer = VertexBuffer;
  26230. })(BABYLON || (BABYLON = {}));
  26231. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26232. var BABYLON;
  26233. (function (BABYLON) {
  26234. /**
  26235. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26236. */
  26237. var DummyInternalTextureTracker = /** @class */ (function () {
  26238. function DummyInternalTextureTracker() {
  26239. /**
  26240. * Gets or set the previous tracker in the list
  26241. */
  26242. this.previous = null;
  26243. /**
  26244. * Gets or set the next tracker in the list
  26245. */
  26246. this.next = null;
  26247. }
  26248. return DummyInternalTextureTracker;
  26249. }());
  26250. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26251. })(BABYLON || (BABYLON = {}));
  26252. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26253. var BABYLON;
  26254. (function (BABYLON) {
  26255. /**
  26256. * Class used to store data associated with WebGL texture data for the engine
  26257. * This class should not be used directly
  26258. */
  26259. var InternalTexture = /** @class */ (function () {
  26260. /**
  26261. * Creates a new InternalTexture
  26262. * @param engine defines the engine to use
  26263. * @param dataSource defines the type of data that will be used
  26264. */
  26265. function InternalTexture(engine, dataSource) {
  26266. /**
  26267. * Observable called when the texture is loaded
  26268. */
  26269. this.onLoadedObservable = new BABYLON.Observable();
  26270. /**
  26271. * Gets or set the previous tracker in the list
  26272. */
  26273. this.previous = null;
  26274. /**
  26275. * Gets or set the next tracker in the list
  26276. */
  26277. this.next = null;
  26278. // Private
  26279. /** @ignore */
  26280. this._initialSlot = -1;
  26281. /** @ignore */
  26282. this._designatedSlot = -1;
  26283. /** @ignore */
  26284. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26285. /** @ignore */
  26286. this._comparisonFunction = 0;
  26287. /** @ignore */
  26288. this._references = 1;
  26289. this._engine = engine;
  26290. this._dataSource = dataSource;
  26291. this._webGLTexture = engine._createTexture();
  26292. }
  26293. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26294. /**
  26295. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26296. */
  26297. get: function () {
  26298. return this._dataSource;
  26299. },
  26300. enumerable: true,
  26301. configurable: true
  26302. });
  26303. /**
  26304. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26305. */
  26306. InternalTexture.prototype.incrementReferences = function () {
  26307. this._references++;
  26308. };
  26309. /**
  26310. * Change the size of the texture (not the size of the content)
  26311. * @param width defines the new width
  26312. * @param height defines the new height
  26313. * @param depth defines the new depth (1 by default)
  26314. */
  26315. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26316. if (depth === void 0) { depth = 1; }
  26317. this.width = width;
  26318. this.height = height;
  26319. this.depth = depth;
  26320. this.baseWidth = width;
  26321. this.baseHeight = height;
  26322. this.baseDepth = depth;
  26323. this._size = width * height * depth;
  26324. };
  26325. /** @ignore */
  26326. InternalTexture.prototype._rebuild = function () {
  26327. var _this = this;
  26328. var proxy;
  26329. this.isReady = false;
  26330. this._cachedCoordinatesMode = null;
  26331. this._cachedWrapU = null;
  26332. this._cachedWrapV = null;
  26333. this._cachedAnisotropicFilteringLevel = null;
  26334. switch (this._dataSource) {
  26335. case InternalTexture.DATASOURCE_TEMP:
  26336. return;
  26337. case InternalTexture.DATASOURCE_URL:
  26338. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26339. _this.isReady = true;
  26340. }, null, this._buffer, undefined, this.format);
  26341. proxy._swapAndDie(this);
  26342. return;
  26343. case InternalTexture.DATASOURCE_RAW:
  26344. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26345. proxy._swapAndDie(this);
  26346. this.isReady = true;
  26347. return;
  26348. case InternalTexture.DATASOURCE_RAW3D:
  26349. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26350. proxy._swapAndDie(this);
  26351. this.isReady = true;
  26352. return;
  26353. case InternalTexture.DATASOURCE_DYNAMIC:
  26354. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26355. proxy._swapAndDie(this);
  26356. // The engine will make sure to update content so no need to flag it as isReady = true
  26357. return;
  26358. case InternalTexture.DATASOURCE_RENDERTARGET:
  26359. var options = new BABYLON.RenderTargetCreationOptions();
  26360. options.generateDepthBuffer = this._generateDepthBuffer;
  26361. options.generateMipMaps = this.generateMipMaps;
  26362. options.generateStencilBuffer = this._generateStencilBuffer;
  26363. options.samplingMode = this.samplingMode;
  26364. options.type = this.type;
  26365. if (this.isCube) {
  26366. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26367. }
  26368. else {
  26369. var size = {
  26370. width: this.width,
  26371. height: this.height
  26372. };
  26373. proxy = this._engine.createRenderTargetTexture(size, options);
  26374. }
  26375. proxy._swapAndDie(this);
  26376. this.isReady = true;
  26377. return;
  26378. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26379. var depthTextureOptions = {
  26380. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26381. comparisonFunction: this._comparisonFunction,
  26382. generateStencil: this._generateStencilBuffer,
  26383. };
  26384. if (this.isCube) {
  26385. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26386. }
  26387. else {
  26388. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26389. }
  26390. proxy._swapAndDie(this);
  26391. this.isReady = true;
  26392. return;
  26393. case InternalTexture.DATASOURCE_CUBE:
  26394. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26395. _this.isReady = true;
  26396. }, null, this.format, this._extension);
  26397. proxy._swapAndDie(this);
  26398. return;
  26399. case InternalTexture.DATASOURCE_CUBERAW:
  26400. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26401. proxy._swapAndDie(this);
  26402. this.isReady = true;
  26403. return;
  26404. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26405. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26406. if (proxy) {
  26407. proxy._swapAndDie(_this);
  26408. }
  26409. _this.isReady = true;
  26410. }, null, this.format, this._extension);
  26411. return;
  26412. }
  26413. };
  26414. InternalTexture.prototype._swapAndDie = function (target) {
  26415. target._webGLTexture = this._webGLTexture;
  26416. if (this._framebuffer) {
  26417. target._framebuffer = this._framebuffer;
  26418. }
  26419. if (this._depthStencilBuffer) {
  26420. target._depthStencilBuffer = this._depthStencilBuffer;
  26421. }
  26422. if (this._lodTextureHigh) {
  26423. if (target._lodTextureHigh) {
  26424. target._lodTextureHigh.dispose();
  26425. }
  26426. target._lodTextureHigh = this._lodTextureHigh;
  26427. }
  26428. if (this._lodTextureMid) {
  26429. if (target._lodTextureMid) {
  26430. target._lodTextureMid.dispose();
  26431. }
  26432. target._lodTextureMid = this._lodTextureMid;
  26433. }
  26434. if (this._lodTextureLow) {
  26435. if (target._lodTextureLow) {
  26436. target._lodTextureLow.dispose();
  26437. }
  26438. target._lodTextureLow = this._lodTextureLow;
  26439. }
  26440. var cache = this._engine.getLoadedTexturesCache();
  26441. var index = cache.indexOf(this);
  26442. if (index !== -1) {
  26443. cache.splice(index, 1);
  26444. }
  26445. };
  26446. /**
  26447. * Dispose the current allocated resources
  26448. */
  26449. InternalTexture.prototype.dispose = function () {
  26450. if (!this._webGLTexture) {
  26451. return;
  26452. }
  26453. this._references--;
  26454. if (this._references === 0) {
  26455. this._engine._releaseTexture(this);
  26456. this._webGLTexture = null;
  26457. this.previous = null;
  26458. this.next = null;
  26459. }
  26460. };
  26461. /**
  26462. * The source of the texture data is unknown
  26463. */
  26464. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26465. /**
  26466. * Texture data comes from an URL
  26467. */
  26468. InternalTexture.DATASOURCE_URL = 1;
  26469. /**
  26470. * Texture data is only used for temporary storage
  26471. */
  26472. InternalTexture.DATASOURCE_TEMP = 2;
  26473. /**
  26474. * Texture data comes from raw data (ArrayBuffer)
  26475. */
  26476. InternalTexture.DATASOURCE_RAW = 3;
  26477. /**
  26478. * Texture content is dynamic (video or dynamic texture)
  26479. */
  26480. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26481. /**
  26482. * Texture content is generated by rendering to it
  26483. */
  26484. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26485. /**
  26486. * Texture content is part of a multi render target process
  26487. */
  26488. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26489. /**
  26490. * Texture data comes from a cube data file
  26491. */
  26492. InternalTexture.DATASOURCE_CUBE = 7;
  26493. /**
  26494. * Texture data comes from a raw cube data
  26495. */
  26496. InternalTexture.DATASOURCE_CUBERAW = 8;
  26497. /**
  26498. * Texture data come from a prefiltered cube data file
  26499. */
  26500. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26501. /**
  26502. * Texture content is raw 3D data
  26503. */
  26504. InternalTexture.DATASOURCE_RAW3D = 10;
  26505. /**
  26506. * Texture content is a depth texture
  26507. */
  26508. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26509. return InternalTexture;
  26510. }());
  26511. BABYLON.InternalTexture = InternalTexture;
  26512. })(BABYLON || (BABYLON = {}));
  26513. //# sourceMappingURL=babylon.internalTexture.js.map
  26514. var BABYLON;
  26515. (function (BABYLON) {
  26516. var BaseTexture = /** @class */ (function () {
  26517. function BaseTexture(scene) {
  26518. this._hasAlpha = false;
  26519. this.getAlphaFromRGB = false;
  26520. this.level = 1;
  26521. this.coordinatesIndex = 0;
  26522. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26523. /**
  26524. * | Value | Type | Description |
  26525. * | ----- | ------------------ | ----------- |
  26526. * | 0 | CLAMP_ADDRESSMODE | |
  26527. * | 1 | WRAP_ADDRESSMODE | |
  26528. * | 2 | MIRROR_ADDRESSMODE | |
  26529. */
  26530. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26531. /**
  26532. * | Value | Type | Description |
  26533. * | ----- | ------------------ | ----------- |
  26534. * | 0 | CLAMP_ADDRESSMODE | |
  26535. * | 1 | WRAP_ADDRESSMODE | |
  26536. * | 2 | MIRROR_ADDRESSMODE | |
  26537. */
  26538. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26539. /**
  26540. * | Value | Type | Description |
  26541. * | ----- | ------------------ | ----------- |
  26542. * | 0 | CLAMP_ADDRESSMODE | |
  26543. * | 1 | WRAP_ADDRESSMODE | |
  26544. * | 2 | MIRROR_ADDRESSMODE | |
  26545. */
  26546. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26547. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26548. this.isCube = false;
  26549. this.is3D = false;
  26550. this.gammaSpace = true;
  26551. this.invertZ = false;
  26552. this.lodLevelInAlpha = false;
  26553. this.lodGenerationOffset = 0.0;
  26554. this.lodGenerationScale = 0.8;
  26555. this.isRenderTarget = false;
  26556. this.animations = new Array();
  26557. /**
  26558. * An event triggered when the texture is disposed.
  26559. * @type {BABYLON.Observable}
  26560. */
  26561. this.onDisposeObservable = new BABYLON.Observable();
  26562. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26563. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26564. if (this._scene) {
  26565. this._scene.textures.push(this);
  26566. }
  26567. this._uid = null;
  26568. }
  26569. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26570. get: function () {
  26571. return this._hasAlpha;
  26572. },
  26573. set: function (value) {
  26574. if (this._hasAlpha === value) {
  26575. return;
  26576. }
  26577. this._hasAlpha = value;
  26578. if (this._scene) {
  26579. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26580. }
  26581. },
  26582. enumerable: true,
  26583. configurable: true
  26584. });
  26585. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26586. get: function () {
  26587. return this._coordinatesMode;
  26588. },
  26589. /**
  26590. * How a texture is mapped.
  26591. *
  26592. * | Value | Type | Description |
  26593. * | ----- | ----------------------------------- | ----------- |
  26594. * | 0 | EXPLICIT_MODE | |
  26595. * | 1 | SPHERICAL_MODE | |
  26596. * | 2 | PLANAR_MODE | |
  26597. * | 3 | CUBIC_MODE | |
  26598. * | 4 | PROJECTION_MODE | |
  26599. * | 5 | SKYBOX_MODE | |
  26600. * | 6 | INVCUBIC_MODE | |
  26601. * | 7 | EQUIRECTANGULAR_MODE | |
  26602. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26603. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26604. */
  26605. set: function (value) {
  26606. if (this._coordinatesMode === value) {
  26607. return;
  26608. }
  26609. this._coordinatesMode = value;
  26610. if (this._scene) {
  26611. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26612. }
  26613. },
  26614. enumerable: true,
  26615. configurable: true
  26616. });
  26617. Object.defineProperty(BaseTexture.prototype, "uid", {
  26618. get: function () {
  26619. if (!this._uid) {
  26620. this._uid = BABYLON.Tools.RandomId();
  26621. }
  26622. return this._uid;
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. BaseTexture.prototype.toString = function () {
  26628. return this.name;
  26629. };
  26630. BaseTexture.prototype.getClassName = function () {
  26631. return "BaseTexture";
  26632. };
  26633. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26634. set: function (callback) {
  26635. if (this._onDisposeObserver) {
  26636. this.onDisposeObservable.remove(this._onDisposeObserver);
  26637. }
  26638. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26639. },
  26640. enumerable: true,
  26641. configurable: true
  26642. });
  26643. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26644. get: function () {
  26645. return true;
  26646. },
  26647. enumerable: true,
  26648. configurable: true
  26649. });
  26650. BaseTexture.prototype.getScene = function () {
  26651. return this._scene;
  26652. };
  26653. BaseTexture.prototype.getTextureMatrix = function () {
  26654. return BABYLON.Matrix.IdentityReadOnly;
  26655. };
  26656. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26657. return BABYLON.Matrix.IdentityReadOnly;
  26658. };
  26659. BaseTexture.prototype.getInternalTexture = function () {
  26660. return this._texture;
  26661. };
  26662. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26663. return !this.isBlocking || this.isReady();
  26664. };
  26665. BaseTexture.prototype.isReady = function () {
  26666. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26667. this.delayLoad();
  26668. return false;
  26669. }
  26670. if (this._texture) {
  26671. return this._texture.isReady;
  26672. }
  26673. return false;
  26674. };
  26675. BaseTexture.prototype.getSize = function () {
  26676. if (this._texture && this._texture.width) {
  26677. return new BABYLON.Size(this._texture.width, this._texture.height);
  26678. }
  26679. if (this._texture && this._texture._size) {
  26680. return new BABYLON.Size(this._texture._size, this._texture._size);
  26681. }
  26682. return BABYLON.Size.Zero();
  26683. };
  26684. BaseTexture.prototype.getBaseSize = function () {
  26685. if (!this.isReady() || !this._texture)
  26686. return BABYLON.Size.Zero();
  26687. if (this._texture._size) {
  26688. return new BABYLON.Size(this._texture._size, this._texture._size);
  26689. }
  26690. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26691. };
  26692. BaseTexture.prototype.scale = function (ratio) {
  26693. };
  26694. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26695. get: function () {
  26696. return false;
  26697. },
  26698. enumerable: true,
  26699. configurable: true
  26700. });
  26701. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26702. if (!this._scene) {
  26703. return null;
  26704. }
  26705. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26706. for (var index = 0; index < texturesCache.length; index++) {
  26707. var texturesCacheEntry = texturesCache[index];
  26708. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26709. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26710. texturesCacheEntry.incrementReferences();
  26711. return texturesCacheEntry;
  26712. }
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. BaseTexture.prototype._rebuild = function () {
  26718. };
  26719. BaseTexture.prototype.delayLoad = function () {
  26720. };
  26721. BaseTexture.prototype.clone = function () {
  26722. return null;
  26723. };
  26724. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26725. get: function () {
  26726. if (!this._texture) {
  26727. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26728. }
  26729. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26730. },
  26731. enumerable: true,
  26732. configurable: true
  26733. });
  26734. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26735. get: function () {
  26736. if (!this._texture) {
  26737. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26738. }
  26739. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. BaseTexture.prototype.readPixels = function (faceIndex) {
  26745. if (faceIndex === void 0) { faceIndex = 0; }
  26746. if (!this._texture) {
  26747. return null;
  26748. }
  26749. var size = this.getSize();
  26750. var scene = this.getScene();
  26751. if (!scene) {
  26752. return null;
  26753. }
  26754. var engine = scene.getEngine();
  26755. if (this._texture.isCube) {
  26756. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26757. }
  26758. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26759. };
  26760. BaseTexture.prototype.releaseInternalTexture = function () {
  26761. if (this._texture) {
  26762. this._texture.dispose();
  26763. this._texture = null;
  26764. }
  26765. };
  26766. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26767. get: function () {
  26768. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26769. return null;
  26770. }
  26771. if (!this._texture._sphericalPolynomial) {
  26772. this._texture._sphericalPolynomial =
  26773. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26774. }
  26775. return this._texture._sphericalPolynomial;
  26776. },
  26777. set: function (value) {
  26778. if (this._texture) {
  26779. this._texture._sphericalPolynomial = value;
  26780. }
  26781. },
  26782. enumerable: true,
  26783. configurable: true
  26784. });
  26785. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26786. get: function () {
  26787. if (this._texture) {
  26788. return this._texture._lodTextureHigh;
  26789. }
  26790. return null;
  26791. },
  26792. enumerable: true,
  26793. configurable: true
  26794. });
  26795. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26796. get: function () {
  26797. if (this._texture) {
  26798. return this._texture._lodTextureMid;
  26799. }
  26800. return null;
  26801. },
  26802. enumerable: true,
  26803. configurable: true
  26804. });
  26805. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26806. get: function () {
  26807. if (this._texture) {
  26808. return this._texture._lodTextureLow;
  26809. }
  26810. return null;
  26811. },
  26812. enumerable: true,
  26813. configurable: true
  26814. });
  26815. BaseTexture.prototype.dispose = function () {
  26816. if (!this._scene) {
  26817. return;
  26818. }
  26819. // Animations
  26820. this._scene.stopAnimation(this);
  26821. // Remove from scene
  26822. this._scene._removePendingData(this);
  26823. var index = this._scene.textures.indexOf(this);
  26824. if (index >= 0) {
  26825. this._scene.textures.splice(index, 1);
  26826. }
  26827. if (this._texture === undefined) {
  26828. return;
  26829. }
  26830. // Release
  26831. this.releaseInternalTexture();
  26832. // Callback
  26833. this.onDisposeObservable.notifyObservers(this);
  26834. this.onDisposeObservable.clear();
  26835. };
  26836. BaseTexture.prototype.serialize = function () {
  26837. if (!this.name) {
  26838. return null;
  26839. }
  26840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26841. // Animations
  26842. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26843. return serializationObject;
  26844. };
  26845. BaseTexture.WhenAllReady = function (textures, callback) {
  26846. var numRemaining = textures.length;
  26847. if (numRemaining === 0) {
  26848. callback();
  26849. return;
  26850. }
  26851. var _loop_1 = function () {
  26852. texture = textures[i];
  26853. if (texture.isReady()) {
  26854. if (--numRemaining === 0) {
  26855. callback();
  26856. }
  26857. }
  26858. else {
  26859. onLoadObservable = texture.onLoadObservable;
  26860. var onLoadCallback_1 = function () {
  26861. onLoadObservable.removeCallback(onLoadCallback_1);
  26862. if (--numRemaining === 0) {
  26863. callback();
  26864. }
  26865. };
  26866. onLoadObservable.add(onLoadCallback_1);
  26867. }
  26868. };
  26869. var texture, onLoadObservable;
  26870. for (var i = 0; i < textures.length; i++) {
  26871. _loop_1();
  26872. }
  26873. };
  26874. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26875. __decorate([
  26876. BABYLON.serialize()
  26877. ], BaseTexture.prototype, "name", void 0);
  26878. __decorate([
  26879. BABYLON.serialize("hasAlpha")
  26880. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26881. __decorate([
  26882. BABYLON.serialize()
  26883. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26884. __decorate([
  26885. BABYLON.serialize()
  26886. ], BaseTexture.prototype, "level", void 0);
  26887. __decorate([
  26888. BABYLON.serialize()
  26889. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26890. __decorate([
  26891. BABYLON.serialize("coordinatesMode")
  26892. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26893. __decorate([
  26894. BABYLON.serialize()
  26895. ], BaseTexture.prototype, "wrapU", void 0);
  26896. __decorate([
  26897. BABYLON.serialize()
  26898. ], BaseTexture.prototype, "wrapV", void 0);
  26899. __decorate([
  26900. BABYLON.serialize()
  26901. ], BaseTexture.prototype, "wrapR", void 0);
  26902. __decorate([
  26903. BABYLON.serialize()
  26904. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26905. __decorate([
  26906. BABYLON.serialize()
  26907. ], BaseTexture.prototype, "isCube", void 0);
  26908. __decorate([
  26909. BABYLON.serialize()
  26910. ], BaseTexture.prototype, "is3D", void 0);
  26911. __decorate([
  26912. BABYLON.serialize()
  26913. ], BaseTexture.prototype, "gammaSpace", void 0);
  26914. __decorate([
  26915. BABYLON.serialize()
  26916. ], BaseTexture.prototype, "invertZ", void 0);
  26917. __decorate([
  26918. BABYLON.serialize()
  26919. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26920. __decorate([
  26921. BABYLON.serialize()
  26922. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26923. __decorate([
  26924. BABYLON.serialize()
  26925. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26926. __decorate([
  26927. BABYLON.serialize()
  26928. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26929. return BaseTexture;
  26930. }());
  26931. BABYLON.BaseTexture = BaseTexture;
  26932. })(BABYLON || (BABYLON = {}));
  26933. //# sourceMappingURL=babylon.baseTexture.js.map
  26934. var BABYLON;
  26935. (function (BABYLON) {
  26936. var Texture = /** @class */ (function (_super) {
  26937. __extends(Texture, _super);
  26938. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26939. if (noMipmap === void 0) { noMipmap = false; }
  26940. if (invertY === void 0) { invertY = true; }
  26941. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26942. if (onLoad === void 0) { onLoad = null; }
  26943. if (onError === void 0) { onError = null; }
  26944. if (buffer === void 0) { buffer = null; }
  26945. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26946. var _this = _super.call(this, scene) || this;
  26947. _this.uOffset = 0;
  26948. _this.vOffset = 0;
  26949. _this.uScale = 1.0;
  26950. _this.vScale = 1.0;
  26951. _this.uAng = 0;
  26952. _this.vAng = 0;
  26953. _this.wAng = 0;
  26954. _this._isBlocking = true;
  26955. _this.name = url || "";
  26956. _this.url = url;
  26957. _this._noMipmap = noMipmap;
  26958. _this._invertY = invertY;
  26959. _this._samplingMode = samplingMode;
  26960. _this._buffer = buffer;
  26961. _this._deleteBuffer = deleteBuffer;
  26962. if (format) {
  26963. _this._format = format;
  26964. }
  26965. scene = _this.getScene();
  26966. if (!scene) {
  26967. return _this;
  26968. }
  26969. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26970. var load = function () {
  26971. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26972. _this.onLoadObservable.notifyObservers(_this);
  26973. }
  26974. if (onLoad) {
  26975. onLoad();
  26976. }
  26977. if (!_this.isBlocking && scene) {
  26978. scene.resetCachedMaterial();
  26979. }
  26980. };
  26981. if (!_this.url) {
  26982. _this._delayedOnLoad = load;
  26983. _this._delayedOnError = onError;
  26984. return _this;
  26985. }
  26986. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26987. if (!_this._texture) {
  26988. if (!scene.useDelayedTextureLoading) {
  26989. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26990. if (deleteBuffer) {
  26991. delete _this._buffer;
  26992. }
  26993. }
  26994. else {
  26995. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26996. _this._delayedOnLoad = load;
  26997. _this._delayedOnError = onError;
  26998. }
  26999. }
  27000. else {
  27001. if (_this._texture.isReady) {
  27002. BABYLON.Tools.SetImmediate(function () { return load(); });
  27003. }
  27004. else {
  27005. _this._texture.onLoadedObservable.add(load);
  27006. }
  27007. }
  27008. return _this;
  27009. }
  27010. Object.defineProperty(Texture.prototype, "noMipmap", {
  27011. get: function () {
  27012. return this._noMipmap;
  27013. },
  27014. enumerable: true,
  27015. configurable: true
  27016. });
  27017. Object.defineProperty(Texture.prototype, "isBlocking", {
  27018. get: function () {
  27019. return this._isBlocking;
  27020. },
  27021. set: function (value) {
  27022. this._isBlocking = value;
  27023. },
  27024. enumerable: true,
  27025. configurable: true
  27026. });
  27027. Object.defineProperty(Texture.prototype, "samplingMode", {
  27028. get: function () {
  27029. return this._samplingMode;
  27030. },
  27031. enumerable: true,
  27032. configurable: true
  27033. });
  27034. Texture.prototype.updateURL = function (url) {
  27035. this.url = url;
  27036. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27037. this.delayLoad();
  27038. };
  27039. Texture.prototype.delayLoad = function () {
  27040. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27041. return;
  27042. }
  27043. var scene = this.getScene();
  27044. if (!scene) {
  27045. return;
  27046. }
  27047. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27048. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27049. if (!this._texture) {
  27050. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27051. if (this._deleteBuffer) {
  27052. delete this._buffer;
  27053. }
  27054. }
  27055. else {
  27056. if (this._delayedOnLoad) {
  27057. if (this._texture.isReady) {
  27058. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27059. }
  27060. else {
  27061. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27062. }
  27063. }
  27064. }
  27065. this._delayedOnLoad = null;
  27066. this._delayedOnError = null;
  27067. };
  27068. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27069. if (!this._texture) {
  27070. return;
  27071. }
  27072. var scene = this.getScene();
  27073. if (!scene) {
  27074. return;
  27075. }
  27076. this._samplingMode = samplingMode;
  27077. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27078. };
  27079. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27080. x *= this.uScale;
  27081. y *= this.vScale;
  27082. x -= 0.5 * this.uScale;
  27083. y -= 0.5 * this.vScale;
  27084. z -= 0.5;
  27085. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27086. t.x += 0.5 * this.uScale + this.uOffset;
  27087. t.y += 0.5 * this.vScale + this.vOffset;
  27088. t.z += 0.5;
  27089. };
  27090. Texture.prototype.getTextureMatrix = function () {
  27091. var _this = this;
  27092. if (this.uOffset === this._cachedUOffset &&
  27093. this.vOffset === this._cachedVOffset &&
  27094. this.uScale === this._cachedUScale &&
  27095. this.vScale === this._cachedVScale &&
  27096. this.uAng === this._cachedUAng &&
  27097. this.vAng === this._cachedVAng &&
  27098. this.wAng === this._cachedWAng) {
  27099. return this._cachedTextureMatrix;
  27100. }
  27101. this._cachedUOffset = this.uOffset;
  27102. this._cachedVOffset = this.vOffset;
  27103. this._cachedUScale = this.uScale;
  27104. this._cachedVScale = this.vScale;
  27105. this._cachedUAng = this.uAng;
  27106. this._cachedVAng = this.vAng;
  27107. this._cachedWAng = this.wAng;
  27108. if (!this._cachedTextureMatrix) {
  27109. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27110. this._rowGenerationMatrix = new BABYLON.Matrix();
  27111. this._t0 = BABYLON.Vector3.Zero();
  27112. this._t1 = BABYLON.Vector3.Zero();
  27113. this._t2 = BABYLON.Vector3.Zero();
  27114. }
  27115. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27116. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27117. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27118. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27119. this._t1.subtractInPlace(this._t0);
  27120. this._t2.subtractInPlace(this._t0);
  27121. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27122. this._cachedTextureMatrix.m[0] = this._t1.x;
  27123. this._cachedTextureMatrix.m[1] = this._t1.y;
  27124. this._cachedTextureMatrix.m[2] = this._t1.z;
  27125. this._cachedTextureMatrix.m[4] = this._t2.x;
  27126. this._cachedTextureMatrix.m[5] = this._t2.y;
  27127. this._cachedTextureMatrix.m[6] = this._t2.z;
  27128. this._cachedTextureMatrix.m[8] = this._t0.x;
  27129. this._cachedTextureMatrix.m[9] = this._t0.y;
  27130. this._cachedTextureMatrix.m[10] = this._t0.z;
  27131. var scene = this.getScene();
  27132. if (!scene) {
  27133. return this._cachedTextureMatrix;
  27134. }
  27135. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27136. return mat.hasTexture(_this);
  27137. });
  27138. return this._cachedTextureMatrix;
  27139. };
  27140. Texture.prototype.getReflectionTextureMatrix = function () {
  27141. var _this = this;
  27142. var scene = this.getScene();
  27143. if (!scene) {
  27144. return this._cachedTextureMatrix;
  27145. }
  27146. if (this.uOffset === this._cachedUOffset &&
  27147. this.vOffset === this._cachedVOffset &&
  27148. this.uScale === this._cachedUScale &&
  27149. this.vScale === this._cachedVScale &&
  27150. this.coordinatesMode === this._cachedCoordinatesMode) {
  27151. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27152. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27153. return this._cachedTextureMatrix;
  27154. }
  27155. }
  27156. else {
  27157. return this._cachedTextureMatrix;
  27158. }
  27159. }
  27160. if (!this._cachedTextureMatrix) {
  27161. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27162. }
  27163. if (!this._projectionModeMatrix) {
  27164. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27165. }
  27166. this._cachedUOffset = this.uOffset;
  27167. this._cachedVOffset = this.vOffset;
  27168. this._cachedUScale = this.uScale;
  27169. this._cachedVScale = this.vScale;
  27170. this._cachedCoordinatesMode = this.coordinatesMode;
  27171. switch (this.coordinatesMode) {
  27172. case Texture.PLANAR_MODE:
  27173. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27174. this._cachedTextureMatrix[0] = this.uScale;
  27175. this._cachedTextureMatrix[5] = this.vScale;
  27176. this._cachedTextureMatrix[12] = this.uOffset;
  27177. this._cachedTextureMatrix[13] = this.vOffset;
  27178. break;
  27179. case Texture.PROJECTION_MODE:
  27180. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27181. this._projectionModeMatrix.m[0] = 0.5;
  27182. this._projectionModeMatrix.m[5] = -0.5;
  27183. this._projectionModeMatrix.m[10] = 0.0;
  27184. this._projectionModeMatrix.m[12] = 0.5;
  27185. this._projectionModeMatrix.m[13] = 0.5;
  27186. this._projectionModeMatrix.m[14] = 1.0;
  27187. this._projectionModeMatrix.m[15] = 1.0;
  27188. var projectionMatrix = scene.getProjectionMatrix();
  27189. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27190. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27191. break;
  27192. default:
  27193. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27194. break;
  27195. }
  27196. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27197. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27198. });
  27199. return this._cachedTextureMatrix;
  27200. };
  27201. Texture.prototype.clone = function () {
  27202. var _this = this;
  27203. return BABYLON.SerializationHelper.Clone(function () {
  27204. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27205. }, this);
  27206. };
  27207. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27208. get: function () {
  27209. if (!this._onLoadObservable) {
  27210. this._onLoadObservable = new BABYLON.Observable();
  27211. }
  27212. return this._onLoadObservable;
  27213. },
  27214. enumerable: true,
  27215. configurable: true
  27216. });
  27217. Texture.prototype.serialize = function () {
  27218. var serializationObject = _super.prototype.serialize.call(this);
  27219. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27220. serializationObject.base64String = this._buffer;
  27221. serializationObject.name = serializationObject.name.replace("data:", "");
  27222. }
  27223. return serializationObject;
  27224. };
  27225. Texture.prototype.getClassName = function () {
  27226. return "Texture";
  27227. };
  27228. Texture.prototype.dispose = function () {
  27229. _super.prototype.dispose.call(this);
  27230. if (this.onLoadObservable) {
  27231. this.onLoadObservable.clear();
  27232. this._onLoadObservable = null;
  27233. }
  27234. this._delayedOnLoad = null;
  27235. this._delayedOnError = null;
  27236. };
  27237. // Statics
  27238. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27239. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27240. if (onLoad === void 0) { onLoad = null; }
  27241. if (onError === void 0) { onError = null; }
  27242. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27243. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27244. };
  27245. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27246. if (parsedTexture.customType) {
  27247. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27248. // Update Sampling Mode
  27249. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27250. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27251. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27252. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27253. }
  27254. }
  27255. return parsedCustomTexture;
  27256. }
  27257. if (parsedTexture.isCube) {
  27258. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27259. }
  27260. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27261. return null;
  27262. }
  27263. var texture = BABYLON.SerializationHelper.Parse(function () {
  27264. var generateMipMaps = true;
  27265. if (parsedTexture.noMipmap) {
  27266. generateMipMaps = false;
  27267. }
  27268. if (parsedTexture.mirrorPlane) {
  27269. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27270. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27271. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27272. return mirrorTexture;
  27273. }
  27274. else if (parsedTexture.isRenderTarget) {
  27275. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27276. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27277. return renderTargetTexture;
  27278. }
  27279. else {
  27280. var texture;
  27281. if (parsedTexture.base64String) {
  27282. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27283. }
  27284. else {
  27285. var url = rootUrl + parsedTexture.name;
  27286. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27287. url = parsedTexture.url;
  27288. }
  27289. texture = new Texture(url, scene, !generateMipMaps);
  27290. }
  27291. return texture;
  27292. }
  27293. }, parsedTexture, scene);
  27294. // Update Sampling Mode
  27295. if (parsedTexture.samplingMode) {
  27296. var sampling = parsedTexture.samplingMode;
  27297. if (texture._samplingMode !== sampling) {
  27298. texture.updateSamplingMode(sampling);
  27299. }
  27300. }
  27301. // Animations
  27302. if (parsedTexture.animations) {
  27303. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27304. var parsedAnimation = parsedTexture.animations[animationIndex];
  27305. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27306. }
  27307. }
  27308. return texture;
  27309. };
  27310. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27311. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27312. if (noMipmap === void 0) { noMipmap = false; }
  27313. if (invertY === void 0) { invertY = true; }
  27314. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27315. if (onLoad === void 0) { onLoad = null; }
  27316. if (onError === void 0) { onError = null; }
  27317. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27318. if (name.substr(0, 5) !== "data:") {
  27319. name = "data:" + name;
  27320. }
  27321. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27322. };
  27323. // Constants
  27324. Texture.NEAREST_SAMPLINGMODE = 1;
  27325. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27326. Texture.BILINEAR_SAMPLINGMODE = 2;
  27327. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27328. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27329. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27330. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27331. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27332. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27333. Texture.NEAREST_LINEAR = 7;
  27334. Texture.NEAREST_NEAREST = 8;
  27335. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27336. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27337. Texture.LINEAR_LINEAR = 11;
  27338. Texture.LINEAR_NEAREST = 12;
  27339. Texture.EXPLICIT_MODE = 0;
  27340. Texture.SPHERICAL_MODE = 1;
  27341. Texture.PLANAR_MODE = 2;
  27342. Texture.CUBIC_MODE = 3;
  27343. Texture.PROJECTION_MODE = 4;
  27344. Texture.SKYBOX_MODE = 5;
  27345. Texture.INVCUBIC_MODE = 6;
  27346. Texture.EQUIRECTANGULAR_MODE = 7;
  27347. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27348. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27349. Texture.CLAMP_ADDRESSMODE = 0;
  27350. Texture.WRAP_ADDRESSMODE = 1;
  27351. Texture.MIRROR_ADDRESSMODE = 2;
  27352. /**
  27353. * 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
  27354. */
  27355. Texture.UseSerializedUrlIfAny = false;
  27356. __decorate([
  27357. BABYLON.serialize()
  27358. ], Texture.prototype, "url", void 0);
  27359. __decorate([
  27360. BABYLON.serialize()
  27361. ], Texture.prototype, "uOffset", void 0);
  27362. __decorate([
  27363. BABYLON.serialize()
  27364. ], Texture.prototype, "vOffset", void 0);
  27365. __decorate([
  27366. BABYLON.serialize()
  27367. ], Texture.prototype, "uScale", void 0);
  27368. __decorate([
  27369. BABYLON.serialize()
  27370. ], Texture.prototype, "vScale", void 0);
  27371. __decorate([
  27372. BABYLON.serialize()
  27373. ], Texture.prototype, "uAng", void 0);
  27374. __decorate([
  27375. BABYLON.serialize()
  27376. ], Texture.prototype, "vAng", void 0);
  27377. __decorate([
  27378. BABYLON.serialize()
  27379. ], Texture.prototype, "wAng", void 0);
  27380. __decorate([
  27381. BABYLON.serialize()
  27382. ], Texture.prototype, "isBlocking", null);
  27383. return Texture;
  27384. }(BABYLON.BaseTexture));
  27385. BABYLON.Texture = Texture;
  27386. })(BABYLON || (BABYLON = {}));
  27387. //# sourceMappingURL=babylon.texture.js.map
  27388. var BABYLON;
  27389. (function (BABYLON) {
  27390. var _InstancesBatch = /** @class */ (function () {
  27391. function _InstancesBatch() {
  27392. this.mustReturn = false;
  27393. this.visibleInstances = new Array();
  27394. this.renderSelf = new Array();
  27395. }
  27396. return _InstancesBatch;
  27397. }());
  27398. BABYLON._InstancesBatch = _InstancesBatch;
  27399. var Mesh = /** @class */ (function (_super) {
  27400. __extends(Mesh, _super);
  27401. /**
  27402. * @constructor
  27403. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27404. * @param {Scene} scene The scene to add this mesh to.
  27405. * @param {Node} parent The parent of this mesh, if it has one
  27406. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27407. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27408. * When false, achieved by calling a clone(), also passing False.
  27409. * This will make creation of children, recursive.
  27410. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27411. */
  27412. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27413. if (scene === void 0) { scene = null; }
  27414. if (parent === void 0) { parent = null; }
  27415. if (source === void 0) { source = null; }
  27416. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27417. var _this = _super.call(this, name, scene) || this;
  27418. // Events
  27419. /**
  27420. * An event triggered before rendering the mesh
  27421. * @type {BABYLON.Observable}
  27422. */
  27423. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27424. /**
  27425. * An event triggered after rendering the mesh
  27426. * @type {BABYLON.Observable}
  27427. */
  27428. _this.onAfterRenderObservable = new BABYLON.Observable();
  27429. /**
  27430. * An event triggered before drawing the mesh
  27431. * @type {BABYLON.Observable}
  27432. */
  27433. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27434. // Members
  27435. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27436. _this.instances = new Array();
  27437. _this._LODLevels = new Array();
  27438. _this._visibleInstances = {};
  27439. _this._renderIdForInstances = new Array();
  27440. _this._batchCache = new _InstancesBatch();
  27441. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27442. // Use by builder only to know what orientation were the mesh build in.
  27443. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27444. _this.overrideMaterialSideOrientation = null;
  27445. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27446. // Will be used to save a source mesh reference, If any
  27447. _this._source = null;
  27448. scene = _this.getScene();
  27449. if (source) {
  27450. // Source mesh
  27451. _this._source = source;
  27452. // Geometry
  27453. if (source._geometry) {
  27454. source._geometry.applyToMesh(_this);
  27455. }
  27456. // Deep copy
  27457. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27458. // Metadata
  27459. if (source.metadata && source.metadata.clone) {
  27460. _this.metadata = source.metadata.clone();
  27461. }
  27462. else {
  27463. _this.metadata = source.metadata;
  27464. }
  27465. // Tags
  27466. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27467. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27468. }
  27469. // Parent
  27470. _this.parent = source.parent;
  27471. // Pivot
  27472. _this.setPivotMatrix(source.getPivotMatrix());
  27473. _this.id = name + "." + source.id;
  27474. // Material
  27475. _this.material = source.material;
  27476. var index;
  27477. if (!doNotCloneChildren) {
  27478. // Children
  27479. var directDescendants = source.getDescendants(true);
  27480. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27481. var child = directDescendants[index_1];
  27482. if (child.clone) {
  27483. child.clone(name + "." + child.name, _this);
  27484. }
  27485. }
  27486. }
  27487. // Physics clone
  27488. var physicsEngine = _this.getScene().getPhysicsEngine();
  27489. if (clonePhysicsImpostor && physicsEngine) {
  27490. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27491. if (impostor) {
  27492. _this.physicsImpostor = impostor.clone(_this);
  27493. }
  27494. }
  27495. // Particles
  27496. for (index = 0; index < scene.particleSystems.length; index++) {
  27497. var system = scene.particleSystems[index];
  27498. if (system.emitter === source) {
  27499. system.clone(system.name, _this);
  27500. }
  27501. }
  27502. _this.computeWorldMatrix(true);
  27503. }
  27504. // Parent
  27505. if (parent !== null) {
  27506. _this.parent = parent;
  27507. }
  27508. return _this;
  27509. }
  27510. Object.defineProperty(Mesh, "FRONTSIDE", {
  27511. /**
  27512. * Mesh side orientation : usually the external or front surface
  27513. */
  27514. get: function () {
  27515. return Mesh._FRONTSIDE;
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. Object.defineProperty(Mesh, "BACKSIDE", {
  27521. /**
  27522. * Mesh side orientation : usually the internal or back surface
  27523. */
  27524. get: function () {
  27525. return Mesh._BACKSIDE;
  27526. },
  27527. enumerable: true,
  27528. configurable: true
  27529. });
  27530. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27531. /**
  27532. * Mesh side orientation : both internal and external or front and back surfaces
  27533. */
  27534. get: function () {
  27535. return Mesh._DOUBLESIDE;
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27541. /**
  27542. * Mesh side orientation : by default, `FRONTSIDE`
  27543. */
  27544. get: function () {
  27545. return Mesh._DEFAULTSIDE;
  27546. },
  27547. enumerable: true,
  27548. configurable: true
  27549. });
  27550. Object.defineProperty(Mesh, "NO_CAP", {
  27551. /**
  27552. * Mesh cap setting : no cap
  27553. */
  27554. get: function () {
  27555. return Mesh._NO_CAP;
  27556. },
  27557. enumerable: true,
  27558. configurable: true
  27559. });
  27560. Object.defineProperty(Mesh, "CAP_START", {
  27561. /**
  27562. * Mesh cap setting : one cap at the beginning of the mesh
  27563. */
  27564. get: function () {
  27565. return Mesh._CAP_START;
  27566. },
  27567. enumerable: true,
  27568. configurable: true
  27569. });
  27570. Object.defineProperty(Mesh, "CAP_END", {
  27571. /**
  27572. * Mesh cap setting : one cap at the end of the mesh
  27573. */
  27574. get: function () {
  27575. return Mesh._CAP_END;
  27576. },
  27577. enumerable: true,
  27578. configurable: true
  27579. });
  27580. Object.defineProperty(Mesh, "CAP_ALL", {
  27581. /**
  27582. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27583. */
  27584. get: function () {
  27585. return Mesh._CAP_ALL;
  27586. },
  27587. enumerable: true,
  27588. configurable: true
  27589. });
  27590. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27591. set: function (callback) {
  27592. if (this._onBeforeDrawObserver) {
  27593. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27594. }
  27595. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27596. },
  27597. enumerable: true,
  27598. configurable: true
  27599. });
  27600. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27601. get: function () {
  27602. return this._morphTargetManager;
  27603. },
  27604. set: function (value) {
  27605. if (this._morphTargetManager === value) {
  27606. return;
  27607. }
  27608. this._morphTargetManager = value;
  27609. this._syncGeometryWithMorphTargetManager();
  27610. },
  27611. enumerable: true,
  27612. configurable: true
  27613. });
  27614. Object.defineProperty(Mesh.prototype, "source", {
  27615. get: function () {
  27616. return this._source;
  27617. },
  27618. enumerable: true,
  27619. configurable: true
  27620. });
  27621. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27622. get: function () {
  27623. return this._unIndexed;
  27624. },
  27625. set: function (value) {
  27626. if (this._unIndexed !== value) {
  27627. this._unIndexed = value;
  27628. this._markSubMeshesAsAttributesDirty();
  27629. }
  27630. },
  27631. enumerable: true,
  27632. configurable: true
  27633. });
  27634. // Methods
  27635. /**
  27636. * Returns the string "Mesh".
  27637. */
  27638. Mesh.prototype.getClassName = function () {
  27639. return "Mesh";
  27640. };
  27641. /**
  27642. * Returns a string.
  27643. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27644. */
  27645. Mesh.prototype.toString = function (fullDetails) {
  27646. var ret = _super.prototype.toString.call(this, fullDetails);
  27647. ret += ", n vertices: " + this.getTotalVertices();
  27648. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27649. if (this.animations) {
  27650. for (var i = 0; i < this.animations.length; i++) {
  27651. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27652. }
  27653. }
  27654. if (fullDetails) {
  27655. if (this._geometry) {
  27656. var ib = this.getIndices();
  27657. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27658. if (vb && ib) {
  27659. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27660. }
  27661. }
  27662. else {
  27663. ret += ", flat shading: UNKNOWN";
  27664. }
  27665. }
  27666. return ret;
  27667. };
  27668. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27669. /**
  27670. * True if the mesh has some Levels Of Details (LOD).
  27671. * Returns a boolean.
  27672. */
  27673. get: function () {
  27674. return this._LODLevels.length > 0;
  27675. },
  27676. enumerable: true,
  27677. configurable: true
  27678. });
  27679. /**
  27680. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27681. * @returns an array of {BABYLON.MeshLODLevel}
  27682. */
  27683. Mesh.prototype.getLODLevels = function () {
  27684. return this._LODLevels;
  27685. };
  27686. Mesh.prototype._sortLODLevels = function () {
  27687. this._LODLevels.sort(function (a, b) {
  27688. if (a.distance < b.distance) {
  27689. return 1;
  27690. }
  27691. if (a.distance > b.distance) {
  27692. return -1;
  27693. }
  27694. return 0;
  27695. });
  27696. };
  27697. /**
  27698. * Add a mesh as LOD level triggered at the given distance.
  27699. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27700. * @param {number} distance The distance from the center of the object to show this level
  27701. * @param {Mesh} mesh The mesh to be added as LOD level
  27702. * @return {Mesh} This mesh (for chaining)
  27703. */
  27704. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27705. if (mesh && mesh._masterMesh) {
  27706. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27707. return this;
  27708. }
  27709. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27710. this._LODLevels.push(level);
  27711. if (mesh) {
  27712. mesh._masterMesh = this;
  27713. }
  27714. this._sortLODLevels();
  27715. return this;
  27716. };
  27717. /**
  27718. * Returns the LOD level mesh at the passed distance or null if not found.
  27719. * It is related to the method `addLODLevel(distance, mesh)`.
  27720. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27721. * Returns an object Mesh or `null`.
  27722. */
  27723. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27724. for (var index = 0; index < this._LODLevels.length; index++) {
  27725. var level = this._LODLevels[index];
  27726. if (level.distance === distance) {
  27727. return level.mesh;
  27728. }
  27729. }
  27730. return null;
  27731. };
  27732. /**
  27733. * Remove a mesh from the LOD array
  27734. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27735. * @param {Mesh} mesh The mesh to be removed.
  27736. * @return {Mesh} This mesh (for chaining)
  27737. */
  27738. Mesh.prototype.removeLODLevel = function (mesh) {
  27739. for (var index = 0; index < this._LODLevels.length; index++) {
  27740. if (this._LODLevels[index].mesh === mesh) {
  27741. this._LODLevels.splice(index, 1);
  27742. if (mesh) {
  27743. mesh._masterMesh = null;
  27744. }
  27745. }
  27746. }
  27747. this._sortLODLevels();
  27748. return this;
  27749. };
  27750. /**
  27751. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27752. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27753. */
  27754. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27755. if (!this._LODLevels || this._LODLevels.length === 0) {
  27756. return this;
  27757. }
  27758. var bSphere;
  27759. if (boundingSphere) {
  27760. bSphere = boundingSphere;
  27761. }
  27762. else {
  27763. var boundingInfo = this.getBoundingInfo();
  27764. bSphere = boundingInfo.boundingSphere;
  27765. }
  27766. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27767. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27768. if (this.onLODLevelSelection) {
  27769. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27770. }
  27771. return this;
  27772. }
  27773. for (var index = 0; index < this._LODLevels.length; index++) {
  27774. var level = this._LODLevels[index];
  27775. if (level.distance < distanceToCamera) {
  27776. if (level.mesh) {
  27777. level.mesh._preActivate();
  27778. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27779. }
  27780. if (this.onLODLevelSelection) {
  27781. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27782. }
  27783. return level.mesh;
  27784. }
  27785. }
  27786. if (this.onLODLevelSelection) {
  27787. this.onLODLevelSelection(distanceToCamera, this, this);
  27788. }
  27789. return this;
  27790. };
  27791. Object.defineProperty(Mesh.prototype, "geometry", {
  27792. /**
  27793. * Returns the mesh internal Geometry object.
  27794. */
  27795. get: function () {
  27796. return this._geometry;
  27797. },
  27798. enumerable: true,
  27799. configurable: true
  27800. });
  27801. /**
  27802. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27803. */
  27804. Mesh.prototype.getTotalVertices = function () {
  27805. if (this._geometry === null || this._geometry === undefined) {
  27806. return 0;
  27807. }
  27808. return this._geometry.getTotalVertices();
  27809. };
  27810. /**
  27811. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27812. * 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.
  27813. * You can force the copy with forceCopy === true
  27814. * Returns null if the mesh has no geometry or no vertex buffer.
  27815. * Possible `kind` values :
  27816. * - BABYLON.VertexBuffer.PositionKind
  27817. * - BABYLON.VertexBuffer.UVKind
  27818. * - BABYLON.VertexBuffer.UV2Kind
  27819. * - BABYLON.VertexBuffer.UV3Kind
  27820. * - BABYLON.VertexBuffer.UV4Kind
  27821. * - BABYLON.VertexBuffer.UV5Kind
  27822. * - BABYLON.VertexBuffer.UV6Kind
  27823. * - BABYLON.VertexBuffer.ColorKind
  27824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27828. */
  27829. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27830. if (!this._geometry) {
  27831. return null;
  27832. }
  27833. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27834. };
  27835. /**
  27836. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27837. * Returns `null` if the mesh has no geometry.
  27838. * Possible `kind` values :
  27839. * - BABYLON.VertexBuffer.PositionKind
  27840. * - BABYLON.VertexBuffer.UVKind
  27841. * - BABYLON.VertexBuffer.UV2Kind
  27842. * - BABYLON.VertexBuffer.UV3Kind
  27843. * - BABYLON.VertexBuffer.UV4Kind
  27844. * - BABYLON.VertexBuffer.UV5Kind
  27845. * - BABYLON.VertexBuffer.UV6Kind
  27846. * - BABYLON.VertexBuffer.ColorKind
  27847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27851. */
  27852. Mesh.prototype.getVertexBuffer = function (kind) {
  27853. if (!this._geometry) {
  27854. return null;
  27855. }
  27856. return this._geometry.getVertexBuffer(kind);
  27857. };
  27858. /**
  27859. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27860. * Possible `kind` values :
  27861. * - BABYLON.VertexBuffer.PositionKind
  27862. * - BABYLON.VertexBuffer.UVKind
  27863. * - BABYLON.VertexBuffer.UV2Kind
  27864. * - BABYLON.VertexBuffer.UV3Kind
  27865. * - BABYLON.VertexBuffer.UV4Kind
  27866. * - BABYLON.VertexBuffer.UV5Kind
  27867. * - BABYLON.VertexBuffer.UV6Kind
  27868. * - BABYLON.VertexBuffer.ColorKind
  27869. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27870. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27871. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27872. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27873. */
  27874. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27875. if (!this._geometry) {
  27876. if (this._delayInfo) {
  27877. return this._delayInfo.indexOf(kind) !== -1;
  27878. }
  27879. return false;
  27880. }
  27881. return this._geometry.isVerticesDataPresent(kind);
  27882. };
  27883. /**
  27884. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27885. * Possible `kind` values :
  27886. * - BABYLON.VertexBuffer.PositionKind
  27887. * - BABYLON.VertexBuffer.UVKind
  27888. * - BABYLON.VertexBuffer.UV2Kind
  27889. * - BABYLON.VertexBuffer.UV3Kind
  27890. * - BABYLON.VertexBuffer.UV4Kind
  27891. * - BABYLON.VertexBuffer.UV5Kind
  27892. * - BABYLON.VertexBuffer.UV6Kind
  27893. * - BABYLON.VertexBuffer.ColorKind
  27894. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27895. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27896. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27897. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27898. */
  27899. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27900. if (!this._geometry) {
  27901. if (this._delayInfo) {
  27902. return this._delayInfo.indexOf(kind) !== -1;
  27903. }
  27904. return false;
  27905. }
  27906. return this._geometry.isVertexBufferUpdatable(kind);
  27907. };
  27908. /**
  27909. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27910. * Possible `kind` values :
  27911. * - BABYLON.VertexBuffer.PositionKind
  27912. * - BABYLON.VertexBuffer.UVKind
  27913. * - BABYLON.VertexBuffer.UV2Kind
  27914. * - BABYLON.VertexBuffer.UV3Kind
  27915. * - BABYLON.VertexBuffer.UV4Kind
  27916. * - BABYLON.VertexBuffer.UV5Kind
  27917. * - BABYLON.VertexBuffer.UV6Kind
  27918. * - BABYLON.VertexBuffer.ColorKind
  27919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27923. */
  27924. Mesh.prototype.getVerticesDataKinds = function () {
  27925. if (!this._geometry) {
  27926. var result = new Array();
  27927. if (this._delayInfo) {
  27928. this._delayInfo.forEach(function (kind, index, array) {
  27929. result.push(kind);
  27930. });
  27931. }
  27932. return result;
  27933. }
  27934. return this._geometry.getVerticesDataKinds();
  27935. };
  27936. /**
  27937. * Returns a positive integer : the total number of indices in this mesh geometry.
  27938. * Returns zero if the mesh has no geometry.
  27939. */
  27940. Mesh.prototype.getTotalIndices = function () {
  27941. if (!this._geometry) {
  27942. return 0;
  27943. }
  27944. return this._geometry.getTotalIndices();
  27945. };
  27946. /**
  27947. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27948. * 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.
  27949. * Returns an empty array if the mesh has no geometry.
  27950. */
  27951. Mesh.prototype.getIndices = function (copyWhenShared) {
  27952. if (!this._geometry) {
  27953. return [];
  27954. }
  27955. return this._geometry.getIndices(copyWhenShared);
  27956. };
  27957. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27958. get: function () {
  27959. return this._masterMesh !== null && this._masterMesh !== undefined;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. /**
  27965. * Determine if the current mesh is ready to be rendered
  27966. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27967. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27968. * @returns true if all associated assets are ready (material, textures, shaders)
  27969. */
  27970. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27971. if (completeCheck === void 0) { completeCheck = false; }
  27972. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27973. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27974. return false;
  27975. }
  27976. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27977. return false;
  27978. }
  27979. if (!this.subMeshes || this.subMeshes.length === 0) {
  27980. return true;
  27981. }
  27982. if (!completeCheck) {
  27983. return true;
  27984. }
  27985. var engine = this.getEngine();
  27986. var scene = this.getScene();
  27987. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27988. this.computeWorldMatrix();
  27989. var mat = this.material || scene.defaultMaterial;
  27990. if (mat) {
  27991. if (mat.storeEffectOnSubMeshes) {
  27992. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27993. var subMesh = _a[_i];
  27994. var effectiveMaterial = subMesh.getMaterial();
  27995. if (effectiveMaterial) {
  27996. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27997. return false;
  27998. }
  27999. }
  28000. }
  28001. }
  28002. else {
  28003. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28004. return false;
  28005. }
  28006. }
  28007. }
  28008. // Shadows
  28009. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28010. var light = _c[_b];
  28011. var generator = light.getShadowGenerator();
  28012. if (generator) {
  28013. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28014. var subMesh = _e[_d];
  28015. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28016. return false;
  28017. }
  28018. }
  28019. }
  28020. }
  28021. // LOD
  28022. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28023. var lod = _g[_f];
  28024. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28025. return false;
  28026. }
  28027. }
  28028. return true;
  28029. };
  28030. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28031. /**
  28032. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28033. * This property is pertinent only for updatable parametric shapes.
  28034. */
  28035. get: function () {
  28036. return this._areNormalsFrozen;
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. /**
  28042. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28043. * It has no effect at all on other shapes.
  28044. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28045. * Returns the Mesh.
  28046. */
  28047. Mesh.prototype.freezeNormals = function () {
  28048. this._areNormalsFrozen = true;
  28049. return this;
  28050. };
  28051. /**
  28052. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28053. * It has no effect at all on other shapes.
  28054. * It reactivates the mesh normals computation if it was previously frozen.
  28055. * Returns the Mesh.
  28056. */
  28057. Mesh.prototype.unfreezeNormals = function () {
  28058. this._areNormalsFrozen = false;
  28059. return this;
  28060. };
  28061. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28062. /**
  28063. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28064. */
  28065. set: function (count) {
  28066. this._overridenInstanceCount = count;
  28067. },
  28068. enumerable: true,
  28069. configurable: true
  28070. });
  28071. // Methods
  28072. Mesh.prototype._preActivate = function () {
  28073. var sceneRenderId = this.getScene().getRenderId();
  28074. if (this._preActivateId === sceneRenderId) {
  28075. return this;
  28076. }
  28077. this._preActivateId = sceneRenderId;
  28078. this._visibleInstances = null;
  28079. return this;
  28080. };
  28081. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28082. if (this._visibleInstances) {
  28083. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28084. }
  28085. return this;
  28086. };
  28087. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28088. if (!this._visibleInstances) {
  28089. this._visibleInstances = {};
  28090. this._visibleInstances.defaultRenderId = renderId;
  28091. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28092. }
  28093. if (!this._visibleInstances[renderId]) {
  28094. this._visibleInstances[renderId] = new Array();
  28095. }
  28096. this._visibleInstances[renderId].push(instance);
  28097. return this;
  28098. };
  28099. /**
  28100. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28101. * This means the mesh underlying bounding box and sphere are recomputed.
  28102. * Returns the Mesh.
  28103. */
  28104. Mesh.prototype.refreshBoundingInfo = function () {
  28105. return this._refreshBoundingInfo(false);
  28106. };
  28107. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28108. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28109. return this;
  28110. }
  28111. var data = this._getPositionData(applySkeleton);
  28112. if (data) {
  28113. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28114. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28115. }
  28116. if (this.subMeshes) {
  28117. for (var index = 0; index < this.subMeshes.length; index++) {
  28118. this.subMeshes[index].refreshBoundingInfo();
  28119. }
  28120. }
  28121. this._updateBoundingInfo();
  28122. return this;
  28123. };
  28124. Mesh.prototype._getPositionData = function (applySkeleton) {
  28125. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28126. if (data && applySkeleton && this.skeleton) {
  28127. data = BABYLON.Tools.Slice(data);
  28128. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28129. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28130. if (matricesWeightsData && matricesIndicesData) {
  28131. var needExtras = this.numBoneInfluencers > 4;
  28132. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28133. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28134. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28135. var tempVector = BABYLON.Tmp.Vector3[0];
  28136. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28137. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28138. var matWeightIdx = 0;
  28139. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28140. finalMatrix.reset();
  28141. var inf;
  28142. var weight;
  28143. for (inf = 0; inf < 4; inf++) {
  28144. weight = matricesWeightsData[matWeightIdx + inf];
  28145. if (weight <= 0)
  28146. break;
  28147. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28148. finalMatrix.addToSelf(tempMatrix);
  28149. }
  28150. if (needExtras) {
  28151. for (inf = 0; inf < 4; inf++) {
  28152. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28153. if (weight <= 0)
  28154. break;
  28155. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28156. finalMatrix.addToSelf(tempMatrix);
  28157. }
  28158. }
  28159. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28160. tempVector.toArray(data, index);
  28161. }
  28162. }
  28163. }
  28164. return data;
  28165. };
  28166. Mesh.prototype._createGlobalSubMesh = function (force) {
  28167. var totalVertices = this.getTotalVertices();
  28168. if (!totalVertices || !this.getIndices()) {
  28169. return null;
  28170. }
  28171. // Check if we need to recreate the submeshes
  28172. if (this.subMeshes && this.subMeshes.length > 0) {
  28173. var ib = this.getIndices();
  28174. if (!ib) {
  28175. return null;
  28176. }
  28177. var totalIndices = ib.length;
  28178. var needToRecreate = false;
  28179. if (force) {
  28180. needToRecreate = true;
  28181. }
  28182. else {
  28183. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28184. var submesh = _a[_i];
  28185. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28186. needToRecreate = true;
  28187. break;
  28188. }
  28189. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28190. needToRecreate = true;
  28191. break;
  28192. }
  28193. }
  28194. }
  28195. if (!needToRecreate) {
  28196. return this.subMeshes[0];
  28197. }
  28198. }
  28199. this.releaseSubMeshes();
  28200. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28201. };
  28202. Mesh.prototype.subdivide = function (count) {
  28203. if (count < 1) {
  28204. return;
  28205. }
  28206. var totalIndices = this.getTotalIndices();
  28207. var subdivisionSize = (totalIndices / count) | 0;
  28208. var offset = 0;
  28209. // Ensure that subdivisionSize is a multiple of 3
  28210. while (subdivisionSize % 3 !== 0) {
  28211. subdivisionSize++;
  28212. }
  28213. this.releaseSubMeshes();
  28214. for (var index = 0; index < count; index++) {
  28215. if (offset >= totalIndices) {
  28216. break;
  28217. }
  28218. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28219. offset += subdivisionSize;
  28220. }
  28221. this.synchronizeInstances();
  28222. };
  28223. /**
  28224. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28225. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28226. * The `data` are either a numeric array either a Float32Array.
  28227. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28228. * 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).
  28229. * Note that a new underlying VertexBuffer object is created each call.
  28230. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28231. *
  28232. * Possible `kind` values :
  28233. * - BABYLON.VertexBuffer.PositionKind
  28234. * - BABYLON.VertexBuffer.UVKind
  28235. * - BABYLON.VertexBuffer.UV2Kind
  28236. * - BABYLON.VertexBuffer.UV3Kind
  28237. * - BABYLON.VertexBuffer.UV4Kind
  28238. * - BABYLON.VertexBuffer.UV5Kind
  28239. * - BABYLON.VertexBuffer.UV6Kind
  28240. * - BABYLON.VertexBuffer.ColorKind
  28241. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28243. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28245. *
  28246. * Returns the Mesh.
  28247. */
  28248. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28249. if (updatable === void 0) { updatable = false; }
  28250. if (!this._geometry) {
  28251. var vertexData = new BABYLON.VertexData();
  28252. vertexData.set(data, kind);
  28253. var scene = this.getScene();
  28254. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28255. }
  28256. else {
  28257. this._geometry.setVerticesData(kind, data, updatable, stride);
  28258. }
  28259. return this;
  28260. };
  28261. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28262. if (updatable === void 0) { updatable = true; }
  28263. var vb = this.getVertexBuffer(kind);
  28264. if (!vb || vb.isUpdatable() === updatable) {
  28265. return;
  28266. }
  28267. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28268. };
  28269. /**
  28270. * Sets the mesh VertexBuffer.
  28271. * Returns the Mesh.
  28272. */
  28273. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28274. if (!this._geometry) {
  28275. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28276. }
  28277. this._geometry.setVerticesBuffer(buffer);
  28278. return this;
  28279. };
  28280. /**
  28281. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28282. * If the mesh has no geometry, it is simply returned as it is.
  28283. * The `data` are either a numeric array either a Float32Array.
  28284. * No new underlying VertexBuffer object is created.
  28285. * 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.
  28286. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28287. *
  28288. * Possible `kind` values :
  28289. * - BABYLON.VertexBuffer.PositionKind
  28290. * - BABYLON.VertexBuffer.UVKind
  28291. * - BABYLON.VertexBuffer.UV2Kind
  28292. * - BABYLON.VertexBuffer.UV3Kind
  28293. * - BABYLON.VertexBuffer.UV4Kind
  28294. * - BABYLON.VertexBuffer.UV5Kind
  28295. * - BABYLON.VertexBuffer.UV6Kind
  28296. * - BABYLON.VertexBuffer.ColorKind
  28297. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28298. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28299. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28300. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28301. *
  28302. * Returns the Mesh.
  28303. */
  28304. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28305. if (!this._geometry) {
  28306. return this;
  28307. }
  28308. if (!makeItUnique) {
  28309. this._geometry.updateVerticesData(kind, data, updateExtends);
  28310. }
  28311. else {
  28312. this.makeGeometryUnique();
  28313. this.updateVerticesData(kind, data, updateExtends, false);
  28314. }
  28315. return this;
  28316. };
  28317. /**
  28318. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28319. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28320. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28321. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28322. * Returns the Mesh.
  28323. */
  28324. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28325. if (computeNormals === void 0) { computeNormals = true; }
  28326. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28327. if (!positions) {
  28328. return this;
  28329. }
  28330. positionFunction(positions);
  28331. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28332. if (computeNormals) {
  28333. var indices = this.getIndices();
  28334. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28335. if (!normals) {
  28336. return this;
  28337. }
  28338. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28339. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28340. }
  28341. return this;
  28342. };
  28343. /**
  28344. * Creates a un-shared specific occurence of the geometry for the mesh.
  28345. * Returns the Mesh.
  28346. */
  28347. Mesh.prototype.makeGeometryUnique = function () {
  28348. if (!this._geometry) {
  28349. return this;
  28350. }
  28351. var oldGeometry = this._geometry;
  28352. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28353. oldGeometry.releaseForMesh(this, true);
  28354. geometry.applyToMesh(this);
  28355. return this;
  28356. };
  28357. /**
  28358. * Sets the mesh indices.
  28359. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28360. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28361. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28362. * This method creates a new index buffer each call.
  28363. * Returns the Mesh.
  28364. */
  28365. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28366. if (totalVertices === void 0) { totalVertices = null; }
  28367. if (updatable === void 0) { updatable = false; }
  28368. if (!this._geometry) {
  28369. var vertexData = new BABYLON.VertexData();
  28370. vertexData.indices = indices;
  28371. var scene = this.getScene();
  28372. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28373. }
  28374. else {
  28375. this._geometry.setIndices(indices, totalVertices, updatable);
  28376. }
  28377. return this;
  28378. };
  28379. /**
  28380. * Update the current index buffer
  28381. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28382. * Returns the Mesh.
  28383. */
  28384. Mesh.prototype.updateIndices = function (indices, offset) {
  28385. if (!this._geometry) {
  28386. return this;
  28387. }
  28388. this._geometry.updateIndices(indices, offset);
  28389. return this;
  28390. };
  28391. /**
  28392. * Invert the geometry to move from a right handed system to a left handed one.
  28393. * Returns the Mesh.
  28394. */
  28395. Mesh.prototype.toLeftHanded = function () {
  28396. if (!this._geometry) {
  28397. return this;
  28398. }
  28399. this._geometry.toLeftHanded();
  28400. return this;
  28401. };
  28402. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28403. if (!this._geometry) {
  28404. return this;
  28405. }
  28406. var engine = this.getScene().getEngine();
  28407. // Wireframe
  28408. var indexToBind;
  28409. if (this._unIndexed) {
  28410. indexToBind = null;
  28411. }
  28412. else {
  28413. switch (fillMode) {
  28414. case BABYLON.Material.PointFillMode:
  28415. indexToBind = null;
  28416. break;
  28417. case BABYLON.Material.WireFrameFillMode:
  28418. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28419. break;
  28420. default:
  28421. case BABYLON.Material.TriangleFillMode:
  28422. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28423. break;
  28424. }
  28425. }
  28426. // VBOs
  28427. this._geometry._bind(effect, indexToBind);
  28428. return this;
  28429. };
  28430. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28431. if (alternate === void 0) { alternate = false; }
  28432. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28433. return this;
  28434. }
  28435. this.onBeforeDrawObservable.notifyObservers(this);
  28436. var scene = this.getScene();
  28437. var engine = scene.getEngine();
  28438. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28439. // or triangles as points
  28440. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28441. }
  28442. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28443. // Triangles as wireframe
  28444. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28445. }
  28446. else {
  28447. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28448. }
  28449. if (scene._isAlternateRenderingEnabled && !alternate) {
  28450. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28451. if (!effect || !scene.activeCamera) {
  28452. return this;
  28453. }
  28454. scene._switchToAlternateCameraConfiguration(true);
  28455. this._effectiveMaterial.bindView(effect);
  28456. this._effectiveMaterial.bindViewProjection(effect);
  28457. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28458. this._draw(subMesh, fillMode, instancesCount, true);
  28459. engine.setViewport(scene.activeCamera.viewport);
  28460. scene._switchToAlternateCameraConfiguration(false);
  28461. this._effectiveMaterial.bindView(effect);
  28462. this._effectiveMaterial.bindViewProjection(effect);
  28463. }
  28464. return this;
  28465. };
  28466. /**
  28467. * Registers for this mesh a javascript function called just before the rendering process.
  28468. * This function is passed the current mesh.
  28469. * Return the Mesh.
  28470. */
  28471. Mesh.prototype.registerBeforeRender = function (func) {
  28472. this.onBeforeRenderObservable.add(func);
  28473. return this;
  28474. };
  28475. /**
  28476. * Disposes a previously registered javascript function called before the rendering.
  28477. * This function is passed the current mesh.
  28478. * Returns the Mesh.
  28479. */
  28480. Mesh.prototype.unregisterBeforeRender = function (func) {
  28481. this.onBeforeRenderObservable.removeCallback(func);
  28482. return this;
  28483. };
  28484. /**
  28485. * Registers for this mesh a javascript function called just after the rendering is complete.
  28486. * This function is passed the current mesh.
  28487. * Returns the Mesh.
  28488. */
  28489. Mesh.prototype.registerAfterRender = function (func) {
  28490. this.onAfterRenderObservable.add(func);
  28491. return this;
  28492. };
  28493. /**
  28494. * Disposes a previously registered javascript function called after the rendering.
  28495. * This function is passed the current mesh.
  28496. * Return the Mesh.
  28497. */
  28498. Mesh.prototype.unregisterAfterRender = function (func) {
  28499. this.onAfterRenderObservable.removeCallback(func);
  28500. return this;
  28501. };
  28502. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28503. var scene = this.getScene();
  28504. this._batchCache.mustReturn = false;
  28505. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28506. this._batchCache.visibleInstances[subMeshId] = null;
  28507. if (this._visibleInstances) {
  28508. var currentRenderId = scene.getRenderId();
  28509. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28510. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28511. var selfRenderId = this._renderId;
  28512. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28513. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28514. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28515. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28516. }
  28517. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28518. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28519. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28520. this._batchCache.mustReturn = true;
  28521. return this._batchCache;
  28522. }
  28523. if (currentRenderId !== selfRenderId) {
  28524. this._batchCache.renderSelf[subMeshId] = false;
  28525. }
  28526. }
  28527. this._renderIdForInstances[subMeshId] = currentRenderId;
  28528. }
  28529. return this._batchCache;
  28530. };
  28531. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28532. var visibleInstances = batch.visibleInstances[subMesh._id];
  28533. if (!visibleInstances) {
  28534. return this;
  28535. }
  28536. var matricesCount = visibleInstances.length + 1;
  28537. var bufferSize = matricesCount * 16 * 4;
  28538. var currentInstancesBufferSize = this._instancesBufferSize;
  28539. var instancesBuffer = this._instancesBuffer;
  28540. while (this._instancesBufferSize < bufferSize) {
  28541. this._instancesBufferSize *= 2;
  28542. }
  28543. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28544. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28545. }
  28546. var offset = 0;
  28547. var instancesCount = 0;
  28548. var world = this.getWorldMatrix();
  28549. if (batch.renderSelf[subMesh._id]) {
  28550. world.copyToArray(this._instancesData, offset);
  28551. offset += 16;
  28552. instancesCount++;
  28553. }
  28554. if (visibleInstances) {
  28555. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28556. var instance = visibleInstances[instanceIndex];
  28557. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28558. offset += 16;
  28559. instancesCount++;
  28560. }
  28561. }
  28562. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28563. if (instancesBuffer) {
  28564. instancesBuffer.dispose();
  28565. }
  28566. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28567. this._instancesBuffer = instancesBuffer;
  28568. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28569. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28570. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28571. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28572. }
  28573. else {
  28574. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28575. }
  28576. this._bind(subMesh, effect, fillMode);
  28577. this._draw(subMesh, fillMode, instancesCount);
  28578. engine.unbindInstanceAttributes();
  28579. return this;
  28580. };
  28581. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28582. var scene = this.getScene();
  28583. var engine = scene.getEngine();
  28584. if (hardwareInstancedRendering) {
  28585. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28586. }
  28587. else {
  28588. if (batch.renderSelf[subMesh._id]) {
  28589. // Draw
  28590. if (onBeforeDraw) {
  28591. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28592. }
  28593. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28594. }
  28595. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28596. if (visibleInstancesForSubMesh) {
  28597. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28598. var instance = visibleInstancesForSubMesh[instanceIndex];
  28599. // World
  28600. var world = instance.getWorldMatrix();
  28601. if (onBeforeDraw) {
  28602. onBeforeDraw(true, world, effectiveMaterial);
  28603. }
  28604. // Draw
  28605. this._draw(subMesh, fillMode);
  28606. }
  28607. }
  28608. }
  28609. return this;
  28610. };
  28611. /**
  28612. * Triggers the draw call for the mesh.
  28613. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28614. * Returns the Mesh.
  28615. */
  28616. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28617. this.checkOcclusionQuery();
  28618. if (this._isOccluded) {
  28619. return this;
  28620. }
  28621. var scene = this.getScene();
  28622. // Managing instances
  28623. var batch = this._getInstancesRenderList(subMesh._id);
  28624. if (batch.mustReturn) {
  28625. return this;
  28626. }
  28627. // Checking geometry state
  28628. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28629. return this;
  28630. }
  28631. this.onBeforeRenderObservable.notifyObservers(this);
  28632. var engine = scene.getEngine();
  28633. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28634. // Material
  28635. var material = subMesh.getMaterial();
  28636. if (!material) {
  28637. return this;
  28638. }
  28639. this._effectiveMaterial = material;
  28640. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28641. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28642. return this;
  28643. }
  28644. }
  28645. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28646. return this;
  28647. }
  28648. // Alpha mode
  28649. if (enableAlphaMode) {
  28650. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28651. }
  28652. // Outline - step 1
  28653. var savedDepthWrite = engine.getDepthWrite();
  28654. if (this.renderOutline) {
  28655. engine.setDepthWrite(false);
  28656. scene.getOutlineRenderer().render(subMesh, batch);
  28657. engine.setDepthWrite(savedDepthWrite);
  28658. }
  28659. var effect;
  28660. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28661. effect = subMesh.effect;
  28662. }
  28663. else {
  28664. effect = this._effectiveMaterial.getEffect();
  28665. }
  28666. if (!effect) {
  28667. return this;
  28668. }
  28669. var sideOrientation = this.overrideMaterialSideOrientation;
  28670. if (sideOrientation == null) {
  28671. sideOrientation = this._effectiveMaterial.sideOrientation;
  28672. if (this._getWorldMatrixDeterminant() < 0) {
  28673. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28674. }
  28675. }
  28676. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28677. if (this._effectiveMaterial.forceDepthWrite) {
  28678. engine.setDepthWrite(true);
  28679. }
  28680. // Bind
  28681. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28682. if (!hardwareInstancedRendering) {
  28683. this._bind(subMesh, effect, fillMode);
  28684. }
  28685. var world = this.getWorldMatrix();
  28686. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28687. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28688. }
  28689. else {
  28690. this._effectiveMaterial.bind(world, this);
  28691. }
  28692. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28693. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28694. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28695. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28696. }
  28697. // Draw
  28698. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28699. // Unbind
  28700. this._effectiveMaterial.unbind();
  28701. // Outline - step 2
  28702. if (this.renderOutline && savedDepthWrite) {
  28703. engine.setDepthWrite(true);
  28704. engine.setColorWrite(false);
  28705. scene.getOutlineRenderer().render(subMesh, batch);
  28706. engine.setColorWrite(true);
  28707. }
  28708. // Overlay
  28709. if (this.renderOverlay) {
  28710. var currentMode = engine.getAlphaMode();
  28711. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28712. scene.getOutlineRenderer().render(subMesh, batch, true);
  28713. engine.setAlphaMode(currentMode);
  28714. }
  28715. this.onAfterRenderObservable.notifyObservers(this);
  28716. return this;
  28717. };
  28718. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28719. if (isInstance && effectiveMaterial) {
  28720. effectiveMaterial.bindOnlyWorldMatrix(world);
  28721. }
  28722. };
  28723. /**
  28724. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28725. */
  28726. Mesh.prototype.getEmittedParticleSystems = function () {
  28727. var results = new Array();
  28728. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28729. var particleSystem = this.getScene().particleSystems[index];
  28730. if (particleSystem.emitter === this) {
  28731. results.push(particleSystem);
  28732. }
  28733. }
  28734. return results;
  28735. };
  28736. /**
  28737. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28738. */
  28739. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28740. var results = new Array();
  28741. var descendants = this.getDescendants();
  28742. descendants.push(this);
  28743. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28744. var particleSystem = this.getScene().particleSystems[index];
  28745. var emitter = particleSystem.emitter;
  28746. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28747. results.push(particleSystem);
  28748. }
  28749. }
  28750. return results;
  28751. };
  28752. Mesh.prototype._checkDelayState = function () {
  28753. var scene = this.getScene();
  28754. if (this._geometry) {
  28755. this._geometry.load(scene);
  28756. }
  28757. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28759. this._queueLoad(scene);
  28760. }
  28761. return this;
  28762. };
  28763. Mesh.prototype._queueLoad = function (scene) {
  28764. var _this = this;
  28765. scene._addPendingData(this);
  28766. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28767. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28768. if (data instanceof ArrayBuffer) {
  28769. _this._delayLoadingFunction(data, _this);
  28770. }
  28771. else {
  28772. _this._delayLoadingFunction(JSON.parse(data), _this);
  28773. }
  28774. _this.instances.forEach(function (instance) {
  28775. instance._syncSubMeshes();
  28776. });
  28777. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28778. scene._removePendingData(_this);
  28779. }, function () { }, scene.database, getBinaryData);
  28780. return this;
  28781. };
  28782. /**
  28783. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28784. */
  28785. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28786. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28787. return false;
  28788. }
  28789. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28790. return false;
  28791. }
  28792. this._checkDelayState();
  28793. return true;
  28794. };
  28795. /**
  28796. * Sets the mesh material by the material or multiMaterial `id` property.
  28797. * The material `id` is a string identifying the material or the multiMaterial.
  28798. * This method returns the Mesh.
  28799. */
  28800. Mesh.prototype.setMaterialByID = function (id) {
  28801. var materials = this.getScene().materials;
  28802. var index;
  28803. for (index = materials.length - 1; index > -1; index--) {
  28804. if (materials[index].id === id) {
  28805. this.material = materials[index];
  28806. return this;
  28807. }
  28808. }
  28809. // Multi
  28810. var multiMaterials = this.getScene().multiMaterials;
  28811. for (index = multiMaterials.length - 1; index > -1; index--) {
  28812. if (multiMaterials[index].id === id) {
  28813. this.material = multiMaterials[index];
  28814. return this;
  28815. }
  28816. }
  28817. return this;
  28818. };
  28819. /**
  28820. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28821. */
  28822. Mesh.prototype.getAnimatables = function () {
  28823. var results = new Array();
  28824. if (this.material) {
  28825. results.push(this.material);
  28826. }
  28827. if (this.skeleton) {
  28828. results.push(this.skeleton);
  28829. }
  28830. return results;
  28831. };
  28832. /**
  28833. * Modifies the mesh geometry according to the passed transformation matrix.
  28834. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28835. * The mesh normals are modified accordingly the same transformation.
  28836. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28837. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28838. * Returns the Mesh.
  28839. */
  28840. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28841. // Position
  28842. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28843. return this;
  28844. }
  28845. var submeshes = this.subMeshes.splice(0);
  28846. this._resetPointsArrayCache();
  28847. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28848. var temp = new Array();
  28849. var index;
  28850. for (index = 0; index < data.length; index += 3) {
  28851. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28852. }
  28853. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28854. // Normals
  28855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28856. return this;
  28857. }
  28858. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28859. temp = [];
  28860. for (index = 0; index < data.length; index += 3) {
  28861. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28862. }
  28863. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28864. // flip faces?
  28865. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28866. this.flipFaces();
  28867. }
  28868. // Restore submeshes
  28869. this.releaseSubMeshes();
  28870. this.subMeshes = submeshes;
  28871. return this;
  28872. };
  28873. /**
  28874. * Modifies the mesh geometry according to its own current World Matrix.
  28875. * The mesh World Matrix is then reset.
  28876. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28877. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28878. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28879. * Returns the Mesh.
  28880. */
  28881. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28882. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28883. this.scaling.copyFromFloats(1, 1, 1);
  28884. this.position.copyFromFloats(0, 0, 0);
  28885. this.rotation.copyFromFloats(0, 0, 0);
  28886. //only if quaternion is already set
  28887. if (this.rotationQuaternion) {
  28888. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28889. }
  28890. this._worldMatrix = BABYLON.Matrix.Identity();
  28891. return this;
  28892. };
  28893. Object.defineProperty(Mesh.prototype, "_positions", {
  28894. // Cache
  28895. get: function () {
  28896. if (this._geometry) {
  28897. return this._geometry._positions;
  28898. }
  28899. return null;
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Mesh.prototype._resetPointsArrayCache = function () {
  28905. if (this._geometry) {
  28906. this._geometry._resetPointsArrayCache();
  28907. }
  28908. return this;
  28909. };
  28910. Mesh.prototype._generatePointsArray = function () {
  28911. if (this._geometry) {
  28912. return this._geometry._generatePointsArray();
  28913. }
  28914. return false;
  28915. };
  28916. /**
  28917. * Returns a new Mesh object generated from the current mesh properties.
  28918. * This method must not get confused with createInstance().
  28919. * The parameter `name` is a string, the name given to the new mesh.
  28920. * The optional parameter `newParent` can be any Node object (default `null`).
  28921. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28922. * 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.
  28923. */
  28924. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28925. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28926. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28927. };
  28928. /**
  28929. * Releases resources associated with this mesh.
  28930. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28931. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28932. */
  28933. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28934. var _this = this;
  28935. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28936. this.morphTargetManager = null;
  28937. if (this._geometry) {
  28938. this._geometry.releaseForMesh(this, true);
  28939. }
  28940. // Sources
  28941. var meshes = this.getScene().meshes;
  28942. meshes.forEach(function (abstractMesh) {
  28943. var mesh = abstractMesh;
  28944. if (mesh._source && mesh._source === _this) {
  28945. mesh._source = null;
  28946. }
  28947. });
  28948. this._source = null;
  28949. // Instances
  28950. if (this._instancesBuffer) {
  28951. this._instancesBuffer.dispose();
  28952. this._instancesBuffer = null;
  28953. }
  28954. while (this.instances.length) {
  28955. this.instances[0].dispose();
  28956. }
  28957. // Effect layers.
  28958. var effectLayers = this.getScene().effectLayers;
  28959. for (var i = 0; i < effectLayers.length; i++) {
  28960. var effectLayer = effectLayers[i];
  28961. if (effectLayer) {
  28962. effectLayer._disposeMesh(this);
  28963. }
  28964. }
  28965. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28966. };
  28967. /**
  28968. * Modifies the mesh geometry according to a displacement map.
  28969. * 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.
  28970. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28971. * This method returns nothing.
  28972. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28973. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28974. * 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.
  28975. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28976. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28977. *
  28978. * Returns the Mesh.
  28979. */
  28980. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28981. var _this = this;
  28982. var scene = this.getScene();
  28983. var onload = function (img) {
  28984. // Getting height map data
  28985. var canvas = document.createElement("canvas");
  28986. var context = canvas.getContext("2d");
  28987. var heightMapWidth = img.width;
  28988. var heightMapHeight = img.height;
  28989. canvas.width = heightMapWidth;
  28990. canvas.height = heightMapHeight;
  28991. context.drawImage(img, 0, 0);
  28992. // Create VertexData from map data
  28993. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28994. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28995. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28996. //execute success callback, if set
  28997. if (onSuccess) {
  28998. onSuccess(_this);
  28999. }
  29000. };
  29001. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29002. return this;
  29003. };
  29004. /**
  29005. * Modifies the mesh geometry according to a displacementMap buffer.
  29006. * 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.
  29007. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29008. * This method returns nothing.
  29009. * 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.
  29010. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29011. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29012. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29013. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29014. *
  29015. * Returns the Mesh.
  29016. */
  29017. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29018. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29019. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29020. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29021. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29022. return this;
  29023. }
  29024. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29025. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29026. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29027. var position = BABYLON.Vector3.Zero();
  29028. var normal = BABYLON.Vector3.Zero();
  29029. var uv = BABYLON.Vector2.Zero();
  29030. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29031. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29032. for (var index = 0; index < positions.length; index += 3) {
  29033. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29034. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29035. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29036. // Compute height
  29037. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29038. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29039. var pos = (u + v * heightMapWidth) * 4;
  29040. var r = buffer[pos] / 255.0;
  29041. var g = buffer[pos + 1] / 255.0;
  29042. var b = buffer[pos + 2] / 255.0;
  29043. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29044. normal.normalize();
  29045. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29046. position = position.add(normal);
  29047. position.toArray(positions, index);
  29048. }
  29049. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29050. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29051. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29052. return this;
  29053. };
  29054. /**
  29055. * Modify the mesh to get a flat shading rendering.
  29056. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29057. * This method returns the Mesh.
  29058. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29059. */
  29060. Mesh.prototype.convertToFlatShadedMesh = function () {
  29061. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29062. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29063. var kinds = this.getVerticesDataKinds();
  29064. var vbs = {};
  29065. var data = {};
  29066. var newdata = {};
  29067. var updatableNormals = false;
  29068. var kindIndex;
  29069. var kind;
  29070. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29071. kind = kinds[kindIndex];
  29072. var vertexBuffer = this.getVertexBuffer(kind);
  29073. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29074. updatableNormals = vertexBuffer.isUpdatable();
  29075. kinds.splice(kindIndex, 1);
  29076. kindIndex--;
  29077. continue;
  29078. }
  29079. vbs[kind] = vertexBuffer;
  29080. data[kind] = vbs[kind].getData();
  29081. newdata[kind] = [];
  29082. }
  29083. // Save previous submeshes
  29084. var previousSubmeshes = this.subMeshes.slice(0);
  29085. var indices = this.getIndices();
  29086. var totalIndices = this.getTotalIndices();
  29087. // Generating unique vertices per face
  29088. var index;
  29089. for (index = 0; index < totalIndices; index++) {
  29090. var vertexIndex = indices[index];
  29091. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29092. kind = kinds[kindIndex];
  29093. var stride = vbs[kind].getStrideSize();
  29094. for (var offset = 0; offset < stride; offset++) {
  29095. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29096. }
  29097. }
  29098. }
  29099. // Updating faces & normal
  29100. var normals = [];
  29101. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29102. for (index = 0; index < totalIndices; index += 3) {
  29103. indices[index] = index;
  29104. indices[index + 1] = index + 1;
  29105. indices[index + 2] = index + 2;
  29106. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29107. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29108. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29109. var p1p2 = p1.subtract(p2);
  29110. var p3p2 = p3.subtract(p2);
  29111. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29112. // Store same normals for every vertex
  29113. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29114. normals.push(normal.x);
  29115. normals.push(normal.y);
  29116. normals.push(normal.z);
  29117. }
  29118. }
  29119. this.setIndices(indices);
  29120. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29121. // Updating vertex buffers
  29122. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29123. kind = kinds[kindIndex];
  29124. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29125. }
  29126. // Updating submeshes
  29127. this.releaseSubMeshes();
  29128. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29129. var previousOne = previousSubmeshes[submeshIndex];
  29130. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29131. }
  29132. this.synchronizeInstances();
  29133. return this;
  29134. };
  29135. /**
  29136. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29137. * In other words, more vertices, no more indices and a single bigger VBO.
  29138. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29139. * Returns the Mesh.
  29140. */
  29141. Mesh.prototype.convertToUnIndexedMesh = function () {
  29142. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29143. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29144. var kinds = this.getVerticesDataKinds();
  29145. var vbs = {};
  29146. var data = {};
  29147. var newdata = {};
  29148. var kindIndex;
  29149. var kind;
  29150. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29151. kind = kinds[kindIndex];
  29152. var vertexBuffer = this.getVertexBuffer(kind);
  29153. vbs[kind] = vertexBuffer;
  29154. data[kind] = vbs[kind].getData();
  29155. newdata[kind] = [];
  29156. }
  29157. // Save previous submeshes
  29158. var previousSubmeshes = this.subMeshes.slice(0);
  29159. var indices = this.getIndices();
  29160. var totalIndices = this.getTotalIndices();
  29161. // Generating unique vertices per face
  29162. var index;
  29163. for (index = 0; index < totalIndices; index++) {
  29164. var vertexIndex = indices[index];
  29165. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29166. kind = kinds[kindIndex];
  29167. var stride = vbs[kind].getStrideSize();
  29168. for (var offset = 0; offset < stride; offset++) {
  29169. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29170. }
  29171. }
  29172. }
  29173. // Updating indices
  29174. for (index = 0; index < totalIndices; index += 3) {
  29175. indices[index] = index;
  29176. indices[index + 1] = index + 1;
  29177. indices[index + 2] = index + 2;
  29178. }
  29179. this.setIndices(indices);
  29180. // Updating vertex buffers
  29181. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29182. kind = kinds[kindIndex];
  29183. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29184. }
  29185. // Updating submeshes
  29186. this.releaseSubMeshes();
  29187. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29188. var previousOne = previousSubmeshes[submeshIndex];
  29189. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29190. }
  29191. this._unIndexed = true;
  29192. this.synchronizeInstances();
  29193. return this;
  29194. };
  29195. /**
  29196. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29197. * This method returns the Mesh.
  29198. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29199. */
  29200. Mesh.prototype.flipFaces = function (flipNormals) {
  29201. if (flipNormals === void 0) { flipNormals = false; }
  29202. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29203. var i;
  29204. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29205. for (i = 0; i < vertex_data.normals.length; i++) {
  29206. vertex_data.normals[i] *= -1;
  29207. }
  29208. }
  29209. if (vertex_data.indices) {
  29210. var temp;
  29211. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29212. // reassign indices
  29213. temp = vertex_data.indices[i + 1];
  29214. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29215. vertex_data.indices[i + 2] = temp;
  29216. }
  29217. }
  29218. vertex_data.applyToMesh(this);
  29219. return this;
  29220. };
  29221. // Instances
  29222. /**
  29223. * Creates a new InstancedMesh object from the mesh model.
  29224. * An instance shares the same properties and the same material than its model.
  29225. * Only these properties of each instance can then be set individually :
  29226. * - position
  29227. * - rotation
  29228. * - rotationQuaternion
  29229. * - setPivotMatrix
  29230. * - scaling
  29231. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29232. * Warning : this method is not supported for Line mesh and LineSystem
  29233. */
  29234. Mesh.prototype.createInstance = function (name) {
  29235. return new BABYLON.InstancedMesh(name, this);
  29236. };
  29237. /**
  29238. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29239. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29240. * This method returns the Mesh.
  29241. */
  29242. Mesh.prototype.synchronizeInstances = function () {
  29243. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29244. var instance = this.instances[instanceIndex];
  29245. instance._syncSubMeshes();
  29246. }
  29247. return this;
  29248. };
  29249. /**
  29250. * Simplify the mesh according to the given array of settings.
  29251. * Function will return immediately and will simplify async. It returns the Mesh.
  29252. * @param settings a collection of simplification settings.
  29253. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29254. * @param type the type of simplification to run.
  29255. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29256. */
  29257. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29258. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29259. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29260. this.getScene().simplificationQueue.addTask({
  29261. settings: settings,
  29262. parallelProcessing: parallelProcessing,
  29263. mesh: this,
  29264. simplificationType: simplificationType,
  29265. successCallback: successCallback
  29266. });
  29267. return this;
  29268. };
  29269. /**
  29270. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29271. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29272. * This should be used together with the simplification to avoid disappearing triangles.
  29273. * Returns the Mesh.
  29274. * @param successCallback an optional success callback to be called after the optimization finished.
  29275. */
  29276. Mesh.prototype.optimizeIndices = function (successCallback) {
  29277. var _this = this;
  29278. var indices = this.getIndices();
  29279. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29280. if (!positions || !indices) {
  29281. return this;
  29282. }
  29283. var vectorPositions = new Array();
  29284. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29285. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29286. }
  29287. var dupes = new Array();
  29288. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29289. var realPos = vectorPositions.length - 1 - iteration;
  29290. var testedPosition = vectorPositions[realPos];
  29291. for (var j = 0; j < realPos; ++j) {
  29292. var againstPosition = vectorPositions[j];
  29293. if (testedPosition.equals(againstPosition)) {
  29294. dupes[realPos] = j;
  29295. break;
  29296. }
  29297. }
  29298. }, function () {
  29299. for (var i = 0; i < indices.length; ++i) {
  29300. indices[i] = dupes[indices[i]] || indices[i];
  29301. }
  29302. //indices are now reordered
  29303. var originalSubMeshes = _this.subMeshes.slice(0);
  29304. _this.setIndices(indices);
  29305. _this.subMeshes = originalSubMeshes;
  29306. if (successCallback) {
  29307. successCallback(_this);
  29308. }
  29309. });
  29310. return this;
  29311. };
  29312. Mesh.prototype.serialize = function (serializationObject) {
  29313. serializationObject.name = this.name;
  29314. serializationObject.id = this.id;
  29315. serializationObject.type = this.getClassName();
  29316. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29317. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29318. }
  29319. serializationObject.position = this.position.asArray();
  29320. if (this.rotationQuaternion) {
  29321. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29322. }
  29323. else if (this.rotation) {
  29324. serializationObject.rotation = this.rotation.asArray();
  29325. }
  29326. serializationObject.scaling = this.scaling.asArray();
  29327. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29328. serializationObject.isEnabled = this.isEnabled(false);
  29329. serializationObject.isVisible = this.isVisible;
  29330. serializationObject.infiniteDistance = this.infiniteDistance;
  29331. serializationObject.pickable = this.isPickable;
  29332. serializationObject.receiveShadows = this.receiveShadows;
  29333. serializationObject.billboardMode = this.billboardMode;
  29334. serializationObject.visibility = this.visibility;
  29335. serializationObject.checkCollisions = this.checkCollisions;
  29336. serializationObject.isBlocker = this.isBlocker;
  29337. // Parent
  29338. if (this.parent) {
  29339. serializationObject.parentId = this.parent.id;
  29340. }
  29341. // Geometry
  29342. serializationObject.isUnIndexed = this.isUnIndexed;
  29343. var geometry = this._geometry;
  29344. if (geometry) {
  29345. var geometryId = geometry.id;
  29346. serializationObject.geometryId = geometryId;
  29347. // SubMeshes
  29348. serializationObject.subMeshes = [];
  29349. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29350. var subMesh = this.subMeshes[subIndex];
  29351. serializationObject.subMeshes.push({
  29352. materialIndex: subMesh.materialIndex,
  29353. verticesStart: subMesh.verticesStart,
  29354. verticesCount: subMesh.verticesCount,
  29355. indexStart: subMesh.indexStart,
  29356. indexCount: subMesh.indexCount
  29357. });
  29358. }
  29359. }
  29360. // Material
  29361. if (this.material) {
  29362. serializationObject.materialId = this.material.id;
  29363. }
  29364. else {
  29365. this.material = null;
  29366. }
  29367. // Morph targets
  29368. if (this.morphTargetManager) {
  29369. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29370. }
  29371. // Skeleton
  29372. if (this.skeleton) {
  29373. serializationObject.skeletonId = this.skeleton.id;
  29374. }
  29375. // Physics
  29376. //TODO implement correct serialization for physics impostors.
  29377. var impostor = this.getPhysicsImpostor();
  29378. if (impostor) {
  29379. serializationObject.physicsMass = impostor.getParam("mass");
  29380. serializationObject.physicsFriction = impostor.getParam("friction");
  29381. serializationObject.physicsRestitution = impostor.getParam("mass");
  29382. serializationObject.physicsImpostor = impostor.type;
  29383. }
  29384. // Metadata
  29385. if (this.metadata) {
  29386. serializationObject.metadata = this.metadata;
  29387. }
  29388. // Instances
  29389. serializationObject.instances = [];
  29390. for (var index = 0; index < this.instances.length; index++) {
  29391. var instance = this.instances[index];
  29392. var serializationInstance = {
  29393. name: instance.name,
  29394. id: instance.id,
  29395. position: instance.position.asArray(),
  29396. scaling: instance.scaling.asArray()
  29397. };
  29398. if (instance.rotationQuaternion) {
  29399. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29400. }
  29401. else if (instance.rotation) {
  29402. serializationInstance.rotation = instance.rotation.asArray();
  29403. }
  29404. serializationObject.instances.push(serializationInstance);
  29405. // Animations
  29406. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29407. serializationInstance.ranges = instance.serializeAnimationRanges();
  29408. }
  29409. //
  29410. // Animations
  29411. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29412. serializationObject.ranges = this.serializeAnimationRanges();
  29413. // Layer mask
  29414. serializationObject.layerMask = this.layerMask;
  29415. // Alpha
  29416. serializationObject.alphaIndex = this.alphaIndex;
  29417. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29418. // Overlay
  29419. serializationObject.overlayAlpha = this.overlayAlpha;
  29420. serializationObject.overlayColor = this.overlayColor.asArray();
  29421. serializationObject.renderOverlay = this.renderOverlay;
  29422. // Fog
  29423. serializationObject.applyFog = this.applyFog;
  29424. // Action Manager
  29425. if (this.actionManager) {
  29426. serializationObject.actions = this.actionManager.serialize(this.name);
  29427. }
  29428. };
  29429. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29430. if (!this.geometry) {
  29431. return;
  29432. }
  29433. this._markSubMeshesAsAttributesDirty();
  29434. var morphTargetManager = this._morphTargetManager;
  29435. if (morphTargetManager && morphTargetManager.vertexCount) {
  29436. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29437. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29438. this.morphTargetManager = null;
  29439. return;
  29440. }
  29441. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29442. var morphTarget = morphTargetManager.getActiveTarget(index);
  29443. var positions = morphTarget.getPositions();
  29444. if (!positions) {
  29445. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29446. return;
  29447. }
  29448. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29449. var normals = morphTarget.getNormals();
  29450. if (normals) {
  29451. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29452. }
  29453. var tangents = morphTarget.getTangents();
  29454. if (tangents) {
  29455. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29456. }
  29457. }
  29458. }
  29459. else {
  29460. var index = 0;
  29461. // Positions
  29462. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29463. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29464. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29465. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29466. }
  29467. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29468. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29469. }
  29470. index++;
  29471. }
  29472. }
  29473. };
  29474. // Statics
  29475. /**
  29476. * Returns a new Mesh object parsed from the source provided.
  29477. * The parameter `parsedMesh` is the source.
  29478. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29479. */
  29480. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29481. var mesh;
  29482. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29483. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29484. }
  29485. else {
  29486. mesh = new Mesh(parsedMesh.name, scene);
  29487. }
  29488. mesh.id = parsedMesh.id;
  29489. if (BABYLON.Tags) {
  29490. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29491. }
  29492. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29493. if (parsedMesh.metadata !== undefined) {
  29494. mesh.metadata = parsedMesh.metadata;
  29495. }
  29496. if (parsedMesh.rotationQuaternion) {
  29497. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29498. }
  29499. else if (parsedMesh.rotation) {
  29500. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29501. }
  29502. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29503. if (parsedMesh.localMatrix) {
  29504. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29505. }
  29506. else if (parsedMesh.pivotMatrix) {
  29507. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29508. }
  29509. mesh.setEnabled(parsedMesh.isEnabled);
  29510. mesh.isVisible = parsedMesh.isVisible;
  29511. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29512. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29513. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29514. if (parsedMesh.applyFog !== undefined) {
  29515. mesh.applyFog = parsedMesh.applyFog;
  29516. }
  29517. if (parsedMesh.pickable !== undefined) {
  29518. mesh.isPickable = parsedMesh.pickable;
  29519. }
  29520. if (parsedMesh.alphaIndex !== undefined) {
  29521. mesh.alphaIndex = parsedMesh.alphaIndex;
  29522. }
  29523. mesh.receiveShadows = parsedMesh.receiveShadows;
  29524. mesh.billboardMode = parsedMesh.billboardMode;
  29525. if (parsedMesh.visibility !== undefined) {
  29526. mesh.visibility = parsedMesh.visibility;
  29527. }
  29528. mesh.checkCollisions = parsedMesh.checkCollisions;
  29529. if (parsedMesh.isBlocker !== undefined) {
  29530. mesh.isBlocker = parsedMesh.isBlocker;
  29531. }
  29532. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29533. // freezeWorldMatrix
  29534. if (parsedMesh.freezeWorldMatrix) {
  29535. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29536. }
  29537. // Parent
  29538. if (parsedMesh.parentId) {
  29539. mesh._waitingParentId = parsedMesh.parentId;
  29540. }
  29541. // Actions
  29542. if (parsedMesh.actions !== undefined) {
  29543. mesh._waitingActions = parsedMesh.actions;
  29544. }
  29545. // Overlay
  29546. if (parsedMesh.overlayAlpha !== undefined) {
  29547. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29548. }
  29549. if (parsedMesh.overlayColor !== undefined) {
  29550. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29551. }
  29552. if (parsedMesh.renderOverlay !== undefined) {
  29553. mesh.renderOverlay = parsedMesh.renderOverlay;
  29554. }
  29555. // Geometry
  29556. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29557. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29558. if (parsedMesh.delayLoadingFile) {
  29559. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29560. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29561. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29562. if (parsedMesh._binaryInfo) {
  29563. mesh._binaryInfo = parsedMesh._binaryInfo;
  29564. }
  29565. mesh._delayInfo = [];
  29566. if (parsedMesh.hasUVs) {
  29567. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29568. }
  29569. if (parsedMesh.hasUVs2) {
  29570. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29571. }
  29572. if (parsedMesh.hasUVs3) {
  29573. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29574. }
  29575. if (parsedMesh.hasUVs4) {
  29576. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29577. }
  29578. if (parsedMesh.hasUVs5) {
  29579. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29580. }
  29581. if (parsedMesh.hasUVs6) {
  29582. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29583. }
  29584. if (parsedMesh.hasColors) {
  29585. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29586. }
  29587. if (parsedMesh.hasMatricesIndices) {
  29588. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29589. }
  29590. if (parsedMesh.hasMatricesWeights) {
  29591. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29592. }
  29593. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29594. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29595. mesh._checkDelayState();
  29596. }
  29597. }
  29598. else {
  29599. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29600. }
  29601. // Material
  29602. if (parsedMesh.materialId) {
  29603. mesh.setMaterialByID(parsedMesh.materialId);
  29604. }
  29605. else {
  29606. mesh.material = null;
  29607. }
  29608. // Morph targets
  29609. if (parsedMesh.morphTargetManagerId > -1) {
  29610. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29611. }
  29612. // Skeleton
  29613. if (parsedMesh.skeletonId > -1) {
  29614. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29615. if (parsedMesh.numBoneInfluencers) {
  29616. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29617. }
  29618. }
  29619. // Animations
  29620. if (parsedMesh.animations) {
  29621. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29622. var parsedAnimation = parsedMesh.animations[animationIndex];
  29623. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29624. }
  29625. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29626. }
  29627. if (parsedMesh.autoAnimate) {
  29628. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29629. }
  29630. // Layer Mask
  29631. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29632. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29633. }
  29634. else {
  29635. mesh.layerMask = 0x0FFFFFFF;
  29636. }
  29637. // Physics
  29638. if (parsedMesh.physicsImpostor) {
  29639. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29640. mass: parsedMesh.physicsMass,
  29641. friction: parsedMesh.physicsFriction,
  29642. restitution: parsedMesh.physicsRestitution
  29643. }, scene);
  29644. }
  29645. // Instances
  29646. if (parsedMesh.instances) {
  29647. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29648. var parsedInstance = parsedMesh.instances[index];
  29649. var instance = mesh.createInstance(parsedInstance.name);
  29650. if (parsedInstance.id) {
  29651. instance.id = parsedInstance.id;
  29652. }
  29653. if (BABYLON.Tags) {
  29654. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29655. }
  29656. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29657. if (parsedInstance.parentId) {
  29658. instance._waitingParentId = parsedInstance.parentId;
  29659. }
  29660. if (parsedInstance.rotationQuaternion) {
  29661. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29662. }
  29663. else if (parsedInstance.rotation) {
  29664. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29665. }
  29666. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29667. instance.checkCollisions = mesh.checkCollisions;
  29668. if (parsedMesh.animations) {
  29669. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29670. parsedAnimation = parsedMesh.animations[animationIndex];
  29671. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29672. }
  29673. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29674. }
  29675. }
  29676. }
  29677. return mesh;
  29678. };
  29679. /**
  29680. * Creates a ribbon mesh.
  29681. * Please consider using the same method from the MeshBuilder class instead.
  29682. * 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.
  29683. *
  29684. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29685. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29686. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29687. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29688. * 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.
  29689. * 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.
  29690. * 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
  29691. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29692. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29694. */
  29695. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29696. if (closeArray === void 0) { closeArray = false; }
  29697. if (updatable === void 0) { updatable = false; }
  29698. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29699. pathArray: pathArray,
  29700. closeArray: closeArray,
  29701. closePath: closePath,
  29702. offset: offset,
  29703. updatable: updatable,
  29704. sideOrientation: sideOrientation,
  29705. instance: instance
  29706. }, scene);
  29707. };
  29708. /**
  29709. * Creates a plane polygonal mesh. By default, this is a disc.
  29710. * Please consider using the same method from the MeshBuilder class instead.
  29711. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29712. * 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.
  29713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29716. */
  29717. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29718. if (scene === void 0) { scene = null; }
  29719. var options = {
  29720. radius: radius,
  29721. tessellation: tessellation,
  29722. sideOrientation: sideOrientation,
  29723. updatable: updatable
  29724. };
  29725. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29726. };
  29727. /**
  29728. * Creates a box mesh.
  29729. * Please consider using the same method from the MeshBuilder class instead.
  29730. * The parameter `size` sets the size (float) of each box side (default 1).
  29731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29732. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29734. */
  29735. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29736. if (scene === void 0) { scene = null; }
  29737. var options = {
  29738. size: size,
  29739. sideOrientation: sideOrientation,
  29740. updatable: updatable
  29741. };
  29742. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29743. };
  29744. /**
  29745. * Creates a sphere mesh.
  29746. * Please consider using the same method from the MeshBuilder class instead.
  29747. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29748. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29752. */
  29753. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29754. var options = {
  29755. segments: segments,
  29756. diameterX: diameter,
  29757. diameterY: diameter,
  29758. diameterZ: diameter,
  29759. sideOrientation: sideOrientation,
  29760. updatable: updatable
  29761. };
  29762. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29763. };
  29764. /**
  29765. * Creates a cylinder or a cone mesh.
  29766. * Please consider using the same method from the MeshBuilder class instead.
  29767. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29768. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29769. * 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.
  29770. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29771. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29773. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29775. */
  29776. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29777. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29778. if (scene !== undefined) {
  29779. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29780. updatable = scene;
  29781. }
  29782. scene = subdivisions;
  29783. subdivisions = 1;
  29784. }
  29785. var options = {
  29786. height: height,
  29787. diameterTop: diameterTop,
  29788. diameterBottom: diameterBottom,
  29789. tessellation: tessellation,
  29790. subdivisions: subdivisions,
  29791. sideOrientation: sideOrientation,
  29792. updatable: updatable
  29793. };
  29794. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29795. };
  29796. // Torus (Code from SharpDX.org)
  29797. /**
  29798. * Creates a torus mesh.
  29799. * Please consider using the same method from the MeshBuilder class instead.
  29800. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29801. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29802. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29806. */
  29807. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29808. var options = {
  29809. diameter: diameter,
  29810. thickness: thickness,
  29811. tessellation: tessellation,
  29812. sideOrientation: sideOrientation,
  29813. updatable: updatable
  29814. };
  29815. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29816. };
  29817. /**
  29818. * Creates a torus knot mesh.
  29819. * Please consider using the same method from the MeshBuilder class instead.
  29820. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29821. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29822. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29823. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29825. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29827. */
  29828. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29829. var options = {
  29830. radius: radius,
  29831. tube: tube,
  29832. radialSegments: radialSegments,
  29833. tubularSegments: tubularSegments,
  29834. p: p,
  29835. q: q,
  29836. sideOrientation: sideOrientation,
  29837. updatable: updatable
  29838. };
  29839. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29840. };
  29841. /**
  29842. * Creates a line mesh.
  29843. * Please consider using the same method from the MeshBuilder class instead.
  29844. * 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.
  29845. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29846. * The parameter `points` is an array successive Vector3.
  29847. * 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
  29848. * When updating an instance, remember that only point positions can change, not the number of points.
  29849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29850. */
  29851. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29852. if (scene === void 0) { scene = null; }
  29853. if (updatable === void 0) { updatable = false; }
  29854. if (instance === void 0) { instance = null; }
  29855. var options = {
  29856. points: points,
  29857. updatable: updatable,
  29858. instance: instance
  29859. };
  29860. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29861. };
  29862. /**
  29863. * Creates a dashed line mesh.
  29864. * Please consider using the same method from the MeshBuilder class instead.
  29865. * 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.
  29866. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29867. * The parameter `points` is an array successive Vector3.
  29868. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29869. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29870. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29871. * 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
  29872. * When updating an instance, remember that only point positions can change, not the number of points.
  29873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29874. */
  29875. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29876. if (scene === void 0) { scene = null; }
  29877. var options = {
  29878. points: points,
  29879. dashSize: dashSize,
  29880. gapSize: gapSize,
  29881. dashNb: dashNb,
  29882. updatable: updatable,
  29883. instance: instance
  29884. };
  29885. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29886. };
  29887. /**
  29888. * Creates a polygon mesh.
  29889. * Please consider using the same method from the MeshBuilder class instead.
  29890. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29891. * 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.
  29892. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29894. * Remember you can only change the shape positions, not their number when updating a polygon.
  29895. */
  29896. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29897. var options = {
  29898. shape: shape,
  29899. holes: holes,
  29900. updatable: updatable,
  29901. sideOrientation: sideOrientation
  29902. };
  29903. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29904. };
  29905. /**
  29906. * Creates an extruded polygon mesh, with depth in the Y direction.
  29907. * Please consider using the same method from the MeshBuilder class instead.
  29908. */
  29909. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29910. var options = {
  29911. shape: shape,
  29912. holes: holes,
  29913. depth: depth,
  29914. updatable: updatable,
  29915. sideOrientation: sideOrientation
  29916. };
  29917. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29918. };
  29919. /**
  29920. * Creates an extruded shape mesh.
  29921. * 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.
  29922. * Please consider using the same method from the MeshBuilder class instead.
  29923. *
  29924. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29925. * 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
  29926. * extruded along the Z axis.
  29927. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29928. * 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.
  29929. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29930. * 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
  29931. * 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
  29932. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29936. */
  29937. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29938. if (scene === void 0) { scene = null; }
  29939. var options = {
  29940. shape: shape,
  29941. path: path,
  29942. scale: scale,
  29943. rotation: rotation,
  29944. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29945. sideOrientation: sideOrientation,
  29946. instance: instance,
  29947. updatable: updatable
  29948. };
  29949. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29950. };
  29951. /**
  29952. * Creates an custom extruded shape mesh.
  29953. * 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.
  29954. * Please consider using the same method from the MeshBuilder class instead.
  29955. *
  29956. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29957. * 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
  29958. * extruded along the Z axis.
  29959. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29960. * 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
  29961. * and the distance of this point from the begining of the path :
  29962. * ```javascript
  29963. * var rotationFunction = function(i, distance) {
  29964. * // do things
  29965. * return rotationValue; }
  29966. * ```
  29967. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29968. * 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
  29969. * and the distance of this point from the begining of the path :
  29970. * ```javascript
  29971. * var scaleFunction = function(i, distance) {
  29972. * // do things
  29973. * return scaleValue;}
  29974. * ```
  29975. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29976. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29977. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29978. * 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
  29979. * 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
  29980. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29984. */
  29985. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29986. var options = {
  29987. shape: shape,
  29988. path: path,
  29989. scaleFunction: scaleFunction,
  29990. rotationFunction: rotationFunction,
  29991. ribbonCloseArray: ribbonCloseArray,
  29992. ribbonClosePath: ribbonClosePath,
  29993. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29994. sideOrientation: sideOrientation,
  29995. instance: instance,
  29996. updatable: updatable
  29997. };
  29998. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29999. };
  30000. /**
  30001. * Creates lathe mesh.
  30002. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30003. * Please consider using the same method from the MeshBuilder class instead.
  30004. * 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
  30005. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30006. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30007. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30008. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30009. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30011. */
  30012. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30013. var options = {
  30014. shape: shape,
  30015. radius: radius,
  30016. tessellation: tessellation,
  30017. sideOrientation: sideOrientation,
  30018. updatable: updatable
  30019. };
  30020. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30021. };
  30022. /**
  30023. * Creates a plane mesh.
  30024. * Please consider using the same method from the MeshBuilder class instead.
  30025. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30029. */
  30030. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30031. var options = {
  30032. size: size,
  30033. width: size,
  30034. height: size,
  30035. sideOrientation: sideOrientation,
  30036. updatable: updatable
  30037. };
  30038. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30039. };
  30040. /**
  30041. * Creates a ground mesh.
  30042. * Please consider using the same method from the MeshBuilder class instead.
  30043. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30044. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  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.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30048. var options = {
  30049. width: width,
  30050. height: height,
  30051. subdivisions: subdivisions,
  30052. updatable: updatable
  30053. };
  30054. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30055. };
  30056. /**
  30057. * Creates a tiled ground mesh.
  30058. * Please consider using the same method from the MeshBuilder class instead.
  30059. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30060. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30061. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30062. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30063. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30064. * numbers of subdivisions on the ground width and height of each tile.
  30065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30066. */
  30067. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30068. var options = {
  30069. xmin: xmin,
  30070. zmin: zmin,
  30071. xmax: xmax,
  30072. zmax: zmax,
  30073. subdivisions: subdivisions,
  30074. precision: precision,
  30075. updatable: updatable
  30076. };
  30077. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30078. };
  30079. /**
  30080. * Creates a ground mesh from a height map.
  30081. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30082. * Please consider using the same method from the MeshBuilder class instead.
  30083. * The parameter `url` sets the URL of the height map image resource.
  30084. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30085. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30086. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30087. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30088. * 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).
  30089. * This function is passed the newly built mesh :
  30090. * ```javascript
  30091. * function(mesh) { // do things
  30092. * return; }
  30093. * ```
  30094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30095. */
  30096. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30097. var options = {
  30098. width: width,
  30099. height: height,
  30100. subdivisions: subdivisions,
  30101. minHeight: minHeight,
  30102. maxHeight: maxHeight,
  30103. updatable: updatable,
  30104. onReady: onReady
  30105. };
  30106. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30107. };
  30108. /**
  30109. * Creates a tube mesh.
  30110. * 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.
  30111. * Please consider using the same method from the MeshBuilder class instead.
  30112. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30113. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30114. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30115. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30116. * 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.
  30117. * It must return a radius value (positive float) :
  30118. * ```javascript
  30119. * var radiusFunction = function(i, distance) {
  30120. * // do things
  30121. * return radius; }
  30122. * ```
  30123. * 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
  30124. * 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
  30125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30128. */
  30129. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30130. var options = {
  30131. path: path,
  30132. radius: radius,
  30133. tessellation: tessellation,
  30134. radiusFunction: radiusFunction,
  30135. arc: 1,
  30136. cap: cap,
  30137. updatable: updatable,
  30138. sideOrientation: sideOrientation,
  30139. instance: instance
  30140. };
  30141. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30142. };
  30143. /**
  30144. * Creates a polyhedron mesh.
  30145. * Please consider using the same method from the MeshBuilder class instead.
  30146. * 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
  30147. * to choose the wanted type.
  30148. * The parameter `size` (positive float, default 1) sets the polygon size.
  30149. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30150. * 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`.
  30151. * 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
  30152. * 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)`).
  30153. * 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
  30154. * 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.
  30155. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30156. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30158. */
  30159. Mesh.CreatePolyhedron = function (name, options, scene) {
  30160. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30161. };
  30162. /**
  30163. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30164. * Please consider using the same method from the MeshBuilder class instead.
  30165. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30166. * 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`).
  30167. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30168. * 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.
  30169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30172. */
  30173. Mesh.CreateIcoSphere = function (name, options, scene) {
  30174. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30175. };
  30176. /**
  30177. * Creates a decal mesh.
  30178. * Please consider using the same method from the MeshBuilder class instead.
  30179. * 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.
  30180. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30181. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30182. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30183. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30184. */
  30185. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30186. var options = {
  30187. position: position,
  30188. normal: normal,
  30189. size: size,
  30190. angle: angle
  30191. };
  30192. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30193. };
  30194. // Skeletons
  30195. /**
  30196. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30197. */
  30198. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30199. if (!this._sourcePositions) {
  30200. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30201. if (!source) {
  30202. return this._sourcePositions;
  30203. }
  30204. this._sourcePositions = new Float32Array(source);
  30205. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30206. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30207. }
  30208. }
  30209. return this._sourcePositions;
  30210. };
  30211. /**
  30212. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30213. */
  30214. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30215. if (!this._sourceNormals) {
  30216. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30217. if (!source) {
  30218. return this._sourceNormals;
  30219. }
  30220. this._sourceNormals = new Float32Array(source);
  30221. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30222. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30223. }
  30224. }
  30225. return this._sourceNormals;
  30226. };
  30227. /**
  30228. * Updates the vertex buffer by applying transformation from the bones.
  30229. * Returns the Mesh.
  30230. *
  30231. * @param {skeleton} skeleton to apply
  30232. */
  30233. Mesh.prototype.applySkeleton = function (skeleton) {
  30234. if (!this.geometry) {
  30235. return this;
  30236. }
  30237. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30238. return this;
  30239. }
  30240. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30241. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30242. return this;
  30243. }
  30244. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30245. return this;
  30246. }
  30247. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30248. return this;
  30249. }
  30250. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30251. return this;
  30252. }
  30253. if (!this._sourcePositions) {
  30254. var submeshes = this.subMeshes.slice();
  30255. this.setPositionsForCPUSkinning();
  30256. this.subMeshes = submeshes;
  30257. }
  30258. if (!this._sourceNormals) {
  30259. this.setNormalsForCPUSkinning();
  30260. }
  30261. // positionsData checks for not being Float32Array will only pass at most once
  30262. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30263. if (!positionsData) {
  30264. return this;
  30265. }
  30266. if (!(positionsData instanceof Float32Array)) {
  30267. positionsData = new Float32Array(positionsData);
  30268. }
  30269. // normalsData checks for not being Float32Array will only pass at most once
  30270. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30271. if (!normalsData) {
  30272. return this;
  30273. }
  30274. if (!(normalsData instanceof Float32Array)) {
  30275. normalsData = new Float32Array(normalsData);
  30276. }
  30277. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30278. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30279. if (!matricesWeightsData || !matricesIndicesData) {
  30280. return this;
  30281. }
  30282. var needExtras = this.numBoneInfluencers > 4;
  30283. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30284. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30285. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30286. var tempVector3 = BABYLON.Vector3.Zero();
  30287. var finalMatrix = new BABYLON.Matrix();
  30288. var tempMatrix = new BABYLON.Matrix();
  30289. var matWeightIdx = 0;
  30290. var inf;
  30291. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30292. var weight;
  30293. for (inf = 0; inf < 4; inf++) {
  30294. weight = matricesWeightsData[matWeightIdx + inf];
  30295. if (weight > 0) {
  30296. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30297. finalMatrix.addToSelf(tempMatrix);
  30298. }
  30299. else
  30300. break;
  30301. }
  30302. if (needExtras) {
  30303. for (inf = 0; inf < 4; inf++) {
  30304. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30305. if (weight > 0) {
  30306. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30307. finalMatrix.addToSelf(tempMatrix);
  30308. }
  30309. else
  30310. break;
  30311. }
  30312. }
  30313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30314. tempVector3.toArray(positionsData, index);
  30315. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30316. tempVector3.toArray(normalsData, index);
  30317. finalMatrix.reset();
  30318. }
  30319. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30320. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30321. return this;
  30322. };
  30323. // Tools
  30324. /**
  30325. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30326. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30327. */
  30328. Mesh.MinMax = function (meshes) {
  30329. var minVector = null;
  30330. var maxVector = null;
  30331. meshes.forEach(function (mesh, index, array) {
  30332. var boundingInfo = mesh.getBoundingInfo();
  30333. var boundingBox = boundingInfo.boundingBox;
  30334. if (!minVector || !maxVector) {
  30335. minVector = boundingBox.minimumWorld;
  30336. maxVector = boundingBox.maximumWorld;
  30337. }
  30338. else {
  30339. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30340. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30341. }
  30342. });
  30343. if (!minVector || !maxVector) {
  30344. return {
  30345. min: BABYLON.Vector3.Zero(),
  30346. max: BABYLON.Vector3.Zero()
  30347. };
  30348. }
  30349. return {
  30350. min: minVector,
  30351. max: maxVector
  30352. };
  30353. };
  30354. /**
  30355. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30356. */
  30357. Mesh.Center = function (meshesOrMinMaxVector) {
  30358. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30359. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30360. };
  30361. /**
  30362. * Merge the array of meshes into a single mesh for performance reasons.
  30363. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30364. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30365. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30366. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30367. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30368. */
  30369. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30370. if (disposeSource === void 0) { disposeSource = true; }
  30371. var index;
  30372. if (!allow32BitsIndices) {
  30373. var totalVertices = 0;
  30374. // Counting vertices
  30375. for (index = 0; index < meshes.length; index++) {
  30376. if (meshes[index]) {
  30377. totalVertices += meshes[index].getTotalVertices();
  30378. if (totalVertices > 65536) {
  30379. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30380. return null;
  30381. }
  30382. }
  30383. }
  30384. }
  30385. // Merge
  30386. var vertexData = null;
  30387. var otherVertexData;
  30388. var indiceArray = new Array();
  30389. var source = null;
  30390. for (index = 0; index < meshes.length; index++) {
  30391. if (meshes[index]) {
  30392. meshes[index].computeWorldMatrix(true);
  30393. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30394. otherVertexData.transform(meshes[index].getWorldMatrix());
  30395. if (vertexData) {
  30396. vertexData.merge(otherVertexData);
  30397. }
  30398. else {
  30399. vertexData = otherVertexData;
  30400. source = meshes[index];
  30401. }
  30402. if (subdivideWithSubMeshes) {
  30403. indiceArray.push(meshes[index].getTotalIndices());
  30404. }
  30405. }
  30406. }
  30407. source = source;
  30408. if (!meshSubclass) {
  30409. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30410. }
  30411. vertexData.applyToMesh(meshSubclass);
  30412. // Setting properties
  30413. meshSubclass.material = source.material;
  30414. meshSubclass.checkCollisions = source.checkCollisions;
  30415. // Cleaning
  30416. if (disposeSource) {
  30417. for (index = 0; index < meshes.length; index++) {
  30418. if (meshes[index]) {
  30419. meshes[index].dispose();
  30420. }
  30421. }
  30422. }
  30423. // Subdivide
  30424. if (subdivideWithSubMeshes) {
  30425. //-- Suppresions du submesh global
  30426. meshSubclass.releaseSubMeshes();
  30427. index = 0;
  30428. var offset = 0;
  30429. //-- aplique la subdivision en fonction du tableau d'indices
  30430. while (index < indiceArray.length) {
  30431. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30432. offset += indiceArray[index];
  30433. index++;
  30434. }
  30435. }
  30436. return meshSubclass;
  30437. };
  30438. // Consts
  30439. Mesh._FRONTSIDE = 0;
  30440. Mesh._BACKSIDE = 1;
  30441. Mesh._DOUBLESIDE = 2;
  30442. Mesh._DEFAULTSIDE = 0;
  30443. Mesh._NO_CAP = 0;
  30444. Mesh._CAP_START = 1;
  30445. Mesh._CAP_END = 2;
  30446. Mesh._CAP_ALL = 3;
  30447. return Mesh;
  30448. }(BABYLON.AbstractMesh));
  30449. BABYLON.Mesh = Mesh;
  30450. })(BABYLON || (BABYLON = {}));
  30451. //# sourceMappingURL=babylon.mesh.js.map
  30452. var BABYLON;
  30453. (function (BABYLON) {
  30454. var BaseSubMesh = /** @class */ (function () {
  30455. function BaseSubMesh() {
  30456. }
  30457. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30458. get: function () {
  30459. return this._materialEffect;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30465. if (defines === void 0) { defines = null; }
  30466. if (this._materialEffect === effect) {
  30467. if (!effect) {
  30468. this._materialDefines = null;
  30469. }
  30470. return;
  30471. }
  30472. this._materialDefines = defines;
  30473. this._materialEffect = effect;
  30474. };
  30475. return BaseSubMesh;
  30476. }());
  30477. BABYLON.BaseSubMesh = BaseSubMesh;
  30478. var SubMesh = /** @class */ (function (_super) {
  30479. __extends(SubMesh, _super);
  30480. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30481. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30482. var _this = _super.call(this) || this;
  30483. _this.materialIndex = materialIndex;
  30484. _this.verticesStart = verticesStart;
  30485. _this.verticesCount = verticesCount;
  30486. _this.indexStart = indexStart;
  30487. _this.indexCount = indexCount;
  30488. _this._renderId = 0;
  30489. _this._mesh = mesh;
  30490. _this._renderingMesh = renderingMesh || mesh;
  30491. mesh.subMeshes.push(_this);
  30492. _this._trianglePlanes = [];
  30493. _this._id = mesh.subMeshes.length - 1;
  30494. if (createBoundingBox) {
  30495. _this.refreshBoundingInfo();
  30496. mesh.computeWorldMatrix(true);
  30497. }
  30498. return _this;
  30499. }
  30500. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30501. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30502. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30503. };
  30504. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30505. get: function () {
  30506. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. /**
  30512. * Returns the submesh BoudingInfo object.
  30513. */
  30514. SubMesh.prototype.getBoundingInfo = function () {
  30515. if (this.IsGlobal) {
  30516. return this._mesh.getBoundingInfo();
  30517. }
  30518. return this._boundingInfo;
  30519. };
  30520. /**
  30521. * Sets the submesh BoundingInfo.
  30522. * Return the SubMesh.
  30523. */
  30524. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30525. this._boundingInfo = boundingInfo;
  30526. return this;
  30527. };
  30528. /**
  30529. * Returns the mesh of the current submesh.
  30530. */
  30531. SubMesh.prototype.getMesh = function () {
  30532. return this._mesh;
  30533. };
  30534. /**
  30535. * Returns the rendering mesh of the submesh.
  30536. */
  30537. SubMesh.prototype.getRenderingMesh = function () {
  30538. return this._renderingMesh;
  30539. };
  30540. /**
  30541. * Returns the submesh material.
  30542. */
  30543. SubMesh.prototype.getMaterial = function () {
  30544. var rootMaterial = this._renderingMesh.material;
  30545. if (rootMaterial === null || rootMaterial === undefined) {
  30546. return this._mesh.getScene().defaultMaterial;
  30547. }
  30548. else if (rootMaterial.getSubMaterial) {
  30549. var multiMaterial = rootMaterial;
  30550. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30551. if (this._currentMaterial !== effectiveMaterial) {
  30552. this._currentMaterial = effectiveMaterial;
  30553. this._materialDefines = null;
  30554. }
  30555. return effectiveMaterial;
  30556. }
  30557. return rootMaterial;
  30558. };
  30559. // Methods
  30560. /**
  30561. * Sets a new updated BoundingInfo object to the submesh.
  30562. * Returns the SubMesh.
  30563. */
  30564. SubMesh.prototype.refreshBoundingInfo = function () {
  30565. this._lastColliderWorldVertices = null;
  30566. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30567. return this;
  30568. }
  30569. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30570. if (!data) {
  30571. this._boundingInfo = this._mesh.getBoundingInfo();
  30572. return this;
  30573. }
  30574. var indices = this._renderingMesh.getIndices();
  30575. var extend;
  30576. //is this the only submesh?
  30577. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30578. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30579. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30580. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30581. }
  30582. else {
  30583. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30584. }
  30585. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30586. return this;
  30587. };
  30588. SubMesh.prototype._checkCollision = function (collider) {
  30589. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30590. return boundingInfo._checkCollision(collider);
  30591. };
  30592. /**
  30593. * Updates the submesh BoundingInfo.
  30594. * Returns the Submesh.
  30595. */
  30596. SubMesh.prototype.updateBoundingInfo = function (world) {
  30597. var boundingInfo = this.getBoundingInfo();
  30598. if (!boundingInfo) {
  30599. this.refreshBoundingInfo();
  30600. boundingInfo = this.getBoundingInfo();
  30601. }
  30602. boundingInfo.update(world);
  30603. return this;
  30604. };
  30605. /**
  30606. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30607. * Boolean returned.
  30608. */
  30609. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30610. var boundingInfo = this.getBoundingInfo();
  30611. if (!boundingInfo) {
  30612. return false;
  30613. }
  30614. return boundingInfo.isInFrustum(frustumPlanes);
  30615. };
  30616. /**
  30617. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30618. * Boolean returned.
  30619. */
  30620. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30621. var boundingInfo = this.getBoundingInfo();
  30622. if (!boundingInfo) {
  30623. return false;
  30624. }
  30625. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30626. };
  30627. /**
  30628. * Renders the submesh.
  30629. * Returns it.
  30630. */
  30631. SubMesh.prototype.render = function (enableAlphaMode) {
  30632. this._renderingMesh.render(this, enableAlphaMode);
  30633. return this;
  30634. };
  30635. /**
  30636. * Returns a new Index Buffer.
  30637. * Type returned : WebGLBuffer.
  30638. */
  30639. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30640. if (!this._linesIndexBuffer) {
  30641. var linesIndices = [];
  30642. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30643. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30644. }
  30645. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30646. this.linesIndexCount = linesIndices.length;
  30647. }
  30648. return this._linesIndexBuffer;
  30649. };
  30650. /**
  30651. * True is the passed Ray intersects the submesh bounding box.
  30652. * Boolean returned.
  30653. */
  30654. SubMesh.prototype.canIntersects = function (ray) {
  30655. var boundingInfo = this.getBoundingInfo();
  30656. if (!boundingInfo) {
  30657. return false;
  30658. }
  30659. return ray.intersectsBox(boundingInfo.boundingBox);
  30660. };
  30661. /**
  30662. * Returns an object IntersectionInfo.
  30663. */
  30664. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30665. var intersectInfo = null;
  30666. // LineMesh first as it's also a Mesh...
  30667. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30668. var lineMesh = this._mesh;
  30669. // Line test
  30670. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30671. var p0 = positions[indices[index]];
  30672. var p1 = positions[indices[index + 1]];
  30673. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30674. if (length < 0) {
  30675. continue;
  30676. }
  30677. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30678. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30679. if (fastCheck) {
  30680. break;
  30681. }
  30682. }
  30683. }
  30684. }
  30685. else {
  30686. // Triangles test
  30687. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30688. var p0 = positions[indices[index]];
  30689. var p1 = positions[indices[index + 1]];
  30690. var p2 = positions[indices[index + 2]];
  30691. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30692. if (currentIntersectInfo) {
  30693. if (currentIntersectInfo.distance < 0) {
  30694. continue;
  30695. }
  30696. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30697. intersectInfo = currentIntersectInfo;
  30698. intersectInfo.faceId = index / 3;
  30699. if (fastCheck) {
  30700. break;
  30701. }
  30702. }
  30703. }
  30704. }
  30705. }
  30706. return intersectInfo;
  30707. };
  30708. SubMesh.prototype._rebuild = function () {
  30709. if (this._linesIndexBuffer) {
  30710. this._linesIndexBuffer = null;
  30711. }
  30712. };
  30713. // Clone
  30714. /**
  30715. * Creates a new Submesh from the passed Mesh.
  30716. */
  30717. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30718. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30719. if (!this.IsGlobal) {
  30720. var boundingInfo = this.getBoundingInfo();
  30721. if (!boundingInfo) {
  30722. return result;
  30723. }
  30724. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30725. }
  30726. return result;
  30727. };
  30728. // Dispose
  30729. /**
  30730. * Disposes the Submesh.
  30731. * Returns nothing.
  30732. */
  30733. SubMesh.prototype.dispose = function () {
  30734. if (this._linesIndexBuffer) {
  30735. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30736. this._linesIndexBuffer = null;
  30737. }
  30738. // Remove from mesh
  30739. var index = this._mesh.subMeshes.indexOf(this);
  30740. this._mesh.subMeshes.splice(index, 1);
  30741. };
  30742. // Statics
  30743. /**
  30744. * Creates a new Submesh from the passed parameters :
  30745. * - materialIndex (integer) : the index of the main mesh material.
  30746. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30747. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30748. * - mesh (Mesh) : the main mesh to create the submesh from.
  30749. * - renderingMesh (optional Mesh) : rendering mesh.
  30750. */
  30751. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30752. var minVertexIndex = Number.MAX_VALUE;
  30753. var maxVertexIndex = -Number.MAX_VALUE;
  30754. renderingMesh = (renderingMesh || mesh);
  30755. var indices = renderingMesh.getIndices();
  30756. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30757. var vertexIndex = indices[index];
  30758. if (vertexIndex < minVertexIndex)
  30759. minVertexIndex = vertexIndex;
  30760. if (vertexIndex > maxVertexIndex)
  30761. maxVertexIndex = vertexIndex;
  30762. }
  30763. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30764. };
  30765. return SubMesh;
  30766. }(BaseSubMesh));
  30767. BABYLON.SubMesh = SubMesh;
  30768. })(BABYLON || (BABYLON = {}));
  30769. //# sourceMappingURL=babylon.subMesh.js.map
  30770. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30771. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30772. s = arguments[i];
  30773. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30774. t[p] = s[p];
  30775. }
  30776. return t;
  30777. };
  30778. var BABYLON;
  30779. (function (BABYLON) {
  30780. /**
  30781. * Manages the defines for the Material.
  30782. */
  30783. var MaterialDefines = /** @class */ (function () {
  30784. function MaterialDefines() {
  30785. this._isDirty = true;
  30786. this._areLightsDirty = true;
  30787. this._areAttributesDirty = true;
  30788. this._areTexturesDirty = true;
  30789. this._areFresnelDirty = true;
  30790. this._areMiscDirty = true;
  30791. this._areImageProcessingDirty = true;
  30792. this._normals = false;
  30793. this._uvs = false;
  30794. this._needNormals = false;
  30795. this._needUVs = false;
  30796. }
  30797. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30798. /**
  30799. * Specifies if the material needs to be re-calculated.
  30800. */
  30801. get: function () {
  30802. return this._isDirty;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. /**
  30808. * Marks the material to indicate that it has been re-calculated.
  30809. */
  30810. MaterialDefines.prototype.markAsProcessed = function () {
  30811. this._isDirty = false;
  30812. this._areAttributesDirty = false;
  30813. this._areTexturesDirty = false;
  30814. this._areFresnelDirty = false;
  30815. this._areLightsDirty = false;
  30816. this._areMiscDirty = false;
  30817. this._areImageProcessingDirty = false;
  30818. };
  30819. /**
  30820. * Marks the material to indicate that it needs to be re-calculated.
  30821. */
  30822. MaterialDefines.prototype.markAsUnprocessed = function () {
  30823. this._isDirty = true;
  30824. };
  30825. /**
  30826. * Marks the material to indicate all of its defines need to be re-calculated.
  30827. */
  30828. MaterialDefines.prototype.markAllAsDirty = function () {
  30829. this._areTexturesDirty = true;
  30830. this._areAttributesDirty = true;
  30831. this._areLightsDirty = true;
  30832. this._areFresnelDirty = true;
  30833. this._areMiscDirty = true;
  30834. this._areImageProcessingDirty = true;
  30835. this._isDirty = true;
  30836. };
  30837. /**
  30838. * Marks the material to indicate that image processing needs to be re-calculated.
  30839. */
  30840. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30841. this._areImageProcessingDirty = true;
  30842. this._isDirty = true;
  30843. };
  30844. /**
  30845. * Marks the material to indicate the lights need to be re-calculated.
  30846. */
  30847. MaterialDefines.prototype.markAsLightDirty = function () {
  30848. this._areLightsDirty = true;
  30849. this._isDirty = true;
  30850. };
  30851. /**
  30852. * Marks the attribute state as changed.
  30853. */
  30854. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30855. this._areAttributesDirty = true;
  30856. this._isDirty = true;
  30857. };
  30858. /**
  30859. * Marks the texture state as changed.
  30860. */
  30861. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30862. this._areTexturesDirty = true;
  30863. this._isDirty = true;
  30864. };
  30865. /**
  30866. * Marks the fresnel state as changed.
  30867. */
  30868. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30869. this._areFresnelDirty = true;
  30870. this._isDirty = true;
  30871. };
  30872. /**
  30873. * Marks the misc state as changed.
  30874. */
  30875. MaterialDefines.prototype.markAsMiscDirty = function () {
  30876. this._areMiscDirty = true;
  30877. this._isDirty = true;
  30878. };
  30879. /**
  30880. * Rebuilds the material defines.
  30881. */
  30882. MaterialDefines.prototype.rebuild = function () {
  30883. if (this._keys) {
  30884. delete this._keys;
  30885. }
  30886. this._keys = [];
  30887. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30888. var key = _a[_i];
  30889. if (key[0] === "_") {
  30890. continue;
  30891. }
  30892. this._keys.push(key);
  30893. }
  30894. };
  30895. /**
  30896. * Specifies if two material defines are equal.
  30897. * @param other - A material define instance to compare to.
  30898. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30899. */
  30900. MaterialDefines.prototype.isEqual = function (other) {
  30901. if (this._keys.length !== other._keys.length) {
  30902. return false;
  30903. }
  30904. for (var index = 0; index < this._keys.length; index++) {
  30905. var prop = this._keys[index];
  30906. if (this[prop] !== other[prop]) {
  30907. return false;
  30908. }
  30909. }
  30910. return true;
  30911. };
  30912. /**
  30913. * Clones this instance's defines to another instance.
  30914. * @param other - material defines to clone values to.
  30915. */
  30916. MaterialDefines.prototype.cloneTo = function (other) {
  30917. if (this._keys.length !== other._keys.length) {
  30918. other._keys = this._keys.slice(0);
  30919. }
  30920. for (var index = 0; index < this._keys.length; index++) {
  30921. var prop = this._keys[index];
  30922. other[prop] = this[prop];
  30923. }
  30924. };
  30925. /**
  30926. * Resets the material define values.
  30927. */
  30928. MaterialDefines.prototype.reset = function () {
  30929. for (var index = 0; index < this._keys.length; index++) {
  30930. var prop = this._keys[index];
  30931. if (typeof (this[prop]) === "number") {
  30932. this[prop] = 0;
  30933. }
  30934. else {
  30935. this[prop] = false;
  30936. }
  30937. }
  30938. };
  30939. /**
  30940. * Converts the material define values to a string.
  30941. * @returns - String of material define information.
  30942. */
  30943. MaterialDefines.prototype.toString = function () {
  30944. var result = "";
  30945. for (var index = 0; index < this._keys.length; index++) {
  30946. var prop = this._keys[index];
  30947. var value = this[prop];
  30948. if (typeof (value) === "number") {
  30949. result += "#define " + prop + " " + this[prop] + "\n";
  30950. }
  30951. else if (value) {
  30952. result += "#define " + prop + "\n";
  30953. }
  30954. }
  30955. return result;
  30956. };
  30957. return MaterialDefines;
  30958. }());
  30959. BABYLON.MaterialDefines = MaterialDefines;
  30960. /**
  30961. * This offers the main features of a material in BJS.
  30962. */
  30963. var Material = /** @class */ (function () {
  30964. /**
  30965. * Creates a material instance.
  30966. * @param name - The name of the material.
  30967. * @param scene - The BJS scene to reference.
  30968. * @param doNotAdd - Specifies if the material should be added to the scene.
  30969. */
  30970. function Material(name, scene, doNotAdd) {
  30971. /**
  30972. * Specifies if the ready state should be checked on each call.
  30973. */
  30974. this.checkReadyOnEveryCall = false;
  30975. /**
  30976. * Specifies if the ready state should be checked once.
  30977. */
  30978. this.checkReadyOnlyOnce = false;
  30979. /**
  30980. * The state of the material.
  30981. */
  30982. this.state = "";
  30983. /**
  30984. * The alpha value of the material.
  30985. */
  30986. this._alpha = 1.0;
  30987. /**
  30988. * Specifies if back face culling is enabled.
  30989. */
  30990. this._backFaceCulling = true;
  30991. /**
  30992. * Specifies if the material should be serialized.
  30993. */
  30994. this.doNotSerialize = false;
  30995. /**
  30996. * Specifies if the effect should be stored on sub meshes.
  30997. */
  30998. this.storeEffectOnSubMeshes = false;
  30999. /**
  31000. * An event triggered when the material is disposed.
  31001. * @type {BABYLON.Observable}
  31002. */
  31003. this.onDisposeObservable = new BABYLON.Observable();
  31004. /**
  31005. * An event triggered when the material is bound.
  31006. * @type {BABYLON.Observable}
  31007. */
  31008. this.onBindObservable = new BABYLON.Observable();
  31009. /**
  31010. * An event triggered when the material is unbound.
  31011. * @type {BABYLON.Observable}
  31012. */
  31013. this.onUnBindObservable = new BABYLON.Observable();
  31014. /**
  31015. * Stores the value of the alpha mode.
  31016. */
  31017. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31018. /**
  31019. * Stores the state of the need depth pre-pass value.
  31020. */
  31021. this._needDepthPrePass = false;
  31022. /**
  31023. * Specifies if depth writing should be disabled.
  31024. */
  31025. this.disableDepthWrite = false;
  31026. /**
  31027. * Specifies if depth writing should be forced.
  31028. */
  31029. this.forceDepthWrite = false;
  31030. /**
  31031. * Specifies if there should be a separate pass for culling.
  31032. */
  31033. this.separateCullingPass = false;
  31034. /**
  31035. * Stores the state specifing if fog should be enabled.
  31036. */
  31037. this._fogEnabled = true;
  31038. /**
  31039. * Stores the size of points.
  31040. */
  31041. this.pointSize = 1.0;
  31042. /**
  31043. * Stores the z offset value.
  31044. */
  31045. this.zOffset = 0;
  31046. /**
  31047. * Specifies if the material was previously ready.
  31048. */
  31049. this._wasPreviouslyReady = false;
  31050. /**
  31051. * Stores the fill mode state.
  31052. */
  31053. this._fillMode = Material.TriangleFillMode;
  31054. this.name = name;
  31055. this.id = name || BABYLON.Tools.RandomId();
  31056. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31057. if (this._scene.useRightHandedSystem) {
  31058. this.sideOrientation = Material.ClockWiseSideOrientation;
  31059. }
  31060. else {
  31061. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31062. }
  31063. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31064. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31065. if (!doNotAdd) {
  31066. this._scene.materials.push(this);
  31067. }
  31068. }
  31069. Object.defineProperty(Material, "TriangleFillMode", {
  31070. /**
  31071. * Returns the triangle fill mode.
  31072. */
  31073. get: function () {
  31074. return Material._TriangleFillMode;
  31075. },
  31076. enumerable: true,
  31077. configurable: true
  31078. });
  31079. Object.defineProperty(Material, "WireFrameFillMode", {
  31080. /**
  31081. * Returns the wireframe mode.
  31082. */
  31083. get: function () {
  31084. return Material._WireFrameFillMode;
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. Object.defineProperty(Material, "PointFillMode", {
  31090. /**
  31091. * Returns the point fill mode.
  31092. */
  31093. get: function () {
  31094. return Material._PointFillMode;
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. Object.defineProperty(Material, "PointListDrawMode", {
  31100. /**
  31101. * Returns the point list draw mode.
  31102. */
  31103. get: function () {
  31104. return Material._PointListDrawMode;
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Material, "LineListDrawMode", {
  31110. /**
  31111. * Returns the line list draw mode.
  31112. */
  31113. get: function () {
  31114. return Material._LineListDrawMode;
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. Object.defineProperty(Material, "LineLoopDrawMode", {
  31120. /**
  31121. * Returns the line loop draw mode.
  31122. */
  31123. get: function () {
  31124. return Material._LineLoopDrawMode;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Object.defineProperty(Material, "LineStripDrawMode", {
  31130. /**
  31131. * Returns the line strip draw mode.
  31132. */
  31133. get: function () {
  31134. return Material._LineStripDrawMode;
  31135. },
  31136. enumerable: true,
  31137. configurable: true
  31138. });
  31139. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31140. /**
  31141. * Returns the triangle strip draw mode.
  31142. */
  31143. get: function () {
  31144. return Material._TriangleStripDrawMode;
  31145. },
  31146. enumerable: true,
  31147. configurable: true
  31148. });
  31149. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31150. /**
  31151. * Returns the triangle fan draw mode.
  31152. */
  31153. get: function () {
  31154. return Material._TriangleFanDrawMode;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31160. /**
  31161. * Returns the clock-wise side orientation.
  31162. */
  31163. get: function () {
  31164. return Material._ClockWiseSideOrientation;
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31170. /**
  31171. * Returns the counter clock-wise side orientation.
  31172. */
  31173. get: function () {
  31174. return Material._CounterClockWiseSideOrientation;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(Material, "TextureDirtyFlag", {
  31180. /**
  31181. * Returns the dirty texture flag value.
  31182. */
  31183. get: function () {
  31184. return Material._TextureDirtyFlag;
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Object.defineProperty(Material, "LightDirtyFlag", {
  31190. /**
  31191. * Returns the dirty light flag value.
  31192. */
  31193. get: function () {
  31194. return Material._LightDirtyFlag;
  31195. },
  31196. enumerable: true,
  31197. configurable: true
  31198. });
  31199. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31200. /**
  31201. * Returns the dirty fresnel flag value.
  31202. */
  31203. get: function () {
  31204. return Material._FresnelDirtyFlag;
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31210. /**
  31211. * Returns the dirty attributes flag value.
  31212. */
  31213. get: function () {
  31214. return Material._AttributesDirtyFlag;
  31215. },
  31216. enumerable: true,
  31217. configurable: true
  31218. });
  31219. Object.defineProperty(Material, "MiscDirtyFlag", {
  31220. /**
  31221. * Returns the dirty misc flag value.
  31222. */
  31223. get: function () {
  31224. return Material._MiscDirtyFlag;
  31225. },
  31226. enumerable: true,
  31227. configurable: true
  31228. });
  31229. Object.defineProperty(Material.prototype, "alpha", {
  31230. /**
  31231. * Gets the alpha value of the material.
  31232. */
  31233. get: function () {
  31234. return this._alpha;
  31235. },
  31236. /**
  31237. * Sets the alpha value of the material.
  31238. */
  31239. set: function (value) {
  31240. if (this._alpha === value) {
  31241. return;
  31242. }
  31243. this._alpha = value;
  31244. this.markAsDirty(Material.MiscDirtyFlag);
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31250. /**
  31251. * Gets the back-face culling state.
  31252. */
  31253. get: function () {
  31254. return this._backFaceCulling;
  31255. },
  31256. /**
  31257. * Sets the back-face culling state.
  31258. */
  31259. set: function (value) {
  31260. if (this._backFaceCulling === value) {
  31261. return;
  31262. }
  31263. this._backFaceCulling = value;
  31264. this.markAsDirty(Material.TextureDirtyFlag);
  31265. },
  31266. enumerable: true,
  31267. configurable: true
  31268. });
  31269. Object.defineProperty(Material.prototype, "onDispose", {
  31270. /**
  31271. * Called during a dispose event.
  31272. */
  31273. set: function (callback) {
  31274. if (this._onDisposeObserver) {
  31275. this.onDisposeObservable.remove(this._onDisposeObserver);
  31276. }
  31277. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31278. },
  31279. enumerable: true,
  31280. configurable: true
  31281. });
  31282. Object.defineProperty(Material.prototype, "onBind", {
  31283. /**
  31284. * Called during a bind event.
  31285. */
  31286. set: function (callback) {
  31287. if (this._onBindObserver) {
  31288. this.onBindObservable.remove(this._onBindObserver);
  31289. }
  31290. this._onBindObserver = this.onBindObservable.add(callback);
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(Material.prototype, "alphaMode", {
  31296. /**
  31297. * Gets the value of the alpha mode.
  31298. */
  31299. get: function () {
  31300. return this._alphaMode;
  31301. },
  31302. /**
  31303. * Sets the value of the alpha mode.
  31304. */
  31305. set: function (value) {
  31306. if (this._alphaMode === value) {
  31307. return;
  31308. }
  31309. this._alphaMode = value;
  31310. this.markAsDirty(Material.TextureDirtyFlag);
  31311. },
  31312. enumerable: true,
  31313. configurable: true
  31314. });
  31315. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31316. /**
  31317. * Gets the depth pre-pass value.
  31318. */
  31319. get: function () {
  31320. return this._needDepthPrePass;
  31321. },
  31322. /**
  31323. * Sets the need depth pre-pass value.
  31324. */
  31325. set: function (value) {
  31326. if (this._needDepthPrePass === value) {
  31327. return;
  31328. }
  31329. this._needDepthPrePass = value;
  31330. if (this._needDepthPrePass) {
  31331. this.checkReadyOnEveryCall = true;
  31332. }
  31333. },
  31334. enumerable: true,
  31335. configurable: true
  31336. });
  31337. Object.defineProperty(Material.prototype, "fogEnabled", {
  31338. /**
  31339. * Gets the value of the fog enabled state.
  31340. */
  31341. get: function () {
  31342. return this._fogEnabled;
  31343. },
  31344. /**
  31345. * Sets the state for enabling fog.
  31346. */
  31347. set: function (value) {
  31348. if (this._fogEnabled === value) {
  31349. return;
  31350. }
  31351. this._fogEnabled = value;
  31352. this.markAsDirty(Material.MiscDirtyFlag);
  31353. },
  31354. enumerable: true,
  31355. configurable: true
  31356. });
  31357. Object.defineProperty(Material.prototype, "wireframe", {
  31358. /**
  31359. * Gets a value specifying if wireframe mode is enabled.
  31360. */
  31361. get: function () {
  31362. return this._fillMode === Material.WireFrameFillMode;
  31363. },
  31364. /**
  31365. * Sets the state of wireframe mode.
  31366. */
  31367. set: function (value) {
  31368. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. Object.defineProperty(Material.prototype, "pointsCloud", {
  31374. /**
  31375. * Gets the value specifying if point clouds are enabled.
  31376. */
  31377. get: function () {
  31378. return this._fillMode === Material.PointFillMode;
  31379. },
  31380. /**
  31381. * Sets the state of point cloud mode.
  31382. */
  31383. set: function (value) {
  31384. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31385. },
  31386. enumerable: true,
  31387. configurable: true
  31388. });
  31389. Object.defineProperty(Material.prototype, "fillMode", {
  31390. /**
  31391. * Gets the material fill mode.
  31392. */
  31393. get: function () {
  31394. return this._fillMode;
  31395. },
  31396. /**
  31397. * Sets the material fill mode.
  31398. */
  31399. set: function (value) {
  31400. if (this._fillMode === value) {
  31401. return;
  31402. }
  31403. this._fillMode = value;
  31404. this.markAsDirty(Material.MiscDirtyFlag);
  31405. },
  31406. enumerable: true,
  31407. configurable: true
  31408. });
  31409. /**
  31410. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31411. * subclasses should override adding information pertainent to themselves.
  31412. * @returns - String with material information.
  31413. */
  31414. Material.prototype.toString = function (fullDetails) {
  31415. var ret = "Name: " + this.name;
  31416. if (fullDetails) {
  31417. }
  31418. return ret;
  31419. };
  31420. /**
  31421. * Gets the class name of the material.
  31422. * @returns - String with the class name of the material.
  31423. */
  31424. Material.prototype.getClassName = function () {
  31425. return "Material";
  31426. };
  31427. Object.defineProperty(Material.prototype, "isFrozen", {
  31428. /**
  31429. * Specifies if updates for the material been locked.
  31430. */
  31431. get: function () {
  31432. return this.checkReadyOnlyOnce;
  31433. },
  31434. enumerable: true,
  31435. configurable: true
  31436. });
  31437. /**
  31438. * Locks updates for the material.
  31439. */
  31440. Material.prototype.freeze = function () {
  31441. this.checkReadyOnlyOnce = true;
  31442. };
  31443. /**
  31444. * Unlocks updates for the material.
  31445. */
  31446. Material.prototype.unfreeze = function () {
  31447. this.checkReadyOnlyOnce = false;
  31448. };
  31449. /**
  31450. * Specifies if the material is ready to be used.
  31451. * @param mesh - BJS mesh.
  31452. * @param useInstances - Specifies if instances should be used.
  31453. * @returns - Boolean indicating if the material is ready to be used.
  31454. */
  31455. Material.prototype.isReady = function (mesh, useInstances) {
  31456. return true;
  31457. };
  31458. /**
  31459. * Specifies that the submesh is ready to be used.
  31460. * @param mesh - BJS mesh.
  31461. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31462. * @param useInstances - Specifies that instances should be used.
  31463. * @returns - boolean indicating that the submesh is ready or not.
  31464. */
  31465. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31466. return false;
  31467. };
  31468. /**
  31469. * Returns the material effect.
  31470. * @returns - Nullable material effect.
  31471. */
  31472. Material.prototype.getEffect = function () {
  31473. return this._effect;
  31474. };
  31475. /**
  31476. * Returns the BJS scene.
  31477. * @returns - BJS Scene.
  31478. */
  31479. Material.prototype.getScene = function () {
  31480. return this._scene;
  31481. };
  31482. /**
  31483. * Specifies if the material will require alpha blending
  31484. * @returns - Boolean specifying if alpha blending is needed.
  31485. */
  31486. Material.prototype.needAlphaBlending = function () {
  31487. return (this.alpha < 1.0);
  31488. };
  31489. /**
  31490. * Specifies if the mesh will require alpha blending.
  31491. * @param mesh - BJS mesh.
  31492. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31493. */
  31494. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31495. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31496. };
  31497. /**
  31498. * Specifies if this material should be rendered in alpha test mode.
  31499. * @returns - Boolean specifying if an alpha test is needed.
  31500. */
  31501. Material.prototype.needAlphaTesting = function () {
  31502. return false;
  31503. };
  31504. /**
  31505. * Gets the texture used for the alpha test.
  31506. * @returns - Nullable alpha test texture.
  31507. */
  31508. Material.prototype.getAlphaTestTexture = function () {
  31509. return null;
  31510. };
  31511. /**
  31512. * Marks the material to indicate that it needs to be re-calculated.
  31513. */
  31514. Material.prototype.markDirty = function () {
  31515. this._wasPreviouslyReady = false;
  31516. };
  31517. Material.prototype._preBind = function (effect, overrideOrientation) {
  31518. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31519. var engine = this._scene.getEngine();
  31520. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31521. var reverse = orientation === Material.ClockWiseSideOrientation;
  31522. engine.enableEffect(effect ? effect : this._effect);
  31523. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31524. return reverse;
  31525. };
  31526. /**
  31527. * Binds the material to the mesh.
  31528. * @param world - World transformation matrix.
  31529. * @param mesh - Mesh to bind the material to.
  31530. */
  31531. Material.prototype.bind = function (world, mesh) {
  31532. };
  31533. /**
  31534. * Binds the submesh to the material.
  31535. * @param world - World transformation matrix.
  31536. * @param mesh - Mesh containing the submesh.
  31537. * @param subMesh - Submesh to bind the material to.
  31538. */
  31539. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31540. };
  31541. /**
  31542. * Binds the world matrix to the material.
  31543. * @param world - World transformation matrix.
  31544. */
  31545. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31546. };
  31547. /**
  31548. * Binds the scene's uniform buffer to the effect.
  31549. * @param effect - Effect to bind to the scene uniform buffer.
  31550. * @param sceneUbo - Scene uniform buffer.
  31551. */
  31552. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31553. sceneUbo.bindToEffect(effect, "Scene");
  31554. };
  31555. /**
  31556. * Binds the view matrix to the effect.
  31557. * @param effect - Effect to bind the view matrix to.
  31558. */
  31559. Material.prototype.bindView = function (effect) {
  31560. if (!this._useUBO) {
  31561. effect.setMatrix("view", this.getScene().getViewMatrix());
  31562. }
  31563. else {
  31564. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31565. }
  31566. };
  31567. /**
  31568. * Binds the view projection matrix to the effect.
  31569. * @param effect - Effect to bind the view projection matrix to.
  31570. */
  31571. Material.prototype.bindViewProjection = function (effect) {
  31572. if (!this._useUBO) {
  31573. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31574. }
  31575. else {
  31576. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31577. }
  31578. };
  31579. /**
  31580. * Specifies if material alpha testing should be turned on for the mesh.
  31581. * @param mesh - BJS mesh.
  31582. */
  31583. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31584. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31585. };
  31586. /**
  31587. * Processes to execute after binding the material to a mesh.
  31588. * @param mesh - BJS mesh.
  31589. */
  31590. Material.prototype._afterBind = function (mesh) {
  31591. this._scene._cachedMaterial = this;
  31592. if (mesh) {
  31593. this._scene._cachedVisibility = mesh.visibility;
  31594. }
  31595. else {
  31596. this._scene._cachedVisibility = 1;
  31597. }
  31598. if (mesh) {
  31599. this.onBindObservable.notifyObservers(mesh);
  31600. }
  31601. if (this.disableDepthWrite) {
  31602. var engine = this._scene.getEngine();
  31603. this._cachedDepthWriteState = engine.getDepthWrite();
  31604. engine.setDepthWrite(false);
  31605. }
  31606. };
  31607. /**
  31608. * Unbinds the material from the mesh.
  31609. */
  31610. Material.prototype.unbind = function () {
  31611. this.onUnBindObservable.notifyObservers(this);
  31612. if (this.disableDepthWrite) {
  31613. var engine = this._scene.getEngine();
  31614. engine.setDepthWrite(this._cachedDepthWriteState);
  31615. }
  31616. };
  31617. /**
  31618. * Gets the active textures from the material.
  31619. * @returns - Array of textures.
  31620. */
  31621. Material.prototype.getActiveTextures = function () {
  31622. return [];
  31623. };
  31624. /**
  31625. * Specifies if the material uses a texture.
  31626. * @param texture - Texture to check against the material.
  31627. * @returns - Boolean specifying if the material uses the texture.
  31628. */
  31629. Material.prototype.hasTexture = function (texture) {
  31630. return false;
  31631. };
  31632. /**
  31633. * Makes a duplicate of the material, and gives it a new name.
  31634. * @param name - Name to call the duplicated material.
  31635. * @returns - Nullable cloned material
  31636. */
  31637. Material.prototype.clone = function (name) {
  31638. return null;
  31639. };
  31640. /**
  31641. * Gets the meshes bound to the material.
  31642. * @returns - Array of meshes bound to the material.
  31643. */
  31644. Material.prototype.getBindedMeshes = function () {
  31645. var result = new Array();
  31646. for (var index = 0; index < this._scene.meshes.length; index++) {
  31647. var mesh = this._scene.meshes[index];
  31648. if (mesh.material === this) {
  31649. result.push(mesh);
  31650. }
  31651. }
  31652. return result;
  31653. };
  31654. /**
  31655. * Force shader compilation
  31656. * @param mesh - BJS mesh.
  31657. * @param onCompiled - function to execute once the material is compiled.
  31658. * @param options - options to pass to this function.
  31659. */
  31660. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31661. var _this = this;
  31662. var localOptions = __assign({ clipPlane: false }, options);
  31663. var subMesh = new BABYLON.BaseSubMesh();
  31664. var scene = this.getScene();
  31665. var checkReady = function () {
  31666. if (!_this._scene || !_this._scene.getEngine()) {
  31667. return;
  31668. }
  31669. if (subMesh._materialDefines) {
  31670. subMesh._materialDefines._renderId = -1;
  31671. }
  31672. var clipPlaneState = scene.clipPlane;
  31673. if (localOptions.clipPlane) {
  31674. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31675. }
  31676. if (_this.storeEffectOnSubMeshes) {
  31677. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31678. if (onCompiled) {
  31679. onCompiled(_this);
  31680. }
  31681. }
  31682. else {
  31683. setTimeout(checkReady, 16);
  31684. }
  31685. }
  31686. else {
  31687. if (_this.isReady(mesh)) {
  31688. if (onCompiled) {
  31689. onCompiled(_this);
  31690. }
  31691. }
  31692. else {
  31693. setTimeout(checkReady, 16);
  31694. }
  31695. }
  31696. if (localOptions.clipPlane) {
  31697. scene.clipPlane = clipPlaneState;
  31698. }
  31699. };
  31700. checkReady();
  31701. };
  31702. /**
  31703. * Force shader compilation.
  31704. * @param mesh The mesh that will use this material
  31705. * @param options Additional options for compiling the shaders
  31706. * @returns A promise that resolves when the compilation completes
  31707. */
  31708. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31709. var _this = this;
  31710. return new Promise(function (resolve) {
  31711. _this.forceCompilation(mesh, function () {
  31712. resolve();
  31713. }, options);
  31714. });
  31715. };
  31716. /**
  31717. * Marks a define in the material to indicate that it needs to be re-computed.
  31718. * @param flag - Material define flag.
  31719. */
  31720. Material.prototype.markAsDirty = function (flag) {
  31721. if (flag & Material.TextureDirtyFlag) {
  31722. this._markAllSubMeshesAsTexturesDirty();
  31723. }
  31724. if (flag & Material.LightDirtyFlag) {
  31725. this._markAllSubMeshesAsLightsDirty();
  31726. }
  31727. if (flag & Material.FresnelDirtyFlag) {
  31728. this._markAllSubMeshesAsFresnelDirty();
  31729. }
  31730. if (flag & Material.AttributesDirtyFlag) {
  31731. this._markAllSubMeshesAsAttributesDirty();
  31732. }
  31733. if (flag & Material.MiscDirtyFlag) {
  31734. this._markAllSubMeshesAsMiscDirty();
  31735. }
  31736. this.getScene().resetCachedMaterial();
  31737. };
  31738. /**
  31739. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31740. * @param func - function which checks material defines against the submeshes.
  31741. */
  31742. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31743. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31744. var mesh = _a[_i];
  31745. if (!mesh.subMeshes) {
  31746. continue;
  31747. }
  31748. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31749. var subMesh = _c[_b];
  31750. if (subMesh.getMaterial() !== this) {
  31751. continue;
  31752. }
  31753. if (!subMesh._materialDefines) {
  31754. continue;
  31755. }
  31756. func(subMesh._materialDefines);
  31757. }
  31758. }
  31759. };
  31760. /**
  31761. * Indicates that image processing needs to be re-calculated for all submeshes.
  31762. */
  31763. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31764. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31765. };
  31766. /**
  31767. * Indicates that textures need to be re-calculated for all submeshes.
  31768. */
  31769. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31770. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31771. };
  31772. /**
  31773. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31774. */
  31775. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31777. };
  31778. /**
  31779. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31780. */
  31781. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31782. this._markAllSubMeshesAsDirty(function (defines) {
  31783. defines.markAsFresnelDirty();
  31784. defines.markAsMiscDirty();
  31785. });
  31786. };
  31787. /**
  31788. * Indicates that lights need to be re-calculated for all submeshes.
  31789. */
  31790. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31791. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31792. };
  31793. /**
  31794. * Indicates that attributes need to be re-calculated for all submeshes.
  31795. */
  31796. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31797. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31798. };
  31799. /**
  31800. * Indicates that misc needs to be re-calculated for all submeshes.
  31801. */
  31802. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31803. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31804. };
  31805. /**
  31806. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31807. */
  31808. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31809. this._markAllSubMeshesAsDirty(function (defines) {
  31810. defines.markAsTexturesDirty();
  31811. defines.markAsMiscDirty();
  31812. });
  31813. };
  31814. /**
  31815. * Disposes the material.
  31816. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31817. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31818. */
  31819. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31820. // Animations
  31821. this.getScene().stopAnimation(this);
  31822. this.getScene().freeProcessedMaterials();
  31823. // Remove from scene
  31824. var index = this._scene.materials.indexOf(this);
  31825. if (index >= 0) {
  31826. this._scene.materials.splice(index, 1);
  31827. }
  31828. // Remove from meshes
  31829. for (index = 0; index < this._scene.meshes.length; index++) {
  31830. var mesh = this._scene.meshes[index];
  31831. if (mesh.material === this) {
  31832. mesh.material = null;
  31833. if (mesh.geometry) {
  31834. var geometry = (mesh.geometry);
  31835. if (this.storeEffectOnSubMeshes) {
  31836. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31837. var subMesh = _a[_i];
  31838. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31839. if (forceDisposeEffect && subMesh._materialEffect) {
  31840. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31841. }
  31842. }
  31843. }
  31844. else {
  31845. geometry._releaseVertexArrayObject(this._effect);
  31846. }
  31847. }
  31848. }
  31849. }
  31850. this._uniformBuffer.dispose();
  31851. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31852. if (forceDisposeEffect && this._effect) {
  31853. if (!this.storeEffectOnSubMeshes) {
  31854. this._scene.getEngine()._releaseEffect(this._effect);
  31855. }
  31856. this._effect = null;
  31857. }
  31858. // Callback
  31859. this.onDisposeObservable.notifyObservers(this);
  31860. this.onDisposeObservable.clear();
  31861. this.onBindObservable.clear();
  31862. this.onUnBindObservable.clear();
  31863. };
  31864. /**
  31865. * Serializes this material.
  31866. * @returns - serialized material object.
  31867. */
  31868. Material.prototype.serialize = function () {
  31869. return BABYLON.SerializationHelper.Serialize(this);
  31870. };
  31871. /**
  31872. * Creates a MultiMaterial from parse MultiMaterial data.
  31873. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31874. * @param scene - BJS scene.
  31875. * @returns - MultiMaterial.
  31876. */
  31877. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31878. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31879. multiMaterial.id = parsedMultiMaterial.id;
  31880. if (BABYLON.Tags) {
  31881. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31882. }
  31883. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31884. var subMatId = parsedMultiMaterial.materials[matIndex];
  31885. if (subMatId) {
  31886. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31887. }
  31888. else {
  31889. multiMaterial.subMaterials.push(null);
  31890. }
  31891. }
  31892. return multiMaterial;
  31893. };
  31894. /**
  31895. * Creates a material from parsed material data.
  31896. * @param parsedMaterial - Parsed material data.
  31897. * @param scene - BJS scene.
  31898. * @param rootUrl - Root URL containing the material information.
  31899. * @returns - Parsed material.
  31900. */
  31901. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31902. if (!parsedMaterial.customType) {
  31903. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31904. }
  31905. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31906. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31907. if (!BABYLON.LegacyPBRMaterial) {
  31908. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31909. return;
  31910. }
  31911. }
  31912. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31913. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31914. ;
  31915. };
  31916. // Triangle views
  31917. Material._TriangleFillMode = 0;
  31918. Material._WireFrameFillMode = 1;
  31919. Material._PointFillMode = 2;
  31920. // Draw modes
  31921. Material._PointListDrawMode = 3;
  31922. Material._LineListDrawMode = 4;
  31923. Material._LineLoopDrawMode = 5;
  31924. Material._LineStripDrawMode = 6;
  31925. Material._TriangleStripDrawMode = 7;
  31926. Material._TriangleFanDrawMode = 8;
  31927. /**
  31928. * Stores the clock-wise side orientation.
  31929. */
  31930. Material._ClockWiseSideOrientation = 0;
  31931. /**
  31932. * Stores the counter clock-wise side orientation.
  31933. */
  31934. Material._CounterClockWiseSideOrientation = 1;
  31935. /**
  31936. * The dirty texture flag value.
  31937. */
  31938. Material._TextureDirtyFlag = 1;
  31939. /**
  31940. * The dirty light flag value.
  31941. */
  31942. Material._LightDirtyFlag = 2;
  31943. /**
  31944. * The dirty fresnel flag value.
  31945. */
  31946. Material._FresnelDirtyFlag = 4;
  31947. /**
  31948. * The dirty attribute flag value.
  31949. */
  31950. Material._AttributesDirtyFlag = 8;
  31951. /**
  31952. * The dirty misc flag value.
  31953. */
  31954. Material._MiscDirtyFlag = 16;
  31955. __decorate([
  31956. BABYLON.serialize()
  31957. ], Material.prototype, "id", void 0);
  31958. __decorate([
  31959. BABYLON.serialize()
  31960. ], Material.prototype, "name", void 0);
  31961. __decorate([
  31962. BABYLON.serialize()
  31963. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31964. __decorate([
  31965. BABYLON.serialize()
  31966. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31967. __decorate([
  31968. BABYLON.serialize()
  31969. ], Material.prototype, "state", void 0);
  31970. __decorate([
  31971. BABYLON.serialize("alpha")
  31972. ], Material.prototype, "_alpha", void 0);
  31973. __decorate([
  31974. BABYLON.serialize("backFaceCulling")
  31975. ], Material.prototype, "_backFaceCulling", void 0);
  31976. __decorate([
  31977. BABYLON.serialize()
  31978. ], Material.prototype, "sideOrientation", void 0);
  31979. __decorate([
  31980. BABYLON.serialize("alphaMode")
  31981. ], Material.prototype, "_alphaMode", void 0);
  31982. __decorate([
  31983. BABYLON.serialize()
  31984. ], Material.prototype, "_needDepthPrePass", void 0);
  31985. __decorate([
  31986. BABYLON.serialize()
  31987. ], Material.prototype, "disableDepthWrite", void 0);
  31988. __decorate([
  31989. BABYLON.serialize()
  31990. ], Material.prototype, "forceDepthWrite", void 0);
  31991. __decorate([
  31992. BABYLON.serialize()
  31993. ], Material.prototype, "separateCullingPass", void 0);
  31994. __decorate([
  31995. BABYLON.serialize("fogEnabled")
  31996. ], Material.prototype, "_fogEnabled", void 0);
  31997. __decorate([
  31998. BABYLON.serialize()
  31999. ], Material.prototype, "pointSize", void 0);
  32000. __decorate([
  32001. BABYLON.serialize()
  32002. ], Material.prototype, "zOffset", void 0);
  32003. __decorate([
  32004. BABYLON.serialize()
  32005. ], Material.prototype, "wireframe", null);
  32006. __decorate([
  32007. BABYLON.serialize()
  32008. ], Material.prototype, "pointsCloud", null);
  32009. __decorate([
  32010. BABYLON.serialize()
  32011. ], Material.prototype, "fillMode", null);
  32012. return Material;
  32013. }());
  32014. BABYLON.Material = Material;
  32015. })(BABYLON || (BABYLON = {}));
  32016. //# sourceMappingURL=babylon.material.js.map
  32017. var BABYLON;
  32018. (function (BABYLON) {
  32019. var UniformBuffer = /** @class */ (function () {
  32020. /**
  32021. * Uniform buffer objects.
  32022. *
  32023. * Handles blocks of uniform on the GPU.
  32024. *
  32025. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32026. *
  32027. * For more information, please refer to :
  32028. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32029. */
  32030. function UniformBuffer(engine, data, dynamic) {
  32031. this._engine = engine;
  32032. this._noUBO = !engine.supportsUniformBuffers;
  32033. this._dynamic = dynamic;
  32034. this._data = data || [];
  32035. this._uniformLocations = {};
  32036. this._uniformSizes = {};
  32037. this._uniformLocationPointer = 0;
  32038. this._needSync = false;
  32039. if (this._noUBO) {
  32040. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32041. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32042. this.updateFloat = this._updateFloatForEffect;
  32043. this.updateFloat2 = this._updateFloat2ForEffect;
  32044. this.updateFloat3 = this._updateFloat3ForEffect;
  32045. this.updateFloat4 = this._updateFloat4ForEffect;
  32046. this.updateMatrix = this._updateMatrixForEffect;
  32047. this.updateVector3 = this._updateVector3ForEffect;
  32048. this.updateVector4 = this._updateVector4ForEffect;
  32049. this.updateColor3 = this._updateColor3ForEffect;
  32050. this.updateColor4 = this._updateColor4ForEffect;
  32051. }
  32052. else {
  32053. this._engine._uniformBuffers.push(this);
  32054. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32055. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32056. this.updateFloat = this._updateFloatForUniform;
  32057. this.updateFloat2 = this._updateFloat2ForUniform;
  32058. this.updateFloat3 = this._updateFloat3ForUniform;
  32059. this.updateFloat4 = this._updateFloat4ForUniform;
  32060. this.updateMatrix = this._updateMatrixForUniform;
  32061. this.updateVector3 = this._updateVector3ForUniform;
  32062. this.updateVector4 = this._updateVector4ForUniform;
  32063. this.updateColor3 = this._updateColor3ForUniform;
  32064. this.updateColor4 = this._updateColor4ForUniform;
  32065. }
  32066. }
  32067. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32068. // Properties
  32069. /**
  32070. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32071. * or just falling back on setUniformXXX calls.
  32072. */
  32073. get: function () {
  32074. return !this._noUBO;
  32075. },
  32076. enumerable: true,
  32077. configurable: true
  32078. });
  32079. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32080. /**
  32081. * Indicates if the WebGL underlying uniform buffer is in sync
  32082. * with the javascript cache data.
  32083. */
  32084. get: function () {
  32085. return !this._needSync;
  32086. },
  32087. enumerable: true,
  32088. configurable: true
  32089. });
  32090. /**
  32091. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32092. * Also, a dynamic UniformBuffer will disable cache verification and always
  32093. * update the underlying WebGL uniform buffer to the GPU.
  32094. */
  32095. UniformBuffer.prototype.isDynamic = function () {
  32096. return this._dynamic !== undefined;
  32097. };
  32098. /**
  32099. * The data cache on JS side.
  32100. */
  32101. UniformBuffer.prototype.getData = function () {
  32102. return this._bufferData;
  32103. };
  32104. /**
  32105. * The underlying WebGL Uniform buffer.
  32106. */
  32107. UniformBuffer.prototype.getBuffer = function () {
  32108. return this._buffer;
  32109. };
  32110. /**
  32111. * std140 layout specifies how to align data within an UBO structure.
  32112. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32113. * for specs.
  32114. */
  32115. UniformBuffer.prototype._fillAlignment = function (size) {
  32116. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32117. // and 4x4 matrices
  32118. // TODO : change if other types are used
  32119. var alignment;
  32120. if (size <= 2) {
  32121. alignment = size;
  32122. }
  32123. else {
  32124. alignment = 4;
  32125. }
  32126. if ((this._uniformLocationPointer % alignment) !== 0) {
  32127. var oldPointer = this._uniformLocationPointer;
  32128. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32129. var diff = this._uniformLocationPointer - oldPointer;
  32130. for (var i = 0; i < diff; i++) {
  32131. this._data.push(0);
  32132. }
  32133. }
  32134. };
  32135. /**
  32136. * Adds an uniform in the buffer.
  32137. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32138. * for the layout to be correct !
  32139. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32140. * @param {number|number[]} size Data size, or data directly.
  32141. */
  32142. UniformBuffer.prototype.addUniform = function (name, size) {
  32143. if (this._noUBO) {
  32144. return;
  32145. }
  32146. if (this._uniformLocations[name] !== undefined) {
  32147. // Already existing uniform
  32148. return;
  32149. }
  32150. // This function must be called in the order of the shader layout !
  32151. // size can be the size of the uniform, or data directly
  32152. var data;
  32153. if (size instanceof Array) {
  32154. data = size;
  32155. size = data.length;
  32156. }
  32157. else {
  32158. size = size;
  32159. data = [];
  32160. // Fill with zeros
  32161. for (var i = 0; i < size; i++) {
  32162. data.push(0);
  32163. }
  32164. }
  32165. this._fillAlignment(size);
  32166. this._uniformSizes[name] = size;
  32167. this._uniformLocations[name] = this._uniformLocationPointer;
  32168. this._uniformLocationPointer += size;
  32169. for (var i = 0; i < size; i++) {
  32170. this._data.push(data[i]);
  32171. }
  32172. this._needSync = true;
  32173. };
  32174. /**
  32175. * Wrapper for addUniform.
  32176. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32177. * @param {Matrix} mat A 4x4 matrix.
  32178. */
  32179. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32180. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32181. };
  32182. /**
  32183. * Wrapper for addUniform.
  32184. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32185. * @param {number} x
  32186. * @param {number} y
  32187. */
  32188. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32189. var temp = [x, y];
  32190. this.addUniform(name, temp);
  32191. };
  32192. /**
  32193. * Wrapper for addUniform.
  32194. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32195. * @param {number} x
  32196. * @param {number} y
  32197. * @param {number} z
  32198. */
  32199. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32200. var temp = [x, y, z];
  32201. this.addUniform(name, temp);
  32202. };
  32203. /**
  32204. * Wrapper for addUniform.
  32205. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32206. * @param {Color3} color
  32207. */
  32208. UniformBuffer.prototype.addColor3 = function (name, color) {
  32209. var temp = new Array();
  32210. color.toArray(temp);
  32211. this.addUniform(name, temp);
  32212. };
  32213. /**
  32214. * Wrapper for addUniform.
  32215. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32216. * @param {Color3} color
  32217. * @param {number} alpha
  32218. */
  32219. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32220. var temp = new Array();
  32221. color.toArray(temp);
  32222. temp.push(alpha);
  32223. this.addUniform(name, temp);
  32224. };
  32225. /**
  32226. * Wrapper for addUniform.
  32227. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32228. * @param {Vector3} vector
  32229. */
  32230. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32231. var temp = new Array();
  32232. vector.toArray(temp);
  32233. this.addUniform(name, temp);
  32234. };
  32235. /**
  32236. * Wrapper for addUniform.
  32237. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32238. */
  32239. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32240. this.addUniform(name, 12);
  32241. };
  32242. /**
  32243. * Wrapper for addUniform.
  32244. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32245. */
  32246. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32247. this.addUniform(name, 8);
  32248. };
  32249. /**
  32250. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32251. */
  32252. UniformBuffer.prototype.create = function () {
  32253. if (this._noUBO) {
  32254. return;
  32255. }
  32256. if (this._buffer) {
  32257. return; // nothing to do
  32258. }
  32259. // See spec, alignment must be filled as a vec4
  32260. this._fillAlignment(4);
  32261. this._bufferData = new Float32Array(this._data);
  32262. this._rebuild();
  32263. this._needSync = true;
  32264. };
  32265. UniformBuffer.prototype._rebuild = function () {
  32266. if (this._noUBO) {
  32267. return;
  32268. }
  32269. if (this._dynamic) {
  32270. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32271. }
  32272. else {
  32273. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32274. }
  32275. };
  32276. /**
  32277. * Updates the WebGL Uniform Buffer on the GPU.
  32278. * If the `dynamic` flag is set to true, no cache comparison is done.
  32279. * Otherwise, the buffer will be updated only if the cache differs.
  32280. */
  32281. UniformBuffer.prototype.update = function () {
  32282. if (!this._buffer) {
  32283. this.create();
  32284. return;
  32285. }
  32286. if (!this._dynamic && !this._needSync) {
  32287. return;
  32288. }
  32289. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32290. this._needSync = false;
  32291. };
  32292. /**
  32293. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32294. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32295. * @param {number[]|Float32Array} data Flattened data
  32296. * @param {number} size Size of the data.
  32297. */
  32298. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32299. var location = this._uniformLocations[uniformName];
  32300. if (location === undefined) {
  32301. if (this._buffer) {
  32302. // Cannot add an uniform if the buffer is already created
  32303. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32304. return;
  32305. }
  32306. this.addUniform(uniformName, size);
  32307. location = this._uniformLocations[uniformName];
  32308. }
  32309. if (!this._buffer) {
  32310. this.create();
  32311. }
  32312. if (!this._dynamic) {
  32313. // Cache for static uniform buffers
  32314. var changed = false;
  32315. for (var i = 0; i < size; i++) {
  32316. if (this._bufferData[location + i] !== data[i]) {
  32317. changed = true;
  32318. this._bufferData[location + i] = data[i];
  32319. }
  32320. }
  32321. this._needSync = this._needSync || changed;
  32322. }
  32323. else {
  32324. // No cache for dynamic
  32325. for (var i = 0; i < size; i++) {
  32326. this._bufferData[location + i] = data[i];
  32327. }
  32328. }
  32329. };
  32330. // Update methods
  32331. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32332. // To match std140, matrix must be realigned
  32333. for (var i = 0; i < 3; i++) {
  32334. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32335. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32336. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32337. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32338. }
  32339. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32340. };
  32341. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32342. this._currentEffect.setMatrix3x3(name, matrix);
  32343. };
  32344. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32345. this._currentEffect.setMatrix2x2(name, matrix);
  32346. };
  32347. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32348. // To match std140, matrix must be realigned
  32349. for (var i = 0; i < 2; i++) {
  32350. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32351. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32352. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32353. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32354. }
  32355. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32356. };
  32357. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32358. this._currentEffect.setFloat(name, x);
  32359. };
  32360. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32361. UniformBuffer._tempBuffer[0] = x;
  32362. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32363. };
  32364. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32365. if (suffix === void 0) { suffix = ""; }
  32366. this._currentEffect.setFloat2(name + suffix, x, y);
  32367. };
  32368. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32369. if (suffix === void 0) { suffix = ""; }
  32370. UniformBuffer._tempBuffer[0] = x;
  32371. UniformBuffer._tempBuffer[1] = y;
  32372. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32373. };
  32374. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32375. if (suffix === void 0) { suffix = ""; }
  32376. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32377. };
  32378. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32379. if (suffix === void 0) { suffix = ""; }
  32380. UniformBuffer._tempBuffer[0] = x;
  32381. UniformBuffer._tempBuffer[1] = y;
  32382. UniformBuffer._tempBuffer[2] = z;
  32383. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32384. };
  32385. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32386. if (suffix === void 0) { suffix = ""; }
  32387. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32388. };
  32389. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32390. if (suffix === void 0) { suffix = ""; }
  32391. UniformBuffer._tempBuffer[0] = x;
  32392. UniformBuffer._tempBuffer[1] = y;
  32393. UniformBuffer._tempBuffer[2] = z;
  32394. UniformBuffer._tempBuffer[3] = w;
  32395. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32396. };
  32397. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32398. this._currentEffect.setMatrix(name, mat);
  32399. };
  32400. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32401. this.updateUniform(name, mat.toArray(), 16);
  32402. };
  32403. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32404. this._currentEffect.setVector3(name, vector);
  32405. };
  32406. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32407. vector.toArray(UniformBuffer._tempBuffer);
  32408. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32409. };
  32410. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32411. this._currentEffect.setVector4(name, vector);
  32412. };
  32413. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32414. vector.toArray(UniformBuffer._tempBuffer);
  32415. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32416. };
  32417. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32418. if (suffix === void 0) { suffix = ""; }
  32419. this._currentEffect.setColor3(name + suffix, color);
  32420. };
  32421. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32422. if (suffix === void 0) { suffix = ""; }
  32423. color.toArray(UniformBuffer._tempBuffer);
  32424. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32425. };
  32426. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32427. if (suffix === void 0) { suffix = ""; }
  32428. this._currentEffect.setColor4(name + suffix, color, alpha);
  32429. };
  32430. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32431. if (suffix === void 0) { suffix = ""; }
  32432. color.toArray(UniformBuffer._tempBuffer);
  32433. UniformBuffer._tempBuffer[3] = alpha;
  32434. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32435. };
  32436. /**
  32437. * Sets a sampler uniform on the effect.
  32438. * @param {string} name Name of the sampler.
  32439. * @param {Texture} texture
  32440. */
  32441. UniformBuffer.prototype.setTexture = function (name, texture) {
  32442. this._currentEffect.setTexture(name, texture);
  32443. };
  32444. /**
  32445. * Directly updates the value of the uniform in the cache AND on the GPU.
  32446. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32447. * @param {number[]|Float32Array} data Flattened data
  32448. */
  32449. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32450. this.updateUniform(uniformName, data, data.length);
  32451. this.update();
  32452. };
  32453. /**
  32454. * Binds this uniform buffer to an effect.
  32455. * @param {Effect} effect
  32456. * @param {string} name Name of the uniform block in the shader.
  32457. */
  32458. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32459. this._currentEffect = effect;
  32460. if (this._noUBO || !this._buffer) {
  32461. return;
  32462. }
  32463. effect.bindUniformBuffer(this._buffer, name);
  32464. };
  32465. /**
  32466. * Disposes the uniform buffer.
  32467. */
  32468. UniformBuffer.prototype.dispose = function () {
  32469. if (this._noUBO) {
  32470. return;
  32471. }
  32472. var index = this._engine._uniformBuffers.indexOf(this);
  32473. if (index !== -1) {
  32474. this._engine._uniformBuffers.splice(index, 1);
  32475. }
  32476. if (!this._buffer) {
  32477. return;
  32478. }
  32479. if (this._engine._releaseBuffer(this._buffer)) {
  32480. this._buffer = null;
  32481. }
  32482. };
  32483. // Pool for avoiding memory leaks
  32484. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32485. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32486. return UniformBuffer;
  32487. }());
  32488. BABYLON.UniformBuffer = UniformBuffer;
  32489. })(BABYLON || (BABYLON = {}));
  32490. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32491. var BABYLON;
  32492. (function (BABYLON) {
  32493. var VertexData = /** @class */ (function () {
  32494. function VertexData() {
  32495. }
  32496. VertexData.prototype.set = function (data, kind) {
  32497. switch (kind) {
  32498. case BABYLON.VertexBuffer.PositionKind:
  32499. this.positions = data;
  32500. break;
  32501. case BABYLON.VertexBuffer.NormalKind:
  32502. this.normals = data;
  32503. break;
  32504. case BABYLON.VertexBuffer.TangentKind:
  32505. this.tangents = data;
  32506. break;
  32507. case BABYLON.VertexBuffer.UVKind:
  32508. this.uvs = data;
  32509. break;
  32510. case BABYLON.VertexBuffer.UV2Kind:
  32511. this.uvs2 = data;
  32512. break;
  32513. case BABYLON.VertexBuffer.UV3Kind:
  32514. this.uvs3 = data;
  32515. break;
  32516. case BABYLON.VertexBuffer.UV4Kind:
  32517. this.uvs4 = data;
  32518. break;
  32519. case BABYLON.VertexBuffer.UV5Kind:
  32520. this.uvs5 = data;
  32521. break;
  32522. case BABYLON.VertexBuffer.UV6Kind:
  32523. this.uvs6 = data;
  32524. break;
  32525. case BABYLON.VertexBuffer.ColorKind:
  32526. this.colors = data;
  32527. break;
  32528. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32529. this.matricesIndices = data;
  32530. break;
  32531. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32532. this.matricesWeights = data;
  32533. break;
  32534. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32535. this.matricesIndicesExtra = data;
  32536. break;
  32537. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32538. this.matricesWeightsExtra = data;
  32539. break;
  32540. }
  32541. };
  32542. /**
  32543. * Associates the vertexData to the passed Mesh.
  32544. * Sets it as updatable or not (default `false`).
  32545. * Returns the VertexData.
  32546. */
  32547. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32548. this._applyTo(mesh, updatable);
  32549. return this;
  32550. };
  32551. /**
  32552. * Associates the vertexData to the passed Geometry.
  32553. * Sets it as updatable or not (default `false`).
  32554. * Returns the VertexData.
  32555. */
  32556. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32557. this._applyTo(geometry, updatable);
  32558. return this;
  32559. };
  32560. /**
  32561. * Updates the associated mesh.
  32562. * Returns the VertexData.
  32563. */
  32564. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32565. this._update(mesh);
  32566. return this;
  32567. };
  32568. /**
  32569. * Updates the associated geometry.
  32570. * Returns the VertexData.
  32571. */
  32572. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32573. this._update(geometry);
  32574. return this;
  32575. };
  32576. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32577. if (updatable === void 0) { updatable = false; }
  32578. if (this.positions) {
  32579. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32580. }
  32581. if (this.normals) {
  32582. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32583. }
  32584. if (this.tangents) {
  32585. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32586. }
  32587. if (this.uvs) {
  32588. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32589. }
  32590. if (this.uvs2) {
  32591. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32592. }
  32593. if (this.uvs3) {
  32594. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32595. }
  32596. if (this.uvs4) {
  32597. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32598. }
  32599. if (this.uvs5) {
  32600. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32601. }
  32602. if (this.uvs6) {
  32603. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32604. }
  32605. if (this.colors) {
  32606. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32607. }
  32608. if (this.matricesIndices) {
  32609. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32610. }
  32611. if (this.matricesWeights) {
  32612. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32613. }
  32614. if (this.matricesIndicesExtra) {
  32615. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32616. }
  32617. if (this.matricesWeightsExtra) {
  32618. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32619. }
  32620. if (this.indices) {
  32621. meshOrGeometry.setIndices(this.indices, null, updatable);
  32622. }
  32623. return this;
  32624. };
  32625. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32626. if (this.positions) {
  32627. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32628. }
  32629. if (this.normals) {
  32630. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32631. }
  32632. if (this.tangents) {
  32633. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32634. }
  32635. if (this.uvs) {
  32636. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32637. }
  32638. if (this.uvs2) {
  32639. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32640. }
  32641. if (this.uvs3) {
  32642. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32643. }
  32644. if (this.uvs4) {
  32645. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32646. }
  32647. if (this.uvs5) {
  32648. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32649. }
  32650. if (this.uvs6) {
  32651. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32652. }
  32653. if (this.colors) {
  32654. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32655. }
  32656. if (this.matricesIndices) {
  32657. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32658. }
  32659. if (this.matricesWeights) {
  32660. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32661. }
  32662. if (this.matricesIndicesExtra) {
  32663. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32664. }
  32665. if (this.matricesWeightsExtra) {
  32666. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32667. }
  32668. if (this.indices) {
  32669. meshOrGeometry.setIndices(this.indices, null);
  32670. }
  32671. return this;
  32672. };
  32673. /**
  32674. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32675. * Returns the VertexData.
  32676. */
  32677. VertexData.prototype.transform = function (matrix) {
  32678. var transformed = BABYLON.Vector3.Zero();
  32679. var index;
  32680. if (this.positions) {
  32681. var position = BABYLON.Vector3.Zero();
  32682. for (index = 0; index < this.positions.length; index += 3) {
  32683. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32684. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32685. this.positions[index] = transformed.x;
  32686. this.positions[index + 1] = transformed.y;
  32687. this.positions[index + 2] = transformed.z;
  32688. }
  32689. }
  32690. if (this.normals) {
  32691. var normal = BABYLON.Vector3.Zero();
  32692. for (index = 0; index < this.normals.length; index += 3) {
  32693. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32694. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32695. this.normals[index] = transformed.x;
  32696. this.normals[index + 1] = transformed.y;
  32697. this.normals[index + 2] = transformed.z;
  32698. }
  32699. }
  32700. if (this.tangents) {
  32701. var tangent = BABYLON.Vector4.Zero();
  32702. var tangentTransformed = BABYLON.Vector4.Zero();
  32703. for (index = 0; index < this.tangents.length; index += 4) {
  32704. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32705. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32706. this.tangents[index] = tangentTransformed.x;
  32707. this.tangents[index + 1] = tangentTransformed.y;
  32708. this.tangents[index + 2] = tangentTransformed.z;
  32709. this.tangents[index + 3] = tangentTransformed.w;
  32710. }
  32711. }
  32712. return this;
  32713. };
  32714. /**
  32715. * Merges the passed VertexData into the current one.
  32716. * Returns the modified VertexData.
  32717. */
  32718. VertexData.prototype.merge = function (other) {
  32719. this._validate();
  32720. other._validate();
  32721. if (!this.normals !== !other.normals ||
  32722. !this.tangents !== !other.tangents ||
  32723. !this.uvs !== !other.uvs ||
  32724. !this.uvs2 !== !other.uvs2 ||
  32725. !this.uvs3 !== !other.uvs3 ||
  32726. !this.uvs4 !== !other.uvs4 ||
  32727. !this.uvs5 !== !other.uvs5 ||
  32728. !this.uvs6 !== !other.uvs6 ||
  32729. !this.colors !== !other.colors ||
  32730. !this.matricesIndices !== !other.matricesIndices ||
  32731. !this.matricesWeights !== !other.matricesWeights ||
  32732. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32733. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32734. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32735. }
  32736. if (other.indices) {
  32737. if (!this.indices) {
  32738. this.indices = [];
  32739. }
  32740. var offset = this.positions ? this.positions.length / 3 : 0;
  32741. for (var index = 0; index < other.indices.length; index++) {
  32742. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32743. this.indices.push(other.indices[index] + offset);
  32744. }
  32745. }
  32746. this.positions = this._mergeElement(this.positions, other.positions);
  32747. this.normals = this._mergeElement(this.normals, other.normals);
  32748. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32749. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32750. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32751. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32752. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32753. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32754. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32755. this.colors = this._mergeElement(this.colors, other.colors);
  32756. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32757. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32758. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32759. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32760. return this;
  32761. };
  32762. VertexData.prototype._mergeElement = function (source, other) {
  32763. if (!source) {
  32764. return other;
  32765. }
  32766. if (!other) {
  32767. return source;
  32768. }
  32769. var len = other.length + source.length;
  32770. var isSrcTypedArray = source instanceof Float32Array;
  32771. var isOthTypedArray = other instanceof Float32Array;
  32772. // use non-loop method when the source is Float32Array
  32773. if (isSrcTypedArray) {
  32774. var ret32 = new Float32Array(len);
  32775. ret32.set(source);
  32776. ret32.set(other, source.length);
  32777. return ret32;
  32778. // source is number[], when other is also use concat
  32779. }
  32780. else if (!isOthTypedArray) {
  32781. return source.concat(other);
  32782. // source is a number[], but other is a Float32Array, loop required
  32783. }
  32784. else {
  32785. var ret = source.slice(0); // copy source to a separate array
  32786. for (var i = 0, len = other.length; i < len; i++) {
  32787. ret.push(other[i]);
  32788. }
  32789. return ret;
  32790. }
  32791. };
  32792. VertexData.prototype._validate = function () {
  32793. if (!this.positions) {
  32794. throw new Error("Positions are required");
  32795. }
  32796. var getElementCount = function (kind, values) {
  32797. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32798. if ((values.length % stride) !== 0) {
  32799. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32800. }
  32801. return values.length / stride;
  32802. };
  32803. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32804. var validateElementCount = function (kind, values) {
  32805. var elementCount = getElementCount(kind, values);
  32806. if (elementCount !== positionsElementCount) {
  32807. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32808. }
  32809. };
  32810. if (this.normals)
  32811. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32812. if (this.tangents)
  32813. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32814. if (this.uvs)
  32815. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32816. if (this.uvs2)
  32817. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32818. if (this.uvs3)
  32819. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32820. if (this.uvs4)
  32821. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32822. if (this.uvs5)
  32823. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32824. if (this.uvs6)
  32825. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32826. if (this.colors)
  32827. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32828. if (this.matricesIndices)
  32829. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32830. if (this.matricesWeights)
  32831. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32832. if (this.matricesIndicesExtra)
  32833. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32834. if (this.matricesWeightsExtra)
  32835. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32836. };
  32837. /**
  32838. * Serializes the VertexData.
  32839. * Returns a serialized object.
  32840. */
  32841. VertexData.prototype.serialize = function () {
  32842. var serializationObject = this.serialize();
  32843. if (this.positions) {
  32844. serializationObject.positions = this.positions;
  32845. }
  32846. if (this.normals) {
  32847. serializationObject.normals = this.normals;
  32848. }
  32849. if (this.tangents) {
  32850. serializationObject.tangents = this.tangents;
  32851. }
  32852. if (this.uvs) {
  32853. serializationObject.uvs = this.uvs;
  32854. }
  32855. if (this.uvs2) {
  32856. serializationObject.uvs2 = this.uvs2;
  32857. }
  32858. if (this.uvs3) {
  32859. serializationObject.uvs3 = this.uvs3;
  32860. }
  32861. if (this.uvs4) {
  32862. serializationObject.uvs4 = this.uvs4;
  32863. }
  32864. if (this.uvs5) {
  32865. serializationObject.uvs5 = this.uvs5;
  32866. }
  32867. if (this.uvs6) {
  32868. serializationObject.uvs6 = this.uvs6;
  32869. }
  32870. if (this.colors) {
  32871. serializationObject.colors = this.colors;
  32872. }
  32873. if (this.matricesIndices) {
  32874. serializationObject.matricesIndices = this.matricesIndices;
  32875. serializationObject.matricesIndices._isExpanded = true;
  32876. }
  32877. if (this.matricesWeights) {
  32878. serializationObject.matricesWeights = this.matricesWeights;
  32879. }
  32880. if (this.matricesIndicesExtra) {
  32881. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32882. serializationObject.matricesIndicesExtra._isExpanded = true;
  32883. }
  32884. if (this.matricesWeightsExtra) {
  32885. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32886. }
  32887. serializationObject.indices = this.indices;
  32888. return serializationObject;
  32889. };
  32890. // Statics
  32891. /**
  32892. * Returns the object VertexData associated to the passed mesh.
  32893. */
  32894. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32895. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32896. };
  32897. /**
  32898. * Returns the object VertexData associated to the passed geometry.
  32899. */
  32900. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32901. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32902. };
  32903. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32904. var result = new VertexData();
  32905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32906. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32907. }
  32908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32909. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32910. }
  32911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32912. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32913. }
  32914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32915. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32916. }
  32917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32918. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32919. }
  32920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32921. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32922. }
  32923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32924. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32925. }
  32926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32927. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32928. }
  32929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32930. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32931. }
  32932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32933. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32934. }
  32935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32936. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32937. }
  32938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32939. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32940. }
  32941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32942. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32943. }
  32944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32945. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32946. }
  32947. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32948. return result;
  32949. };
  32950. /**
  32951. * Creates the vertexData of the Ribbon.
  32952. */
  32953. VertexData.CreateRibbon = function (options) {
  32954. var pathArray = options.pathArray;
  32955. var closeArray = options.closeArray || false;
  32956. var closePath = options.closePath || false;
  32957. var invertUV = options.invertUV || false;
  32958. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32959. var offset = options.offset || defaultOffset;
  32960. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32961. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32962. var customUV = options.uvs;
  32963. var customColors = options.colors;
  32964. var positions = [];
  32965. var indices = [];
  32966. var normals = [];
  32967. var uvs = [];
  32968. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32969. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32970. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32971. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32972. var minlg; // minimal length among all paths from pathArray
  32973. var lg = []; // array of path lengths : nb of vertex per path
  32974. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32975. var p; // path iterator
  32976. var i; // point iterator
  32977. var j; // point iterator
  32978. // if single path in pathArray
  32979. if (pathArray.length < 2) {
  32980. var ar1 = [];
  32981. var ar2 = [];
  32982. for (i = 0; i < pathArray[0].length - offset; i++) {
  32983. ar1.push(pathArray[0][i]);
  32984. ar2.push(pathArray[0][i + offset]);
  32985. }
  32986. pathArray = [ar1, ar2];
  32987. }
  32988. // positions and horizontal distances (u)
  32989. var idc = 0;
  32990. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32991. var path;
  32992. var l;
  32993. minlg = pathArray[0].length;
  32994. var vectlg;
  32995. var dist;
  32996. for (p = 0; p < pathArray.length; p++) {
  32997. uTotalDistance[p] = 0;
  32998. us[p] = [0];
  32999. path = pathArray[p];
  33000. l = path.length;
  33001. minlg = (minlg < l) ? minlg : l;
  33002. j = 0;
  33003. while (j < l) {
  33004. positions.push(path[j].x, path[j].y, path[j].z);
  33005. if (j > 0) {
  33006. vectlg = path[j].subtract(path[j - 1]).length();
  33007. dist = vectlg + uTotalDistance[p];
  33008. us[p].push(dist);
  33009. uTotalDistance[p] = dist;
  33010. }
  33011. j++;
  33012. }
  33013. if (closePath) {
  33014. j--;
  33015. positions.push(path[0].x, path[0].y, path[0].z);
  33016. vectlg = path[j].subtract(path[0]).length();
  33017. dist = vectlg + uTotalDistance[p];
  33018. us[p].push(dist);
  33019. uTotalDistance[p] = dist;
  33020. }
  33021. lg[p] = l + closePathCorr;
  33022. idx[p] = idc;
  33023. idc += (l + closePathCorr);
  33024. }
  33025. // vertical distances (v)
  33026. var path1;
  33027. var path2;
  33028. var vertex1 = null;
  33029. var vertex2 = null;
  33030. for (i = 0; i < minlg + closePathCorr; i++) {
  33031. vTotalDistance[i] = 0;
  33032. vs[i] = [0];
  33033. for (p = 0; p < pathArray.length - 1; p++) {
  33034. path1 = pathArray[p];
  33035. path2 = pathArray[p + 1];
  33036. if (i === minlg) {
  33037. vertex1 = path1[0];
  33038. vertex2 = path2[0];
  33039. }
  33040. else {
  33041. vertex1 = path1[i];
  33042. vertex2 = path2[i];
  33043. }
  33044. vectlg = vertex2.subtract(vertex1).length();
  33045. dist = vectlg + vTotalDistance[i];
  33046. vs[i].push(dist);
  33047. vTotalDistance[i] = dist;
  33048. }
  33049. if (closeArray && vertex2 && vertex1) {
  33050. path1 = pathArray[p];
  33051. path2 = pathArray[0];
  33052. if (i === minlg) {
  33053. vertex2 = path2[0];
  33054. }
  33055. vectlg = vertex2.subtract(vertex1).length();
  33056. dist = vectlg + vTotalDistance[i];
  33057. vTotalDistance[i] = dist;
  33058. }
  33059. }
  33060. // uvs
  33061. var u;
  33062. var v;
  33063. if (customUV) {
  33064. for (p = 0; p < customUV.length; p++) {
  33065. uvs.push(customUV[p].x, customUV[p].y);
  33066. }
  33067. }
  33068. else {
  33069. for (p = 0; p < pathArray.length; p++) {
  33070. for (i = 0; i < minlg + closePathCorr; i++) {
  33071. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33072. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33073. if (invertUV) {
  33074. uvs.push(v, u);
  33075. }
  33076. else {
  33077. uvs.push(u, v);
  33078. }
  33079. }
  33080. }
  33081. }
  33082. // indices
  33083. p = 0; // path index
  33084. var pi = 0; // positions array index
  33085. var l1 = lg[p] - 1; // path1 length
  33086. var l2 = lg[p + 1] - 1; // path2 length
  33087. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33088. var shft = idx[1] - idx[0]; // shift
  33089. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33090. while (pi <= min && p < path1nb) {
  33091. // 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
  33092. indices.push(pi, pi + shft, pi + 1);
  33093. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33094. pi += 1;
  33095. if (pi === min) {
  33096. p++;
  33097. if (p === lg.length - 1) {
  33098. shft = idx[0] - idx[p];
  33099. l1 = lg[p] - 1;
  33100. l2 = lg[0] - 1;
  33101. }
  33102. else {
  33103. shft = idx[p + 1] - idx[p];
  33104. l1 = lg[p] - 1;
  33105. l2 = lg[p + 1] - 1;
  33106. }
  33107. pi = idx[p];
  33108. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33109. }
  33110. }
  33111. // normals
  33112. VertexData.ComputeNormals(positions, indices, normals);
  33113. if (closePath) {
  33114. var indexFirst = 0;
  33115. var indexLast = 0;
  33116. for (p = 0; p < pathArray.length; p++) {
  33117. indexFirst = idx[p] * 3;
  33118. if (p + 1 < pathArray.length) {
  33119. indexLast = (idx[p + 1] - 1) * 3;
  33120. }
  33121. else {
  33122. indexLast = normals.length - 3;
  33123. }
  33124. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33125. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33126. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33127. normals[indexLast] = normals[indexFirst];
  33128. normals[indexLast + 1] = normals[indexFirst + 1];
  33129. normals[indexLast + 2] = normals[indexFirst + 2];
  33130. }
  33131. }
  33132. // sides
  33133. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33134. // Colors
  33135. var colors = null;
  33136. if (customColors) {
  33137. colors = new Float32Array(customColors.length * 4);
  33138. for (var c = 0; c < customColors.length; c++) {
  33139. colors[c * 4] = customColors[c].r;
  33140. colors[c * 4 + 1] = customColors[c].g;
  33141. colors[c * 4 + 2] = customColors[c].b;
  33142. colors[c * 4 + 3] = customColors[c].a;
  33143. }
  33144. }
  33145. // Result
  33146. var vertexData = new VertexData();
  33147. var positions32 = new Float32Array(positions);
  33148. var normals32 = new Float32Array(normals);
  33149. var uvs32 = new Float32Array(uvs);
  33150. vertexData.indices = indices;
  33151. vertexData.positions = positions32;
  33152. vertexData.normals = normals32;
  33153. vertexData.uvs = uvs32;
  33154. if (colors) {
  33155. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33156. }
  33157. if (closePath) {
  33158. vertexData._idx = idx;
  33159. }
  33160. return vertexData;
  33161. };
  33162. /**
  33163. * Creates the VertexData of the Box.
  33164. */
  33165. VertexData.CreateBox = function (options) {
  33166. var normalsSource = [
  33167. new BABYLON.Vector3(0, 0, 1),
  33168. new BABYLON.Vector3(0, 0, -1),
  33169. new BABYLON.Vector3(1, 0, 0),
  33170. new BABYLON.Vector3(-1, 0, 0),
  33171. new BABYLON.Vector3(0, 1, 0),
  33172. new BABYLON.Vector3(0, -1, 0)
  33173. ];
  33174. var indices = [];
  33175. var positions = [];
  33176. var normals = [];
  33177. var uvs = [];
  33178. var width = options.width || options.size || 1;
  33179. var height = options.height || options.size || 1;
  33180. var depth = options.depth || options.size || 1;
  33181. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33182. var faceUV = options.faceUV || new Array(6);
  33183. var faceColors = options.faceColors;
  33184. var colors = [];
  33185. // default face colors and UV if undefined
  33186. for (var f = 0; f < 6; f++) {
  33187. if (faceUV[f] === undefined) {
  33188. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33189. }
  33190. if (faceColors && faceColors[f] === undefined) {
  33191. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33192. }
  33193. }
  33194. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33195. // Create each face in turn.
  33196. for (var index = 0; index < normalsSource.length; index++) {
  33197. var normal = normalsSource[index];
  33198. // Get two vectors perpendicular to the face normal and to each other.
  33199. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33200. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33201. // Six indices (two triangles) per face.
  33202. var verticesLength = positions.length / 3;
  33203. indices.push(verticesLength);
  33204. indices.push(verticesLength + 1);
  33205. indices.push(verticesLength + 2);
  33206. indices.push(verticesLength);
  33207. indices.push(verticesLength + 2);
  33208. indices.push(verticesLength + 3);
  33209. // Four vertices per face.
  33210. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33211. positions.push(vertex.x, vertex.y, vertex.z);
  33212. normals.push(normal.x, normal.y, normal.z);
  33213. uvs.push(faceUV[index].z, faceUV[index].w);
  33214. if (faceColors) {
  33215. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33216. }
  33217. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33218. positions.push(vertex.x, vertex.y, vertex.z);
  33219. normals.push(normal.x, normal.y, normal.z);
  33220. uvs.push(faceUV[index].x, faceUV[index].w);
  33221. if (faceColors) {
  33222. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33223. }
  33224. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33225. positions.push(vertex.x, vertex.y, vertex.z);
  33226. normals.push(normal.x, normal.y, normal.z);
  33227. uvs.push(faceUV[index].x, faceUV[index].y);
  33228. if (faceColors) {
  33229. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33230. }
  33231. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33232. positions.push(vertex.x, vertex.y, vertex.z);
  33233. normals.push(normal.x, normal.y, normal.z);
  33234. uvs.push(faceUV[index].z, faceUV[index].y);
  33235. if (faceColors) {
  33236. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33237. }
  33238. }
  33239. // sides
  33240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33241. // Result
  33242. var vertexData = new VertexData();
  33243. vertexData.indices = indices;
  33244. vertexData.positions = positions;
  33245. vertexData.normals = normals;
  33246. vertexData.uvs = uvs;
  33247. if (faceColors) {
  33248. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33249. vertexData.colors = totalColors;
  33250. }
  33251. return vertexData;
  33252. };
  33253. /**
  33254. * Creates the VertexData of the Sphere.
  33255. */
  33256. VertexData.CreateSphere = function (options) {
  33257. var segments = options.segments || 32;
  33258. var diameterX = options.diameterX || options.diameter || 1;
  33259. var diameterY = options.diameterY || options.diameter || 1;
  33260. var diameterZ = options.diameterZ || options.diameter || 1;
  33261. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33262. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33263. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33264. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33265. var totalZRotationSteps = 2 + segments;
  33266. var totalYRotationSteps = 2 * totalZRotationSteps;
  33267. var indices = [];
  33268. var positions = [];
  33269. var normals = [];
  33270. var uvs = [];
  33271. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33272. var normalizedZ = zRotationStep / totalZRotationSteps;
  33273. var angleZ = normalizedZ * Math.PI * slice;
  33274. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33275. var normalizedY = yRotationStep / totalYRotationSteps;
  33276. var angleY = normalizedY * Math.PI * 2 * arc;
  33277. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33278. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33279. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33280. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33281. var vertex = complete.multiply(radius);
  33282. var normal = complete.divide(radius).normalize();
  33283. positions.push(vertex.x, vertex.y, vertex.z);
  33284. normals.push(normal.x, normal.y, normal.z);
  33285. uvs.push(normalizedY, normalizedZ);
  33286. }
  33287. if (zRotationStep > 0) {
  33288. var verticesCount = positions.length / 3;
  33289. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33290. indices.push((firstIndex));
  33291. indices.push((firstIndex + 1));
  33292. indices.push(firstIndex + totalYRotationSteps + 1);
  33293. indices.push((firstIndex + totalYRotationSteps + 1));
  33294. indices.push((firstIndex + 1));
  33295. indices.push((firstIndex + totalYRotationSteps + 2));
  33296. }
  33297. }
  33298. }
  33299. // Sides
  33300. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33301. // Result
  33302. var vertexData = new VertexData();
  33303. vertexData.indices = indices;
  33304. vertexData.positions = positions;
  33305. vertexData.normals = normals;
  33306. vertexData.uvs = uvs;
  33307. return vertexData;
  33308. };
  33309. /**
  33310. * Creates the VertexData of the Cylinder or Cone.
  33311. */
  33312. VertexData.CreateCylinder = function (options) {
  33313. var height = options.height || 2;
  33314. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33315. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33316. var tessellation = options.tessellation || 24;
  33317. var subdivisions = options.subdivisions || 1;
  33318. var hasRings = options.hasRings ? true : false;
  33319. var enclose = options.enclose ? true : false;
  33320. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33322. var faceUV = options.faceUV || new Array(3);
  33323. var faceColors = options.faceColors;
  33324. // default face colors and UV if undefined
  33325. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33326. var ringNb = (hasRings) ? subdivisions : 1;
  33327. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33328. var f;
  33329. for (f = 0; f < surfaceNb; f++) {
  33330. if (faceColors && faceColors[f] === undefined) {
  33331. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33332. }
  33333. }
  33334. for (f = 0; f < surfaceNb; f++) {
  33335. if (faceUV && faceUV[f] === undefined) {
  33336. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33337. }
  33338. }
  33339. var indices = new Array();
  33340. var positions = new Array();
  33341. var normals = new Array();
  33342. var uvs = new Array();
  33343. var colors = new Array();
  33344. var angle_step = Math.PI * 2 * arc / tessellation;
  33345. var angle;
  33346. var h;
  33347. var radius;
  33348. var tan = (diameterBottom - diameterTop) / 2 / height;
  33349. var ringVertex = BABYLON.Vector3.Zero();
  33350. var ringNormal = BABYLON.Vector3.Zero();
  33351. var ringFirstVertex = BABYLON.Vector3.Zero();
  33352. var ringFirstNormal = BABYLON.Vector3.Zero();
  33353. var quadNormal = BABYLON.Vector3.Zero();
  33354. var Y = BABYLON.Axis.Y;
  33355. // positions, normals, uvs
  33356. var i;
  33357. var j;
  33358. var r;
  33359. var ringIdx = 1;
  33360. var s = 1; // surface index
  33361. var cs = 0;
  33362. var v = 0;
  33363. for (i = 0; i <= subdivisions; i++) {
  33364. h = i / subdivisions;
  33365. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33366. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33367. for (r = 0; r < ringIdx; r++) {
  33368. if (hasRings) {
  33369. s += r;
  33370. }
  33371. if (enclose) {
  33372. s += 2 * r;
  33373. }
  33374. for (j = 0; j <= tessellation; j++) {
  33375. angle = j * angle_step;
  33376. // position
  33377. ringVertex.x = Math.cos(-angle) * radius;
  33378. ringVertex.y = -height / 2 + h * height;
  33379. ringVertex.z = Math.sin(-angle) * radius;
  33380. // normal
  33381. if (diameterTop === 0 && i === subdivisions) {
  33382. // if no top cap, reuse former normals
  33383. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33384. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33385. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33386. }
  33387. else {
  33388. ringNormal.x = ringVertex.x;
  33389. ringNormal.z = ringVertex.z;
  33390. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33391. ringNormal.normalize();
  33392. }
  33393. // keep first ring vertex values for enclose
  33394. if (j === 0) {
  33395. ringFirstVertex.copyFrom(ringVertex);
  33396. ringFirstNormal.copyFrom(ringNormal);
  33397. }
  33398. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33399. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33400. if (hasRings) {
  33401. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33402. }
  33403. else {
  33404. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33405. }
  33406. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33407. if (faceColors) {
  33408. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33409. }
  33410. }
  33411. // if enclose, add four vertices and their dedicated normals
  33412. if (arc !== 1 && enclose) {
  33413. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33414. positions.push(0, ringVertex.y, 0);
  33415. positions.push(0, ringVertex.y, 0);
  33416. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33417. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33418. quadNormal.normalize();
  33419. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33420. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33421. quadNormal.normalize();
  33422. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33423. if (hasRings) {
  33424. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33425. }
  33426. else {
  33427. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33428. }
  33429. uvs.push(faceUV[s + 1].x, v);
  33430. uvs.push(faceUV[s + 1].z, v);
  33431. if (hasRings) {
  33432. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33433. }
  33434. else {
  33435. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33436. }
  33437. uvs.push(faceUV[s + 2].x, v);
  33438. uvs.push(faceUV[s + 2].z, v);
  33439. if (faceColors) {
  33440. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33441. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33442. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33443. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33444. }
  33445. }
  33446. if (cs !== s) {
  33447. cs = s;
  33448. }
  33449. }
  33450. }
  33451. // indices
  33452. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33453. var s;
  33454. i = 0;
  33455. for (s = 0; s < subdivisions; s++) {
  33456. var i0 = 0;
  33457. var i1 = 0;
  33458. var i2 = 0;
  33459. var i3 = 0;
  33460. for (j = 0; j < tessellation; j++) {
  33461. i0 = i * (e + 1) + j;
  33462. i1 = (i + 1) * (e + 1) + j;
  33463. i2 = i * (e + 1) + (j + 1);
  33464. i3 = (i + 1) * (e + 1) + (j + 1);
  33465. indices.push(i0, i1, i2);
  33466. indices.push(i3, i2, i1);
  33467. }
  33468. if (arc !== 1 && enclose) {
  33469. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33470. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33471. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33472. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33473. }
  33474. i = (hasRings) ? (i + 2) : (i + 1);
  33475. }
  33476. // Caps
  33477. var createCylinderCap = function (isTop) {
  33478. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33479. if (radius === 0) {
  33480. return;
  33481. }
  33482. // Cap positions, normals & uvs
  33483. var angle;
  33484. var circleVector;
  33485. var i;
  33486. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33487. var c = null;
  33488. if (faceColors) {
  33489. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33490. }
  33491. // cap center
  33492. var vbase = positions.length / 3;
  33493. var offset = isTop ? height / 2 : -height / 2;
  33494. var center = new BABYLON.Vector3(0, offset, 0);
  33495. positions.push(center.x, center.y, center.z);
  33496. normals.push(0, isTop ? 1 : -1, 0);
  33497. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33498. if (c) {
  33499. colors.push(c.r, c.g, c.b, c.a);
  33500. }
  33501. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33502. for (i = 0; i <= tessellation; i++) {
  33503. angle = Math.PI * 2 * i * arc / tessellation;
  33504. var cos = Math.cos(-angle);
  33505. var sin = Math.sin(-angle);
  33506. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33507. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33508. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33509. normals.push(0, isTop ? 1 : -1, 0);
  33510. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33511. if (c) {
  33512. colors.push(c.r, c.g, c.b, c.a);
  33513. }
  33514. }
  33515. // Cap indices
  33516. for (i = 0; i < tessellation; i++) {
  33517. if (!isTop) {
  33518. indices.push(vbase);
  33519. indices.push(vbase + (i + 1));
  33520. indices.push(vbase + (i + 2));
  33521. }
  33522. else {
  33523. indices.push(vbase);
  33524. indices.push(vbase + (i + 2));
  33525. indices.push(vbase + (i + 1));
  33526. }
  33527. }
  33528. };
  33529. // add caps to geometry
  33530. createCylinderCap(false);
  33531. createCylinderCap(true);
  33532. // Sides
  33533. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33534. var vertexData = new VertexData();
  33535. vertexData.indices = indices;
  33536. vertexData.positions = positions;
  33537. vertexData.normals = normals;
  33538. vertexData.uvs = uvs;
  33539. if (faceColors) {
  33540. vertexData.colors = colors;
  33541. }
  33542. return vertexData;
  33543. };
  33544. /**
  33545. * Creates the VertexData of the Torus.
  33546. */
  33547. VertexData.CreateTorus = function (options) {
  33548. var indices = [];
  33549. var positions = [];
  33550. var normals = [];
  33551. var uvs = [];
  33552. var diameter = options.diameter || 1;
  33553. var thickness = options.thickness || 0.5;
  33554. var tessellation = options.tessellation || 16;
  33555. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33556. var stride = tessellation + 1;
  33557. for (var i = 0; i <= tessellation; i++) {
  33558. var u = i / tessellation;
  33559. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33560. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33561. for (var j = 0; j <= tessellation; j++) {
  33562. var v = 1 - j / tessellation;
  33563. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33564. var dx = Math.cos(innerAngle);
  33565. var dy = Math.sin(innerAngle);
  33566. // Create a vertex.
  33567. var normal = new BABYLON.Vector3(dx, dy, 0);
  33568. var position = normal.scale(thickness / 2);
  33569. var textureCoordinate = new BABYLON.Vector2(u, v);
  33570. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33571. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33572. positions.push(position.x, position.y, position.z);
  33573. normals.push(normal.x, normal.y, normal.z);
  33574. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33575. // And create indices for two triangles.
  33576. var nextI = (i + 1) % stride;
  33577. var nextJ = (j + 1) % stride;
  33578. indices.push(i * stride + j);
  33579. indices.push(i * stride + nextJ);
  33580. indices.push(nextI * stride + j);
  33581. indices.push(i * stride + nextJ);
  33582. indices.push(nextI * stride + nextJ);
  33583. indices.push(nextI * stride + j);
  33584. }
  33585. }
  33586. // Sides
  33587. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33588. // Result
  33589. var vertexData = new VertexData();
  33590. vertexData.indices = indices;
  33591. vertexData.positions = positions;
  33592. vertexData.normals = normals;
  33593. vertexData.uvs = uvs;
  33594. return vertexData;
  33595. };
  33596. /**
  33597. * Creates the VertexData of the LineSystem.
  33598. */
  33599. VertexData.CreateLineSystem = function (options) {
  33600. var indices = [];
  33601. var positions = [];
  33602. var lines = options.lines;
  33603. var colors = options.colors;
  33604. var vertexColors = [];
  33605. var idx = 0;
  33606. for (var l = 0; l < lines.length; l++) {
  33607. var points = lines[l];
  33608. for (var index = 0; index < points.length; index++) {
  33609. positions.push(points[index].x, points[index].y, points[index].z);
  33610. if (colors) {
  33611. var color = colors[l];
  33612. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33613. }
  33614. if (index > 0) {
  33615. indices.push(idx - 1);
  33616. indices.push(idx);
  33617. }
  33618. idx++;
  33619. }
  33620. }
  33621. var vertexData = new VertexData();
  33622. vertexData.indices = indices;
  33623. vertexData.positions = positions;
  33624. if (colors) {
  33625. vertexData.colors = vertexColors;
  33626. }
  33627. return vertexData;
  33628. };
  33629. /**
  33630. * Create the VertexData of the DashedLines.
  33631. */
  33632. VertexData.CreateDashedLines = function (options) {
  33633. var dashSize = options.dashSize || 3;
  33634. var gapSize = options.gapSize || 1;
  33635. var dashNb = options.dashNb || 200;
  33636. var points = options.points;
  33637. var positions = new Array();
  33638. var indices = new Array();
  33639. var curvect = BABYLON.Vector3.Zero();
  33640. var lg = 0;
  33641. var nb = 0;
  33642. var shft = 0;
  33643. var dashshft = 0;
  33644. var curshft = 0;
  33645. var idx = 0;
  33646. var i = 0;
  33647. for (i = 0; i < points.length - 1; i++) {
  33648. points[i + 1].subtractToRef(points[i], curvect);
  33649. lg += curvect.length();
  33650. }
  33651. shft = lg / dashNb;
  33652. dashshft = dashSize * shft / (dashSize + gapSize);
  33653. for (i = 0; i < points.length - 1; i++) {
  33654. points[i + 1].subtractToRef(points[i], curvect);
  33655. nb = Math.floor(curvect.length() / shft);
  33656. curvect.normalize();
  33657. for (var j = 0; j < nb; j++) {
  33658. curshft = shft * j;
  33659. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33660. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33661. indices.push(idx, idx + 1);
  33662. idx += 2;
  33663. }
  33664. }
  33665. // Result
  33666. var vertexData = new VertexData();
  33667. vertexData.positions = positions;
  33668. vertexData.indices = indices;
  33669. return vertexData;
  33670. };
  33671. /**
  33672. * Creates the VertexData of the Ground.
  33673. */
  33674. VertexData.CreateGround = function (options) {
  33675. var indices = [];
  33676. var positions = [];
  33677. var normals = [];
  33678. var uvs = [];
  33679. var row, col;
  33680. var width = options.width || 1;
  33681. var height = options.height || 1;
  33682. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33683. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33684. for (row = 0; row <= subdivisionsY; row++) {
  33685. for (col = 0; col <= subdivisionsX; col++) {
  33686. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33687. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33688. positions.push(position.x, position.y, position.z);
  33689. normals.push(normal.x, normal.y, normal.z);
  33690. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33691. }
  33692. }
  33693. for (row = 0; row < subdivisionsY; row++) {
  33694. for (col = 0; col < subdivisionsX; col++) {
  33695. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33696. indices.push(col + 1 + row * (subdivisionsX + 1));
  33697. indices.push(col + row * (subdivisionsX + 1));
  33698. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33699. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33700. indices.push(col + row * (subdivisionsX + 1));
  33701. }
  33702. }
  33703. // Result
  33704. var vertexData = new VertexData();
  33705. vertexData.indices = indices;
  33706. vertexData.positions = positions;
  33707. vertexData.normals = normals;
  33708. vertexData.uvs = uvs;
  33709. return vertexData;
  33710. };
  33711. /**
  33712. * Creates the VertexData of the TiledGround.
  33713. */
  33714. VertexData.CreateTiledGround = function (options) {
  33715. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33716. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33717. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33718. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33719. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33720. var precision = options.precision || { w: 1, h: 1 };
  33721. var indices = new Array();
  33722. var positions = new Array();
  33723. var normals = new Array();
  33724. var uvs = new Array();
  33725. var row, col, tileRow, tileCol;
  33726. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33727. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33728. precision.w = (precision.w < 1) ? 1 : precision.w;
  33729. precision.h = (precision.h < 1) ? 1 : precision.h;
  33730. var tileSize = {
  33731. 'w': (xmax - xmin) / subdivisions.w,
  33732. 'h': (zmax - zmin) / subdivisions.h
  33733. };
  33734. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33735. // Indices
  33736. var base = positions.length / 3;
  33737. var rowLength = precision.w + 1;
  33738. for (row = 0; row < precision.h; row++) {
  33739. for (col = 0; col < precision.w; col++) {
  33740. var square = [
  33741. base + col + row * rowLength,
  33742. base + (col + 1) + row * rowLength,
  33743. base + (col + 1) + (row + 1) * rowLength,
  33744. base + col + (row + 1) * rowLength
  33745. ];
  33746. indices.push(square[1]);
  33747. indices.push(square[2]);
  33748. indices.push(square[3]);
  33749. indices.push(square[0]);
  33750. indices.push(square[1]);
  33751. indices.push(square[3]);
  33752. }
  33753. }
  33754. // Position, normals and uvs
  33755. var position = BABYLON.Vector3.Zero();
  33756. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33757. for (row = 0; row <= precision.h; row++) {
  33758. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33759. for (col = 0; col <= precision.w; col++) {
  33760. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33761. position.y = 0;
  33762. positions.push(position.x, position.y, position.z);
  33763. normals.push(normal.x, normal.y, normal.z);
  33764. uvs.push(col / precision.w, row / precision.h);
  33765. }
  33766. }
  33767. }
  33768. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33769. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33770. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33771. }
  33772. }
  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 Ground designed from a heightmap.
  33783. */
  33784. VertexData.CreateGroundFromHeightMap = function (options) {
  33785. var indices = [];
  33786. var positions = [];
  33787. var normals = [];
  33788. var uvs = [];
  33789. var row, col;
  33790. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33791. // Vertices
  33792. for (row = 0; row <= options.subdivisions; row++) {
  33793. for (col = 0; col <= options.subdivisions; col++) {
  33794. 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));
  33795. // Compute height
  33796. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33797. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33798. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33799. var r = options.buffer[pos] / 255.0;
  33800. var g = options.buffer[pos + 1] / 255.0;
  33801. var b = options.buffer[pos + 2] / 255.0;
  33802. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33803. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33804. // Add vertex
  33805. positions.push(position.x, position.y, position.z);
  33806. normals.push(0, 0, 0);
  33807. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33808. }
  33809. }
  33810. // Indices
  33811. for (row = 0; row < options.subdivisions; row++) {
  33812. for (col = 0; col < options.subdivisions; col++) {
  33813. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33814. indices.push(col + 1 + row * (options.subdivisions + 1));
  33815. indices.push(col + row * (options.subdivisions + 1));
  33816. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33817. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33818. indices.push(col + row * (options.subdivisions + 1));
  33819. }
  33820. }
  33821. // Normals
  33822. VertexData.ComputeNormals(positions, indices, normals);
  33823. // Result
  33824. var vertexData = new VertexData();
  33825. vertexData.indices = indices;
  33826. vertexData.positions = positions;
  33827. vertexData.normals = normals;
  33828. vertexData.uvs = uvs;
  33829. return vertexData;
  33830. };
  33831. /**
  33832. * Creates the VertexData of the Plane.
  33833. */
  33834. VertexData.CreatePlane = function (options) {
  33835. var indices = [];
  33836. var positions = [];
  33837. var normals = [];
  33838. var uvs = [];
  33839. var width = options.width || options.size || 1;
  33840. var height = options.height || options.size || 1;
  33841. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33842. // Vertices
  33843. var halfWidth = width / 2.0;
  33844. var halfHeight = height / 2.0;
  33845. positions.push(-halfWidth, -halfHeight, 0);
  33846. normals.push(0, 0, -1.0);
  33847. uvs.push(0.0, 0.0);
  33848. positions.push(halfWidth, -halfHeight, 0);
  33849. normals.push(0, 0, -1.0);
  33850. uvs.push(1.0, 0.0);
  33851. positions.push(halfWidth, halfHeight, 0);
  33852. normals.push(0, 0, -1.0);
  33853. uvs.push(1.0, 1.0);
  33854. positions.push(-halfWidth, halfHeight, 0);
  33855. normals.push(0, 0, -1.0);
  33856. uvs.push(0.0, 1.0);
  33857. // Indices
  33858. indices.push(0);
  33859. indices.push(1);
  33860. indices.push(2);
  33861. indices.push(0);
  33862. indices.push(2);
  33863. indices.push(3);
  33864. // Sides
  33865. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33866. // Result
  33867. var vertexData = new VertexData();
  33868. vertexData.indices = indices;
  33869. vertexData.positions = positions;
  33870. vertexData.normals = normals;
  33871. vertexData.uvs = uvs;
  33872. return vertexData;
  33873. };
  33874. /**
  33875. * Creates the VertexData of the Disc or regular Polygon.
  33876. */
  33877. VertexData.CreateDisc = function (options) {
  33878. var positions = new Array();
  33879. var indices = new Array();
  33880. var normals = new Array();
  33881. var uvs = new Array();
  33882. var radius = options.radius || 0.5;
  33883. var tessellation = options.tessellation || 64;
  33884. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33885. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33886. // positions and uvs
  33887. positions.push(0, 0, 0); // disc center first
  33888. uvs.push(0.5, 0.5);
  33889. var theta = Math.PI * 2 * arc;
  33890. var step = theta / tessellation;
  33891. for (var a = 0; a < theta; a += step) {
  33892. var x = Math.cos(a);
  33893. var y = Math.sin(a);
  33894. var u = (x + 1) / 2;
  33895. var v = (1 - y) / 2;
  33896. positions.push(radius * x, radius * y, 0);
  33897. uvs.push(u, v);
  33898. }
  33899. if (arc === 1) {
  33900. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33901. uvs.push(uvs[2], uvs[3]);
  33902. }
  33903. //indices
  33904. var vertexNb = positions.length / 3;
  33905. for (var i = 1; i < vertexNb - 1; i++) {
  33906. indices.push(i + 1, 0, i);
  33907. }
  33908. // result
  33909. VertexData.ComputeNormals(positions, indices, normals);
  33910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33911. var vertexData = new VertexData();
  33912. vertexData.indices = indices;
  33913. vertexData.positions = positions;
  33914. vertexData.normals = normals;
  33915. vertexData.uvs = uvs;
  33916. return vertexData;
  33917. };
  33918. /**
  33919. * Re-creates the VertexData of the Polygon for sideOrientation.
  33920. */
  33921. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33922. var faceUV = fUV || new Array(3);
  33923. var faceColors = fColors;
  33924. var colors = [];
  33925. // default face colors and UV if undefined
  33926. for (var f = 0; f < 3; f++) {
  33927. if (faceUV[f] === undefined) {
  33928. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33929. }
  33930. if (faceColors && faceColors[f] === undefined) {
  33931. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33932. }
  33933. }
  33934. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33935. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33936. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33937. var indices = polygon.getIndices();
  33938. // set face colours and textures
  33939. var idx = 0;
  33940. var face = 0;
  33941. for (var index = 0; index < normals.length; index += 3) {
  33942. //Edge Face no. 1
  33943. if (Math.abs(normals[index + 1]) < 0.001) {
  33944. face = 1;
  33945. }
  33946. //Top Face no. 0
  33947. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33948. face = 0;
  33949. }
  33950. //Bottom Face no. 2
  33951. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33952. face = 2;
  33953. }
  33954. idx = index / 3;
  33955. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33956. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33957. if (faceColors) {
  33958. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33959. }
  33960. }
  33961. // sides
  33962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33963. // Result
  33964. var vertexData = new VertexData();
  33965. vertexData.indices = indices;
  33966. vertexData.positions = positions;
  33967. vertexData.normals = normals;
  33968. vertexData.uvs = uvs;
  33969. if (faceColors) {
  33970. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33971. vertexData.colors = totalColors;
  33972. }
  33973. return vertexData;
  33974. };
  33975. /**
  33976. * Creates the VertexData of the IcoSphere.
  33977. */
  33978. VertexData.CreateIcoSphere = function (options) {
  33979. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33980. var radius = options.radius || 1;
  33981. var flat = (options.flat === undefined) ? true : options.flat;
  33982. var subdivisions = options.subdivisions || 4;
  33983. var radiusX = options.radiusX || radius;
  33984. var radiusY = options.radiusY || radius;
  33985. var radiusZ = options.radiusZ || radius;
  33986. var t = (1 + Math.sqrt(5)) / 2;
  33987. // 12 vertex x,y,z
  33988. var ico_vertices = [
  33989. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33990. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33991. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33992. ];
  33993. // index of 3 vertex makes a face of icopshere
  33994. var ico_indices = [
  33995. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33996. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33997. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33998. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33999. ];
  34000. // vertex for uv have aliased position, not for UV
  34001. var vertices_unalias_id = [
  34002. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34003. // vertex alias
  34004. 0,
  34005. 2,
  34006. 3,
  34007. 3,
  34008. 3,
  34009. 4,
  34010. 7,
  34011. 8,
  34012. 9,
  34013. 9,
  34014. 10,
  34015. 11 // 23: B + 12
  34016. ];
  34017. // uv as integer step (not pixels !)
  34018. var ico_vertexuv = [
  34019. 5, 1, 3, 1, 6, 4, 0, 0,
  34020. 5, 3, 4, 2, 2, 2, 4, 0,
  34021. 2, 0, 1, 1, 6, 0, 6, 2,
  34022. // vertex alias (for same vertex on different faces)
  34023. 0, 4,
  34024. 3, 3,
  34025. 4, 4,
  34026. 3, 1,
  34027. 4, 2,
  34028. 4, 4,
  34029. 0, 2,
  34030. 1, 1,
  34031. 2, 2,
  34032. 3, 3,
  34033. 1, 3,
  34034. 2, 4 // 23: B + 12
  34035. ];
  34036. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34037. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34038. // First island of uv mapping
  34039. // v = 4h 3+ 2
  34040. // v = 3h 9+ 4
  34041. // v = 2h 9+ 5 B
  34042. // v = 1h 9 1 0
  34043. // v = 0h 3 8 7 A
  34044. // u = 0 1 2 3 4 5 6 *a
  34045. // Second island of uv mapping
  34046. // v = 4h 0+ B+ 4+
  34047. // v = 3h A+ 2+
  34048. // v = 2h 7+ 6 3+
  34049. // v = 1h 8+ 3+
  34050. // v = 0h
  34051. // u = 0 1 2 3 4 5 6 *a
  34052. // Face layout on texture UV mapping
  34053. // ============
  34054. // \ 4 /\ 16 / ======
  34055. // \ / \ / /\ 11 /
  34056. // \/ 7 \/ / \ /
  34057. // ======= / 10 \/
  34058. // /\ 17 /\ =======
  34059. // / \ / \ \ 15 /\
  34060. // / 8 \/ 12 \ \ / \
  34061. // ============ \/ 6 \
  34062. // \ 18 /\ ============
  34063. // \ / \ \ 5 /\ 0 /
  34064. // \/ 13 \ \ / \ /
  34065. // ======= \/ 1 \/
  34066. // =============
  34067. // /\ 19 /\ 2 /\
  34068. // / \ / \ / \
  34069. // / 14 \/ 9 \/ 3 \
  34070. // ===================
  34071. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34072. var ustep = 138 / 1024;
  34073. var vstep = 239 / 1024;
  34074. var uoffset = 60 / 1024;
  34075. var voffset = 26 / 1024;
  34076. // Second island should have margin, not to touch the first island
  34077. // avoid any borderline artefact in pixel rounding
  34078. var island_u_offset = -40 / 1024;
  34079. var island_v_offset = +20 / 1024;
  34080. // face is either island 0 or 1 :
  34081. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34082. var island = [
  34083. 0, 0, 0, 0, 1,
  34084. 0, 0, 1, 1, 0,
  34085. 0, 0, 1, 1, 0,
  34086. 0, 1, 1, 1, 0 // 15 - 19
  34087. ];
  34088. var indices = new Array();
  34089. var positions = new Array();
  34090. var normals = new Array();
  34091. var uvs = new Array();
  34092. var current_indice = 0;
  34093. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34094. var face_vertex_pos = new Array(3);
  34095. var face_vertex_uv = new Array(3);
  34096. var v012;
  34097. for (v012 = 0; v012 < 3; v012++) {
  34098. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34099. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34100. }
  34101. // create all with normals
  34102. for (var face = 0; face < 20; face++) {
  34103. // 3 vertex per face
  34104. for (v012 = 0; v012 < 3; v012++) {
  34105. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34106. var v_id = ico_indices[3 * face + v012];
  34107. // vertex have 3D position (x,y,z)
  34108. 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]);
  34109. // Normalize to get normal, then scale to radius
  34110. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34111. // uv Coordinates from vertex ID
  34112. 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);
  34113. }
  34114. // Subdivide the face (interpolate pos, norm, uv)
  34115. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34116. // - norm is linear interpolation of vertex corner normal
  34117. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34118. // - uv is linear interpolation
  34119. //
  34120. // Topology is as below for sub-divide by 2
  34121. // vertex shown as v0,v1,v2
  34122. // interp index is i1 to progress in range [v0,v1[
  34123. // interp index is i2 to progress in range [v0,v2[
  34124. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34125. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34126. //
  34127. //
  34128. // i2 v2
  34129. // ^ ^
  34130. // / / \
  34131. // / / \
  34132. // / / \
  34133. // / / (0,1) \
  34134. // / #---------\
  34135. // / / \ (0,0)'/ \
  34136. // / / \ / \
  34137. // / / \ / \
  34138. // / / (0,0) \ / (1,0) \
  34139. // / #---------#---------\
  34140. // v0 v1
  34141. //
  34142. // --------------------> i1
  34143. //
  34144. // interp of (i1,i2):
  34145. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34146. // along i1 : lerp(x0,x1, i1/(S-i2))
  34147. //
  34148. // centroid of triangle is needed to get help normal computation
  34149. // (c1,c2) are used for centroid location
  34150. var interp_vertex = function (i1, i2, c1, c2) {
  34151. // vertex is interpolated from
  34152. // - face_vertex_pos[0..2]
  34153. // - face_vertex_uv[0..2]
  34154. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34155. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34156. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34157. pos_interp.normalize();
  34158. var vertex_normal;
  34159. if (flat) {
  34160. // in flat mode, recalculate normal as face centroid normal
  34161. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34162. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34163. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34164. }
  34165. else {
  34166. // in smooth mode, recalculate normal from each single vertex position
  34167. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34168. }
  34169. // Vertex normal need correction due to X,Y,Z radius scaling
  34170. vertex_normal.x /= radiusX;
  34171. vertex_normal.y /= radiusY;
  34172. vertex_normal.z /= radiusZ;
  34173. vertex_normal.normalize();
  34174. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34175. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34176. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34177. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34178. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34179. uvs.push(uv_interp.x, uv_interp.y);
  34180. // push each vertex has member of a face
  34181. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34182. indices.push(current_indice);
  34183. current_indice++;
  34184. };
  34185. for (var i2 = 0; i2 < subdivisions; i2++) {
  34186. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34187. // face : (i1,i2) for /\ :
  34188. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34189. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34190. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34191. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34192. if (i1 + i2 + 1 < subdivisions) {
  34193. // face : (i1,i2)' for \/ :
  34194. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34195. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34196. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34197. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34198. }
  34199. }
  34200. }
  34201. }
  34202. // Sides
  34203. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34204. // Result
  34205. var vertexData = new VertexData();
  34206. vertexData.indices = indices;
  34207. vertexData.positions = positions;
  34208. vertexData.normals = normals;
  34209. vertexData.uvs = uvs;
  34210. return vertexData;
  34211. };
  34212. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34213. /**
  34214. * Creates the VertexData of the Polyhedron.
  34215. */
  34216. VertexData.CreatePolyhedron = function (options) {
  34217. // provided polyhedron types :
  34218. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34219. // 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)
  34220. var polyhedra = [];
  34221. 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]] };
  34222. 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]] };
  34223. polyhedra[2] = {
  34224. 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]],
  34225. 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]]
  34226. };
  34227. polyhedra[3] = {
  34228. 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]],
  34229. 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]]
  34230. };
  34231. polyhedra[4] = {
  34232. 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]],
  34233. 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]]
  34234. };
  34235. 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]] };
  34236. 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]] };
  34237. 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]] };
  34238. 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]] };
  34239. 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]] };
  34240. 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]] };
  34241. 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]] };
  34242. 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]] };
  34243. 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]] };
  34244. polyhedra[14] = {
  34245. 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]],
  34246. 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]]
  34247. };
  34248. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34249. var size = options.size;
  34250. var sizeX = options.sizeX || size || 1;
  34251. var sizeY = options.sizeY || size || 1;
  34252. var sizeZ = options.sizeZ || size || 1;
  34253. var data = options.custom || polyhedra[type];
  34254. var nbfaces = data.face.length;
  34255. var faceUV = options.faceUV || new Array(nbfaces);
  34256. var faceColors = options.faceColors;
  34257. var flat = (options.flat === undefined) ? true : options.flat;
  34258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34259. var positions = new Array();
  34260. var indices = new Array();
  34261. var normals = new Array();
  34262. var uvs = new Array();
  34263. var colors = new Array();
  34264. var index = 0;
  34265. var faceIdx = 0; // face cursor in the array "indexes"
  34266. var indexes = new Array();
  34267. var i = 0;
  34268. var f = 0;
  34269. var u, v, ang, x, y, tmp;
  34270. // default face colors and UV if undefined
  34271. if (flat) {
  34272. for (f = 0; f < nbfaces; f++) {
  34273. if (faceColors && faceColors[f] === undefined) {
  34274. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34275. }
  34276. if (faceUV && faceUV[f] === undefined) {
  34277. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34278. }
  34279. }
  34280. }
  34281. if (!flat) {
  34282. for (i = 0; i < data.vertex.length; i++) {
  34283. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34284. uvs.push(0, 0);
  34285. }
  34286. for (f = 0; f < nbfaces; f++) {
  34287. for (i = 0; i < data.face[f].length - 2; i++) {
  34288. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34289. }
  34290. }
  34291. }
  34292. else {
  34293. for (f = 0; f < nbfaces; f++) {
  34294. var fl = data.face[f].length; // number of vertices of the current face
  34295. ang = 2 * Math.PI / fl;
  34296. x = 0.5 * Math.tan(ang / 2);
  34297. y = 0.5;
  34298. // positions, uvs, colors
  34299. for (i = 0; i < fl; i++) {
  34300. // positions
  34301. 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);
  34302. indexes.push(index);
  34303. index++;
  34304. // uvs
  34305. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34306. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34307. uvs.push(u, v);
  34308. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34309. y = x * Math.sin(ang) + y * Math.cos(ang);
  34310. x = tmp;
  34311. // colors
  34312. if (faceColors) {
  34313. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34314. }
  34315. }
  34316. // indices from indexes
  34317. for (i = 0; i < fl - 2; i++) {
  34318. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34319. }
  34320. faceIdx += fl;
  34321. }
  34322. }
  34323. VertexData.ComputeNormals(positions, indices, normals);
  34324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34325. var vertexData = new VertexData();
  34326. vertexData.positions = positions;
  34327. vertexData.indices = indices;
  34328. vertexData.normals = normals;
  34329. vertexData.uvs = uvs;
  34330. if (faceColors && flat) {
  34331. vertexData.colors = colors;
  34332. }
  34333. return vertexData;
  34334. };
  34335. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34336. /**
  34337. * Creates the VertexData of the Torus Knot.
  34338. */
  34339. VertexData.CreateTorusKnot = function (options) {
  34340. var indices = new Array();
  34341. var positions = new Array();
  34342. var normals = new Array();
  34343. var uvs = new Array();
  34344. var radius = options.radius || 2;
  34345. var tube = options.tube || 0.5;
  34346. var radialSegments = options.radialSegments || 32;
  34347. var tubularSegments = options.tubularSegments || 32;
  34348. var p = options.p || 2;
  34349. var q = options.q || 3;
  34350. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34351. // Helper
  34352. var getPos = function (angle) {
  34353. var cu = Math.cos(angle);
  34354. var su = Math.sin(angle);
  34355. var quOverP = q / p * angle;
  34356. var cs = Math.cos(quOverP);
  34357. var tx = radius * (2 + cs) * 0.5 * cu;
  34358. var ty = radius * (2 + cs) * su * 0.5;
  34359. var tz = radius * Math.sin(quOverP) * 0.5;
  34360. return new BABYLON.Vector3(tx, ty, tz);
  34361. };
  34362. // Vertices
  34363. var i;
  34364. var j;
  34365. for (i = 0; i <= radialSegments; i++) {
  34366. var modI = i % radialSegments;
  34367. var u = modI / radialSegments * 2 * p * Math.PI;
  34368. var p1 = getPos(u);
  34369. var p2 = getPos(u + 0.01);
  34370. var tang = p2.subtract(p1);
  34371. var n = p2.add(p1);
  34372. var bitan = BABYLON.Vector3.Cross(tang, n);
  34373. n = BABYLON.Vector3.Cross(bitan, tang);
  34374. bitan.normalize();
  34375. n.normalize();
  34376. for (j = 0; j < tubularSegments; j++) {
  34377. var modJ = j % tubularSegments;
  34378. var v = modJ / tubularSegments * 2 * Math.PI;
  34379. var cx = -tube * Math.cos(v);
  34380. var cy = tube * Math.sin(v);
  34381. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34382. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34383. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34384. uvs.push(i / radialSegments);
  34385. uvs.push(j / tubularSegments);
  34386. }
  34387. }
  34388. for (i = 0; i < radialSegments; i++) {
  34389. for (j = 0; j < tubularSegments; j++) {
  34390. var jNext = (j + 1) % tubularSegments;
  34391. var a = i * tubularSegments + j;
  34392. var b = (i + 1) * tubularSegments + j;
  34393. var c = (i + 1) * tubularSegments + jNext;
  34394. var d = i * tubularSegments + jNext;
  34395. indices.push(d);
  34396. indices.push(b);
  34397. indices.push(a);
  34398. indices.push(d);
  34399. indices.push(c);
  34400. indices.push(b);
  34401. }
  34402. }
  34403. // Normals
  34404. VertexData.ComputeNormals(positions, indices, normals);
  34405. // Sides
  34406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34407. // Result
  34408. var vertexData = new VertexData();
  34409. vertexData.indices = indices;
  34410. vertexData.positions = positions;
  34411. vertexData.normals = normals;
  34412. vertexData.uvs = uvs;
  34413. return vertexData;
  34414. };
  34415. // Tools
  34416. /**
  34417. * @param {any} - positions (number[] or Float32Array)
  34418. * @param {any} - indices (number[] or Uint16Array)
  34419. * @param {any} - normals (number[] or Float32Array)
  34420. * options (optional) :
  34421. * facetPositions : optional array of facet positions (vector3)
  34422. * facetNormals : optional array of facet normals (vector3)
  34423. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34424. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34425. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34426. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34427. * bInfo : optional bounding info, required for facetPartitioning computation
  34428. * useRightHandedSystem: optional boolean to for right handed system computation
  34429. * depthSort : optional boolean to enable the facet depth sort computation
  34430. * distanceTo : optional Vector3 to compute the facet depth from this location
  34431. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34432. */
  34433. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34434. // temporary scalar variables
  34435. var index = 0; // facet index
  34436. var p1p2x = 0.0; // p1p2 vector x coordinate
  34437. var p1p2y = 0.0; // p1p2 vector y coordinate
  34438. var p1p2z = 0.0; // p1p2 vector z coordinate
  34439. var p3p2x = 0.0; // p3p2 vector x coordinate
  34440. var p3p2y = 0.0; // p3p2 vector y coordinate
  34441. var p3p2z = 0.0; // p3p2 vector z coordinate
  34442. var faceNormalx = 0.0; // facet normal x coordinate
  34443. var faceNormaly = 0.0; // facet normal y coordinate
  34444. var faceNormalz = 0.0; // facet normal z coordinate
  34445. var length = 0.0; // facet normal length before normalization
  34446. var v1x = 0; // vector1 x index in the positions array
  34447. var v1y = 0; // vector1 y index in the positions array
  34448. var v1z = 0; // vector1 z index in the positions array
  34449. var v2x = 0; // vector2 x index in the positions array
  34450. var v2y = 0; // vector2 y index in the positions array
  34451. var v2z = 0; // vector2 z index in the positions array
  34452. var v3x = 0; // vector3 x index in the positions array
  34453. var v3y = 0; // vector3 y index in the positions array
  34454. var v3z = 0; // vector3 z index in the positions array
  34455. var computeFacetNormals = false;
  34456. var computeFacetPositions = false;
  34457. var computeFacetPartitioning = false;
  34458. var computeDepthSort = false;
  34459. var faceNormalSign = 1;
  34460. var ratio = 0;
  34461. var distanceTo = null;
  34462. if (options) {
  34463. computeFacetNormals = (options.facetNormals) ? true : false;
  34464. computeFacetPositions = (options.facetPositions) ? true : false;
  34465. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34466. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34467. ratio = options.ratio || 0;
  34468. computeDepthSort = (options.depthSort) ? true : false;
  34469. distanceTo = (options.distanceTo);
  34470. if (computeDepthSort) {
  34471. if (distanceTo === undefined) {
  34472. distanceTo = BABYLON.Vector3.Zero();
  34473. }
  34474. var depthSortedFacets = options.depthSortedFacets;
  34475. }
  34476. }
  34477. // facetPartitioning reinit if needed
  34478. var xSubRatio = 0;
  34479. var ySubRatio = 0;
  34480. var zSubRatio = 0;
  34481. var subSq = 0;
  34482. if (computeFacetPartitioning && options && options.bbSize) {
  34483. var ox = 0; // X partitioning index for facet position
  34484. var oy = 0; // Y partinioning index for facet position
  34485. var oz = 0; // Z partinioning index for facet position
  34486. var b1x = 0; // X partitioning index for facet v1 vertex
  34487. var b1y = 0; // Y partitioning index for facet v1 vertex
  34488. var b1z = 0; // z partitioning index for facet v1 vertex
  34489. var b2x = 0; // X partitioning index for facet v2 vertex
  34490. var b2y = 0; // Y partitioning index for facet v2 vertex
  34491. var b2z = 0; // Z partitioning index for facet v2 vertex
  34492. var b3x = 0; // X partitioning index for facet v3 vertex
  34493. var b3y = 0; // Y partitioning index for facet v3 vertex
  34494. var b3z = 0; // Z partitioning index for facet v3 vertex
  34495. var block_idx_o = 0; // facet barycenter block index
  34496. var block_idx_v1 = 0; // v1 vertex block index
  34497. var block_idx_v2 = 0; // v2 vertex block index
  34498. var block_idx_v3 = 0; // v3 vertex block index
  34499. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34500. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34501. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34502. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34503. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34504. subSq = options.subDiv.max * options.subDiv.max;
  34505. options.facetPartitioning.length = 0;
  34506. }
  34507. // reset the normals
  34508. for (index = 0; index < positions.length; index++) {
  34509. normals[index] = 0.0;
  34510. }
  34511. // Loop : 1 indice triplet = 1 facet
  34512. var nbFaces = (indices.length / 3) | 0;
  34513. for (index = 0; index < nbFaces; index++) {
  34514. // get the indexes of the coordinates of each vertex of the facet
  34515. v1x = indices[index * 3] * 3;
  34516. v1y = v1x + 1;
  34517. v1z = v1x + 2;
  34518. v2x = indices[index * 3 + 1] * 3;
  34519. v2y = v2x + 1;
  34520. v2z = v2x + 2;
  34521. v3x = indices[index * 3 + 2] * 3;
  34522. v3y = v3x + 1;
  34523. v3z = v3x + 2;
  34524. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34525. p1p2y = positions[v1y] - positions[v2y];
  34526. p1p2z = positions[v1z] - positions[v2z];
  34527. p3p2x = positions[v3x] - positions[v2x];
  34528. p3p2y = positions[v3y] - positions[v2y];
  34529. p3p2z = positions[v3z] - positions[v2z];
  34530. // compute the face normal with the cross product
  34531. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34532. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34533. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34534. // normalize this normal and store it in the array facetData
  34535. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34536. length = (length === 0) ? 1.0 : length;
  34537. faceNormalx /= length;
  34538. faceNormaly /= length;
  34539. faceNormalz /= length;
  34540. if (computeFacetNormals && options) {
  34541. options.facetNormals[index].x = faceNormalx;
  34542. options.facetNormals[index].y = faceNormaly;
  34543. options.facetNormals[index].z = faceNormalz;
  34544. }
  34545. if (computeFacetPositions && options) {
  34546. // compute and the facet barycenter coordinates in the array facetPositions
  34547. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34548. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34549. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34550. }
  34551. if (computeFacetPartitioning && options) {
  34552. // store the facet indexes in arrays in the main facetPartitioning array :
  34553. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34554. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34555. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34556. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34557. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34558. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34559. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34560. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34561. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34562. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34563. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34564. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34565. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34566. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34567. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34568. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34569. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34570. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34571. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34572. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34573. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34574. // push each facet index in each block containing the vertex
  34575. options.facetPartitioning[block_idx_v1].push(index);
  34576. if (block_idx_v2 != block_idx_v1) {
  34577. options.facetPartitioning[block_idx_v2].push(index);
  34578. }
  34579. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34580. options.facetPartitioning[block_idx_v3].push(index);
  34581. }
  34582. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34583. options.facetPartitioning[block_idx_o].push(index);
  34584. }
  34585. }
  34586. if (computeDepthSort && options && options.facetPositions) {
  34587. var dsf = depthSortedFacets[index];
  34588. dsf.ind = index * 3;
  34589. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34590. }
  34591. // compute the normals anyway
  34592. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34593. normals[v1y] += faceNormaly;
  34594. normals[v1z] += faceNormalz;
  34595. normals[v2x] += faceNormalx;
  34596. normals[v2y] += faceNormaly;
  34597. normals[v2z] += faceNormalz;
  34598. normals[v3x] += faceNormalx;
  34599. normals[v3y] += faceNormaly;
  34600. normals[v3z] += faceNormalz;
  34601. }
  34602. // last normalization of each normal
  34603. for (index = 0; index < normals.length / 3; index++) {
  34604. faceNormalx = normals[index * 3];
  34605. faceNormaly = normals[index * 3 + 1];
  34606. faceNormalz = normals[index * 3 + 2];
  34607. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34608. length = (length === 0) ? 1.0 : length;
  34609. faceNormalx /= length;
  34610. faceNormaly /= length;
  34611. faceNormalz /= length;
  34612. normals[index * 3] = faceNormalx;
  34613. normals[index * 3 + 1] = faceNormaly;
  34614. normals[index * 3 + 2] = faceNormalz;
  34615. }
  34616. };
  34617. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34618. var li = indices.length;
  34619. var ln = normals.length;
  34620. var i;
  34621. var n;
  34622. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34623. switch (sideOrientation) {
  34624. case BABYLON.Mesh.FRONTSIDE:
  34625. // nothing changed
  34626. break;
  34627. case BABYLON.Mesh.BACKSIDE:
  34628. var tmp;
  34629. // indices
  34630. for (i = 0; i < li; i += 3) {
  34631. tmp = indices[i];
  34632. indices[i] = indices[i + 2];
  34633. indices[i + 2] = tmp;
  34634. }
  34635. // normals
  34636. for (n = 0; n < ln; n++) {
  34637. normals[n] = -normals[n];
  34638. }
  34639. break;
  34640. case BABYLON.Mesh.DOUBLESIDE:
  34641. // positions
  34642. var lp = positions.length;
  34643. var l = lp / 3;
  34644. for (var p = 0; p < lp; p++) {
  34645. positions[lp + p] = positions[p];
  34646. }
  34647. // indices
  34648. for (i = 0; i < li; i += 3) {
  34649. indices[i + li] = indices[i + 2] + l;
  34650. indices[i + 1 + li] = indices[i + 1] + l;
  34651. indices[i + 2 + li] = indices[i] + l;
  34652. }
  34653. // normals
  34654. for (n = 0; n < ln; n++) {
  34655. normals[ln + n] = -normals[n];
  34656. }
  34657. // uvs
  34658. var lu = uvs.length;
  34659. var u = 0;
  34660. for (u = 0; u < lu; u++) {
  34661. uvs[u + lu] = uvs[u];
  34662. }
  34663. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34664. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34665. u = 0;
  34666. for (i = 0; i < lu / 2; i++) {
  34667. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34668. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34669. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34670. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34671. u += 2;
  34672. }
  34673. break;
  34674. }
  34675. };
  34676. /**
  34677. * Creates a new VertexData from the imported parameters.
  34678. */
  34679. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34680. var vertexData = new VertexData();
  34681. // positions
  34682. var positions = parsedVertexData.positions;
  34683. if (positions) {
  34684. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34685. }
  34686. // normals
  34687. var normals = parsedVertexData.normals;
  34688. if (normals) {
  34689. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34690. }
  34691. // tangents
  34692. var tangents = parsedVertexData.tangents;
  34693. if (tangents) {
  34694. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34695. }
  34696. // uvs
  34697. var uvs = parsedVertexData.uvs;
  34698. if (uvs) {
  34699. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34700. }
  34701. // uv2s
  34702. var uv2s = parsedVertexData.uv2s;
  34703. if (uv2s) {
  34704. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34705. }
  34706. // uv3s
  34707. var uv3s = parsedVertexData.uv3s;
  34708. if (uv3s) {
  34709. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34710. }
  34711. // uv4s
  34712. var uv4s = parsedVertexData.uv4s;
  34713. if (uv4s) {
  34714. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34715. }
  34716. // uv5s
  34717. var uv5s = parsedVertexData.uv5s;
  34718. if (uv5s) {
  34719. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34720. }
  34721. // uv6s
  34722. var uv6s = parsedVertexData.uv6s;
  34723. if (uv6s) {
  34724. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34725. }
  34726. // colors
  34727. var colors = parsedVertexData.colors;
  34728. if (colors) {
  34729. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34730. }
  34731. // matricesIndices
  34732. var matricesIndices = parsedVertexData.matricesIndices;
  34733. if (matricesIndices) {
  34734. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34735. }
  34736. // matricesWeights
  34737. var matricesWeights = parsedVertexData.matricesWeights;
  34738. if (matricesWeights) {
  34739. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34740. }
  34741. // indices
  34742. var indices = parsedVertexData.indices;
  34743. if (indices) {
  34744. vertexData.indices = indices;
  34745. }
  34746. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34747. };
  34748. return VertexData;
  34749. }());
  34750. BABYLON.VertexData = VertexData;
  34751. })(BABYLON || (BABYLON = {}));
  34752. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34753. var BABYLON;
  34754. (function (BABYLON) {
  34755. /**
  34756. * Class used to store geometry data (vertex buffers + index buffer)
  34757. */
  34758. var Geometry = /** @class */ (function () {
  34759. /**
  34760. * Creates a new geometry
  34761. * @param id defines the unique ID
  34762. * @param scene defines the hosting scene
  34763. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34764. * @param updatable defines if geometry must be updatable (false by default)
  34765. * @param mesh defines the mesh that will be associated with the geometry
  34766. */
  34767. function Geometry(id, scene, vertexData, updatable, mesh) {
  34768. if (updatable === void 0) { updatable = false; }
  34769. if (mesh === void 0) { mesh = null; }
  34770. /**
  34771. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34772. */
  34773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34774. this._totalVertices = 0;
  34775. this._isDisposed = false;
  34776. this._indexBufferIsUpdatable = false;
  34777. this.id = id;
  34778. this._engine = scene.getEngine();
  34779. this._meshes = [];
  34780. this._scene = scene;
  34781. //Init vertex buffer cache
  34782. this._vertexBuffers = {};
  34783. this._indices = [];
  34784. this._updatable = updatable;
  34785. // vertexData
  34786. if (vertexData) {
  34787. this.setAllVerticesData(vertexData, updatable);
  34788. }
  34789. else {
  34790. this._totalVertices = 0;
  34791. this._indices = [];
  34792. }
  34793. if (this._engine.getCaps().vertexArrayObject) {
  34794. this._vertexArrayObjects = {};
  34795. }
  34796. // applyToMesh
  34797. if (mesh) {
  34798. if (mesh.getClassName() === "LinesMesh") {
  34799. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34800. this.updateExtend();
  34801. }
  34802. this.applyToMesh(mesh);
  34803. mesh.computeWorldMatrix(true);
  34804. }
  34805. }
  34806. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34807. /**
  34808. * 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
  34809. */
  34810. get: function () {
  34811. return this._boundingBias;
  34812. },
  34813. /**
  34814. * 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
  34815. */
  34816. set: function (value) {
  34817. if (this._boundingBias && this._boundingBias.equals(value)) {
  34818. return;
  34819. }
  34820. this._boundingBias = value.clone();
  34821. this.updateBoundingInfo(true, null);
  34822. },
  34823. enumerable: true,
  34824. configurable: true
  34825. });
  34826. /**
  34827. * Static function used to attach a new empty geometry to a mesh
  34828. * @param mesh defines the mesh to attach the geometry to
  34829. * @returns the new {BABYLON.Geometry}
  34830. */
  34831. Geometry.CreateGeometryForMesh = function (mesh) {
  34832. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34833. geometry.applyToMesh(mesh);
  34834. return geometry;
  34835. };
  34836. Object.defineProperty(Geometry.prototype, "extend", {
  34837. /**
  34838. * Gets the current extend of the geometry
  34839. */
  34840. get: function () {
  34841. return this._extend;
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. /**
  34847. * Gets the hosting scene
  34848. * @returns the hosting {BABYLON.Scene}
  34849. */
  34850. Geometry.prototype.getScene = function () {
  34851. return this._scene;
  34852. };
  34853. /**
  34854. * Gets the hosting engine
  34855. * @returns the hosting {BABYLON.Engine}
  34856. */
  34857. Geometry.prototype.getEngine = function () {
  34858. return this._engine;
  34859. };
  34860. /**
  34861. * Defines if the geometry is ready to use
  34862. * @returns true if the geometry is ready to be used
  34863. */
  34864. Geometry.prototype.isReady = function () {
  34865. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34866. };
  34867. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34868. /**
  34869. * Gets a value indicating that the geometry should not be serialized
  34870. */
  34871. get: function () {
  34872. for (var index = 0; index < this._meshes.length; index++) {
  34873. if (!this._meshes[index].doNotSerialize) {
  34874. return false;
  34875. }
  34876. }
  34877. return true;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. /** @ignore */
  34883. Geometry.prototype._rebuild = function () {
  34884. if (this._vertexArrayObjects) {
  34885. this._vertexArrayObjects = {};
  34886. }
  34887. // Index buffer
  34888. if (this._meshes.length !== 0 && this._indices) {
  34889. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34890. }
  34891. // Vertex buffers
  34892. for (var key in this._vertexBuffers) {
  34893. var vertexBuffer = this._vertexBuffers[key];
  34894. vertexBuffer._rebuild();
  34895. }
  34896. };
  34897. /**
  34898. * Affects all gemetry data in one call
  34899. * @param vertexData defines the geometry data
  34900. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34901. */
  34902. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34903. vertexData.applyToGeometry(this, updatable);
  34904. this.notifyUpdate();
  34905. };
  34906. /**
  34907. * Set specific vertex data
  34908. * @param kind defines the data kind (Position, normal, etc...)
  34909. * @param data defines the vertex data to use
  34910. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34911. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34912. */
  34913. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34914. if (updatable === void 0) { updatable = false; }
  34915. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34916. this.setVerticesBuffer(buffer);
  34917. };
  34918. /**
  34919. * Removes a specific vertex data
  34920. * @param kind defines the data kind (Position, normal, etc...)
  34921. */
  34922. Geometry.prototype.removeVerticesData = function (kind) {
  34923. if (this._vertexBuffers[kind]) {
  34924. this._vertexBuffers[kind].dispose();
  34925. delete this._vertexBuffers[kind];
  34926. }
  34927. };
  34928. /**
  34929. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34930. * @param buffer defines the vertex buffer to use
  34931. */
  34932. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34933. var kind = buffer.getKind();
  34934. if (this._vertexBuffers[kind]) {
  34935. this._vertexBuffers[kind].dispose();
  34936. }
  34937. this._vertexBuffers[kind] = buffer;
  34938. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34939. var data = buffer.getData();
  34940. var stride = buffer.getStrideSize();
  34941. this._totalVertices = data.length / stride;
  34942. this.updateExtend(data, stride);
  34943. this._resetPointsArrayCache();
  34944. var meshes = this._meshes;
  34945. var numOfMeshes = meshes.length;
  34946. for (var index = 0; index < numOfMeshes; index++) {
  34947. var mesh = meshes[index];
  34948. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34949. mesh._createGlobalSubMesh(false);
  34950. mesh.computeWorldMatrix(true);
  34951. }
  34952. }
  34953. this.notifyUpdate(kind);
  34954. if (this._vertexArrayObjects) {
  34955. this._disposeVertexArrayObjects();
  34956. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34957. }
  34958. };
  34959. /**
  34960. * Update a specific vertex buffer
  34961. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34962. * It will do nothing if the buffer is not updatable
  34963. * @param kind defines the data kind (Position, normal, etc...)
  34964. * @param data defines the data to use
  34965. * @param offset defines the offset in the target buffer where to store the data
  34966. */
  34967. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34968. var vertexBuffer = this.getVertexBuffer(kind);
  34969. if (!vertexBuffer) {
  34970. return;
  34971. }
  34972. vertexBuffer.updateDirectly(data, offset);
  34973. this.notifyUpdate(kind);
  34974. };
  34975. /**
  34976. * Update a specific vertex buffer
  34977. * This function will create a new buffer if the current one is not updatable
  34978. * @param kind defines the data kind (Position, normal, etc...)
  34979. * @param data defines the data to use
  34980. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34981. */
  34982. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34983. if (updateExtends === void 0) { updateExtends = false; }
  34984. var vertexBuffer = this.getVertexBuffer(kind);
  34985. if (!vertexBuffer) {
  34986. return;
  34987. }
  34988. vertexBuffer.update(data);
  34989. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34990. var stride = vertexBuffer.getStrideSize();
  34991. this._totalVertices = data.length / stride;
  34992. this.updateBoundingInfo(updateExtends, data);
  34993. }
  34994. this.notifyUpdate(kind);
  34995. };
  34996. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34997. if (updateExtends) {
  34998. this.updateExtend(data);
  34999. }
  35000. var meshes = this._meshes;
  35001. var numOfMeshes = meshes.length;
  35002. this._resetPointsArrayCache();
  35003. for (var index = 0; index < numOfMeshes; index++) {
  35004. var mesh = meshes[index];
  35005. if (updateExtends) {
  35006. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35007. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35008. var subMesh = mesh.subMeshes[subIndex];
  35009. subMesh.refreshBoundingInfo();
  35010. }
  35011. }
  35012. }
  35013. };
  35014. /** @ignore */
  35015. Geometry.prototype._bind = function (effect, indexToBind) {
  35016. if (!effect) {
  35017. return;
  35018. }
  35019. if (indexToBind === undefined) {
  35020. indexToBind = this._indexBuffer;
  35021. }
  35022. var vbs = this.getVertexBuffers();
  35023. if (!vbs) {
  35024. return;
  35025. }
  35026. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35027. this._engine.bindBuffers(vbs, indexToBind, effect);
  35028. return;
  35029. }
  35030. // Using VAO
  35031. if (!this._vertexArrayObjects[effect.key]) {
  35032. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35033. }
  35034. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35035. };
  35036. /**
  35037. * Gets total number of vertices
  35038. * @returns the total number of vertices
  35039. */
  35040. Geometry.prototype.getTotalVertices = function () {
  35041. if (!this.isReady()) {
  35042. return 0;
  35043. }
  35044. return this._totalVertices;
  35045. };
  35046. /**
  35047. * Gets a specific vertex data attached to this geometry
  35048. * @param kind defines the data kind (Position, normal, etc...)
  35049. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35050. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35051. * @returns a float array containing vertex data
  35052. */
  35053. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35054. var vertexBuffer = this.getVertexBuffer(kind);
  35055. if (!vertexBuffer) {
  35056. return null;
  35057. }
  35058. var orig = vertexBuffer.getData();
  35059. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35060. return orig;
  35061. }
  35062. else {
  35063. var len = orig.length;
  35064. var copy = [];
  35065. for (var i = 0; i < len; i++) {
  35066. copy.push(orig[i]);
  35067. }
  35068. return copy;
  35069. }
  35070. };
  35071. /**
  35072. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35073. * @param kind defines the data kind (Position, normal, etc...)
  35074. * @returns true if the vertex buffer with the specified kind is updatable
  35075. */
  35076. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35077. var vb = this._vertexBuffers[kind];
  35078. if (!vb) {
  35079. return false;
  35080. }
  35081. return vb.isUpdatable();
  35082. };
  35083. /**
  35084. * Gets a specific vertex buffer
  35085. * @param kind defines the data kind (Position, normal, etc...)
  35086. * @returns a {BABYLON.VertexBuffer}
  35087. */
  35088. Geometry.prototype.getVertexBuffer = function (kind) {
  35089. if (!this.isReady()) {
  35090. return null;
  35091. }
  35092. return this._vertexBuffers[kind];
  35093. };
  35094. /**
  35095. * Returns all vertex buffers
  35096. * @return an object holding all vertex buffers indexed by kind
  35097. */
  35098. Geometry.prototype.getVertexBuffers = function () {
  35099. if (!this.isReady()) {
  35100. return null;
  35101. }
  35102. return this._vertexBuffers;
  35103. };
  35104. /**
  35105. * Gets a boolean indicating if specific vertex buffer is present
  35106. * @param kind defines the data kind (Position, normal, etc...)
  35107. * @returns true if data is present
  35108. */
  35109. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35110. if (!this._vertexBuffers) {
  35111. if (this._delayInfo) {
  35112. return this._delayInfo.indexOf(kind) !== -1;
  35113. }
  35114. return false;
  35115. }
  35116. return this._vertexBuffers[kind] !== undefined;
  35117. };
  35118. /**
  35119. * Gets a list of all attached data kinds (Position, normal, etc...)
  35120. * @returns a list of string containing all kinds
  35121. */
  35122. Geometry.prototype.getVerticesDataKinds = function () {
  35123. var result = [];
  35124. var kind;
  35125. if (!this._vertexBuffers && this._delayInfo) {
  35126. for (kind in this._delayInfo) {
  35127. result.push(kind);
  35128. }
  35129. }
  35130. else {
  35131. for (kind in this._vertexBuffers) {
  35132. result.push(kind);
  35133. }
  35134. }
  35135. return result;
  35136. };
  35137. /**
  35138. * Update index buffer
  35139. * @param indices defines the indices to store in the index buffer
  35140. * @param offset defines the offset in the target buffer where to store the data
  35141. */
  35142. Geometry.prototype.updateIndices = function (indices, offset) {
  35143. if (!this._indexBuffer) {
  35144. return;
  35145. }
  35146. if (!this._indexBufferIsUpdatable) {
  35147. this.setIndices(indices, null, true);
  35148. }
  35149. else {
  35150. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35151. }
  35152. };
  35153. /**
  35154. * Creates a new index buffer
  35155. * @param indices defines the indices to store in the index buffer
  35156. * @param totalVertices defines the total number of vertices (could be null)
  35157. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35158. */
  35159. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35160. if (totalVertices === void 0) { totalVertices = null; }
  35161. if (updatable === void 0) { updatable = false; }
  35162. if (this._indexBuffer) {
  35163. this._engine._releaseBuffer(this._indexBuffer);
  35164. }
  35165. this._disposeVertexArrayObjects();
  35166. this._indices = indices;
  35167. this._indexBufferIsUpdatable = updatable;
  35168. if (this._meshes.length !== 0 && this._indices) {
  35169. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35170. }
  35171. if (totalVertices != undefined) {
  35172. this._totalVertices = totalVertices;
  35173. }
  35174. var meshes = this._meshes;
  35175. var numOfMeshes = meshes.length;
  35176. for (var index = 0; index < numOfMeshes; index++) {
  35177. meshes[index]._createGlobalSubMesh(true);
  35178. }
  35179. this.notifyUpdate();
  35180. };
  35181. /**
  35182. * Return the total number of indices
  35183. * @returns the total number of indices
  35184. */
  35185. Geometry.prototype.getTotalIndices = function () {
  35186. if (!this.isReady()) {
  35187. return 0;
  35188. }
  35189. return this._indices.length;
  35190. };
  35191. /**
  35192. * Gets the index buffer array
  35193. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35194. * @returns the index buffer array
  35195. */
  35196. Geometry.prototype.getIndices = function (copyWhenShared) {
  35197. if (!this.isReady()) {
  35198. return null;
  35199. }
  35200. var orig = this._indices;
  35201. if (!copyWhenShared || this._meshes.length === 1) {
  35202. return orig;
  35203. }
  35204. else {
  35205. var len = orig.length;
  35206. var copy = [];
  35207. for (var i = 0; i < len; i++) {
  35208. copy.push(orig[i]);
  35209. }
  35210. return copy;
  35211. }
  35212. };
  35213. /**
  35214. * Gets the index buffer
  35215. * @return the index buffer
  35216. */
  35217. Geometry.prototype.getIndexBuffer = function () {
  35218. if (!this.isReady()) {
  35219. return null;
  35220. }
  35221. return this._indexBuffer;
  35222. };
  35223. /** @ignore */
  35224. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35225. if (effect === void 0) { effect = null; }
  35226. if (!effect || !this._vertexArrayObjects) {
  35227. return;
  35228. }
  35229. if (this._vertexArrayObjects[effect.key]) {
  35230. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35231. delete this._vertexArrayObjects[effect.key];
  35232. }
  35233. };
  35234. /**
  35235. * Release the associated resources for a specific mesh
  35236. * @param mesh defines the source mesh
  35237. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35238. */
  35239. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35240. var meshes = this._meshes;
  35241. var index = meshes.indexOf(mesh);
  35242. if (index === -1) {
  35243. return;
  35244. }
  35245. meshes.splice(index, 1);
  35246. mesh._geometry = null;
  35247. if (meshes.length === 0 && shouldDispose) {
  35248. this.dispose();
  35249. }
  35250. };
  35251. /**
  35252. * Apply current geometry to a given mesh
  35253. * @param mesh defines the mesh to apply geometry to
  35254. */
  35255. Geometry.prototype.applyToMesh = function (mesh) {
  35256. if (mesh._geometry === this) {
  35257. return;
  35258. }
  35259. var previousGeometry = mesh._geometry;
  35260. if (previousGeometry) {
  35261. previousGeometry.releaseForMesh(mesh);
  35262. }
  35263. var meshes = this._meshes;
  35264. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35265. mesh._geometry = this;
  35266. this._scene.pushGeometry(this);
  35267. meshes.push(mesh);
  35268. if (this.isReady()) {
  35269. this._applyToMesh(mesh);
  35270. }
  35271. else {
  35272. mesh._boundingInfo = this._boundingInfo;
  35273. }
  35274. };
  35275. Geometry.prototype.updateExtend = function (data, stride) {
  35276. if (data === void 0) { data = null; }
  35277. if (!data) {
  35278. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35279. }
  35280. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35281. };
  35282. Geometry.prototype._applyToMesh = function (mesh) {
  35283. var numOfMeshes = this._meshes.length;
  35284. // vertexBuffers
  35285. for (var kind in this._vertexBuffers) {
  35286. if (numOfMeshes === 1) {
  35287. this._vertexBuffers[kind].create();
  35288. }
  35289. var buffer = this._vertexBuffers[kind].getBuffer();
  35290. if (buffer)
  35291. buffer.references = numOfMeshes;
  35292. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35293. if (!this._extend) {
  35294. this.updateExtend(this._vertexBuffers[kind].getData());
  35295. }
  35296. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35297. mesh._createGlobalSubMesh(false);
  35298. //bounding info was just created again, world matrix should be applied again.
  35299. mesh._updateBoundingInfo();
  35300. }
  35301. }
  35302. // indexBuffer
  35303. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35304. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35305. }
  35306. if (this._indexBuffer) {
  35307. this._indexBuffer.references = numOfMeshes;
  35308. }
  35309. };
  35310. Geometry.prototype.notifyUpdate = function (kind) {
  35311. if (this.onGeometryUpdated) {
  35312. this.onGeometryUpdated(this, kind);
  35313. }
  35314. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35315. var mesh = _a[_i];
  35316. mesh._markSubMeshesAsAttributesDirty();
  35317. }
  35318. };
  35319. /**
  35320. * Load the geometry if it was flagged as delay loaded
  35321. * @param scene defines the hosting scene
  35322. * @param onLoaded defines a callback called when the geometry is loaded
  35323. */
  35324. Geometry.prototype.load = function (scene, onLoaded) {
  35325. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35326. return;
  35327. }
  35328. if (this.isReady()) {
  35329. if (onLoaded) {
  35330. onLoaded();
  35331. }
  35332. return;
  35333. }
  35334. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35335. this._queueLoad(scene, onLoaded);
  35336. };
  35337. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35338. var _this = this;
  35339. if (!this.delayLoadingFile) {
  35340. return;
  35341. }
  35342. scene._addPendingData(this);
  35343. scene._loadFile(this.delayLoadingFile, function (data) {
  35344. if (!_this._delayLoadingFunction) {
  35345. return;
  35346. }
  35347. _this._delayLoadingFunction(JSON.parse(data), _this);
  35348. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35349. _this._delayInfo = [];
  35350. scene._removePendingData(_this);
  35351. var meshes = _this._meshes;
  35352. var numOfMeshes = meshes.length;
  35353. for (var index = 0; index < numOfMeshes; index++) {
  35354. _this._applyToMesh(meshes[index]);
  35355. }
  35356. if (onLoaded) {
  35357. onLoaded();
  35358. }
  35359. }, undefined, true);
  35360. };
  35361. /**
  35362. * Invert the geometry to move from a right handed system to a left handed one.
  35363. */
  35364. Geometry.prototype.toLeftHanded = function () {
  35365. // Flip faces
  35366. var tIndices = this.getIndices(false);
  35367. if (tIndices != null && tIndices.length > 0) {
  35368. for (var i = 0; i < tIndices.length; i += 3) {
  35369. var tTemp = tIndices[i + 0];
  35370. tIndices[i + 0] = tIndices[i + 2];
  35371. tIndices[i + 2] = tTemp;
  35372. }
  35373. this.setIndices(tIndices);
  35374. }
  35375. // Negate position.z
  35376. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35377. if (tPositions != null && tPositions.length > 0) {
  35378. for (var i = 0; i < tPositions.length; i += 3) {
  35379. tPositions[i + 2] = -tPositions[i + 2];
  35380. }
  35381. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35382. }
  35383. // Negate normal.z
  35384. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35385. if (tNormals != null && tNormals.length > 0) {
  35386. for (var i = 0; i < tNormals.length; i += 3) {
  35387. tNormals[i + 2] = -tNormals[i + 2];
  35388. }
  35389. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35390. }
  35391. };
  35392. // Cache
  35393. /** @ignore */
  35394. Geometry.prototype._resetPointsArrayCache = function () {
  35395. this._positions = null;
  35396. };
  35397. /** @ignore */
  35398. Geometry.prototype._generatePointsArray = function () {
  35399. if (this._positions)
  35400. return true;
  35401. this._positions = [];
  35402. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35403. if (!data) {
  35404. return false;
  35405. }
  35406. for (var index = 0; index < data.length; index += 3) {
  35407. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35408. }
  35409. return true;
  35410. };
  35411. /**
  35412. * Gets a value indicating if the geometry is disposed
  35413. * @returns true if the geometry was disposed
  35414. */
  35415. Geometry.prototype.isDisposed = function () {
  35416. return this._isDisposed;
  35417. };
  35418. Geometry.prototype._disposeVertexArrayObjects = function () {
  35419. if (this._vertexArrayObjects) {
  35420. for (var kind in this._vertexArrayObjects) {
  35421. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35422. }
  35423. this._vertexArrayObjects = {};
  35424. }
  35425. };
  35426. /**
  35427. * Free all associated resources
  35428. */
  35429. Geometry.prototype.dispose = function () {
  35430. var meshes = this._meshes;
  35431. var numOfMeshes = meshes.length;
  35432. var index;
  35433. for (index = 0; index < numOfMeshes; index++) {
  35434. this.releaseForMesh(meshes[index]);
  35435. }
  35436. this._meshes = [];
  35437. this._disposeVertexArrayObjects();
  35438. for (var kind in this._vertexBuffers) {
  35439. this._vertexBuffers[kind].dispose();
  35440. }
  35441. this._vertexBuffers = {};
  35442. this._totalVertices = 0;
  35443. if (this._indexBuffer) {
  35444. this._engine._releaseBuffer(this._indexBuffer);
  35445. }
  35446. this._indexBuffer = null;
  35447. this._indices = [];
  35448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35449. this.delayLoadingFile = null;
  35450. this._delayLoadingFunction = null;
  35451. this._delayInfo = [];
  35452. this._boundingInfo = null;
  35453. this._scene.removeGeometry(this);
  35454. this._isDisposed = true;
  35455. };
  35456. /**
  35457. * Clone the current geometry into a new geometry
  35458. * @param id defines the unique ID of the new geometry
  35459. * @returns a new geometry object
  35460. */
  35461. Geometry.prototype.copy = function (id) {
  35462. var vertexData = new BABYLON.VertexData();
  35463. vertexData.indices = [];
  35464. var indices = this.getIndices();
  35465. if (indices) {
  35466. for (var index = 0; index < indices.length; index++) {
  35467. vertexData.indices.push(indices[index]);
  35468. }
  35469. }
  35470. var updatable = false;
  35471. var stopChecking = false;
  35472. var kind;
  35473. for (kind in this._vertexBuffers) {
  35474. // using slice() to make a copy of the array and not just reference it
  35475. var data = this.getVerticesData(kind);
  35476. if (data instanceof Float32Array) {
  35477. vertexData.set(new Float32Array(data), kind);
  35478. }
  35479. else {
  35480. vertexData.set(data.slice(0), kind);
  35481. }
  35482. if (!stopChecking) {
  35483. var vb = this.getVertexBuffer(kind);
  35484. if (vb) {
  35485. updatable = vb.isUpdatable();
  35486. stopChecking = !updatable;
  35487. }
  35488. }
  35489. }
  35490. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35491. geometry.delayLoadState = this.delayLoadState;
  35492. geometry.delayLoadingFile = this.delayLoadingFile;
  35493. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35494. for (kind in this._delayInfo) {
  35495. geometry._delayInfo = geometry._delayInfo || [];
  35496. geometry._delayInfo.push(kind);
  35497. }
  35498. // Bounding info
  35499. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35500. return geometry;
  35501. };
  35502. /**
  35503. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35504. * @return a JSON representation of the current geometry data (without the vertices data)
  35505. */
  35506. Geometry.prototype.serialize = function () {
  35507. var serializationObject = {};
  35508. serializationObject.id = this.id;
  35509. serializationObject.updatable = this._updatable;
  35510. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35511. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35512. }
  35513. return serializationObject;
  35514. };
  35515. Geometry.prototype.toNumberArray = function (origin) {
  35516. if (Array.isArray(origin)) {
  35517. return origin;
  35518. }
  35519. else {
  35520. return Array.prototype.slice.call(origin);
  35521. }
  35522. };
  35523. /**
  35524. * Serialize all vertices data into a JSON oject
  35525. * @returns a JSON representation of the current geometry data
  35526. */
  35527. Geometry.prototype.serializeVerticeData = function () {
  35528. var serializationObject = this.serialize();
  35529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35530. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35531. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35532. serializationObject.positions._updatable = true;
  35533. }
  35534. }
  35535. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35536. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35537. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35538. serializationObject.normals._updatable = true;
  35539. }
  35540. }
  35541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35542. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35543. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35544. serializationObject.tangets._updatable = true;
  35545. }
  35546. }
  35547. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35548. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35549. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35550. serializationObject.uvs._updatable = true;
  35551. }
  35552. }
  35553. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35554. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35555. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35556. serializationObject.uv2s._updatable = true;
  35557. }
  35558. }
  35559. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35560. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35561. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35562. serializationObject.uv3s._updatable = true;
  35563. }
  35564. }
  35565. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35566. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35567. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35568. serializationObject.uv4s._updatable = true;
  35569. }
  35570. }
  35571. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35572. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35573. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35574. serializationObject.uv5s._updatable = true;
  35575. }
  35576. }
  35577. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35578. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35579. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35580. serializationObject.uv6s._updatable = true;
  35581. }
  35582. }
  35583. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35584. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35585. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35586. serializationObject.colors._updatable = true;
  35587. }
  35588. }
  35589. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35590. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35591. serializationObject.matricesIndices._isExpanded = true;
  35592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35593. serializationObject.matricesIndices._updatable = true;
  35594. }
  35595. }
  35596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35597. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35599. serializationObject.matricesWeights._updatable = true;
  35600. }
  35601. }
  35602. serializationObject.indices = this.toNumberArray(this.getIndices());
  35603. return serializationObject;
  35604. };
  35605. // Statics
  35606. /**
  35607. * Extracts a clone of a mesh geometry
  35608. * @param mesh defines the source mesh
  35609. * @param id defines the unique ID of the new geometry object
  35610. * @returns the new geometry object
  35611. */
  35612. Geometry.ExtractFromMesh = function (mesh, id) {
  35613. var geometry = mesh._geometry;
  35614. if (!geometry) {
  35615. return null;
  35616. }
  35617. return geometry.copy(id);
  35618. };
  35619. /**
  35620. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35621. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35622. * Be aware Math.random() could cause collisions, but:
  35623. * "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"
  35624. * @returns a string containing a new GUID
  35625. */
  35626. Geometry.RandomId = function () {
  35627. return BABYLON.Tools.RandomId();
  35628. };
  35629. /** @ignore */
  35630. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35631. var scene = mesh.getScene();
  35632. // Geometry
  35633. var geometryId = parsedGeometry.geometryId;
  35634. if (geometryId) {
  35635. var geometry = scene.getGeometryByID(geometryId);
  35636. if (geometry) {
  35637. geometry.applyToMesh(mesh);
  35638. }
  35639. }
  35640. else if (parsedGeometry instanceof ArrayBuffer) {
  35641. var binaryInfo = mesh._binaryInfo;
  35642. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35643. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35644. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35645. }
  35646. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35647. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35648. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35649. }
  35650. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35651. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35652. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35653. }
  35654. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35655. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35657. }
  35658. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35659. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35660. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35661. }
  35662. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35663. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35664. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35665. }
  35666. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35667. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35668. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35669. }
  35670. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35671. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35672. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35673. }
  35674. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35675. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35676. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35677. }
  35678. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35679. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35680. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35681. }
  35682. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35683. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35685. }
  35686. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35687. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35689. }
  35690. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35691. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35692. mesh.setIndices(indicesData, null);
  35693. }
  35694. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35695. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35696. mesh.subMeshes = [];
  35697. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35698. var materialIndex = subMeshesData[(i * 5) + 0];
  35699. var verticesStart = subMeshesData[(i * 5) + 1];
  35700. var verticesCount = subMeshesData[(i * 5) + 2];
  35701. var indexStart = subMeshesData[(i * 5) + 3];
  35702. var indexCount = subMeshesData[(i * 5) + 4];
  35703. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35704. }
  35705. }
  35706. }
  35707. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35708. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35710. if (parsedGeometry.tangents) {
  35711. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35712. }
  35713. if (parsedGeometry.uvs) {
  35714. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35715. }
  35716. if (parsedGeometry.uvs2) {
  35717. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35718. }
  35719. if (parsedGeometry.uvs3) {
  35720. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35721. }
  35722. if (parsedGeometry.uvs4) {
  35723. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35724. }
  35725. if (parsedGeometry.uvs5) {
  35726. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35727. }
  35728. if (parsedGeometry.uvs6) {
  35729. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35730. }
  35731. if (parsedGeometry.colors) {
  35732. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35733. }
  35734. if (parsedGeometry.matricesIndices) {
  35735. if (!parsedGeometry.matricesIndices._isExpanded) {
  35736. var floatIndices = [];
  35737. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35738. var matricesIndex = parsedGeometry.matricesIndices[i];
  35739. floatIndices.push(matricesIndex & 0x000000FF);
  35740. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35741. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35742. floatIndices.push(matricesIndex >> 24);
  35743. }
  35744. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35745. }
  35746. else {
  35747. delete parsedGeometry.matricesIndices._isExpanded;
  35748. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35749. }
  35750. }
  35751. if (parsedGeometry.matricesIndicesExtra) {
  35752. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35753. var floatIndices = [];
  35754. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35755. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35756. floatIndices.push(matricesIndex & 0x000000FF);
  35757. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35758. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35759. floatIndices.push(matricesIndex >> 24);
  35760. }
  35761. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35762. }
  35763. else {
  35764. delete parsedGeometry.matricesIndices._isExpanded;
  35765. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35766. }
  35767. }
  35768. if (parsedGeometry.matricesWeights) {
  35769. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35770. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35771. }
  35772. if (parsedGeometry.matricesWeightsExtra) {
  35773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35774. }
  35775. mesh.setIndices(parsedGeometry.indices, null);
  35776. }
  35777. // SubMeshes
  35778. if (parsedGeometry.subMeshes) {
  35779. mesh.subMeshes = [];
  35780. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35781. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35782. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35783. }
  35784. }
  35785. // Flat shading
  35786. if (mesh._shouldGenerateFlatShading) {
  35787. mesh.convertToFlatShadedMesh();
  35788. delete mesh._shouldGenerateFlatShading;
  35789. }
  35790. // Update
  35791. mesh.computeWorldMatrix(true);
  35792. // Octree
  35793. var sceneOctree = scene.selectionOctree;
  35794. if (sceneOctree !== undefined && sceneOctree !== null) {
  35795. sceneOctree.addMesh(mesh);
  35796. }
  35797. };
  35798. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35799. var epsilon = 1e-3;
  35800. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35801. return;
  35802. }
  35803. var noInfluenceBoneIndex = 0.0;
  35804. if (parsedGeometry.skeletonId > -1) {
  35805. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35806. if (!skeleton) {
  35807. return;
  35808. }
  35809. noInfluenceBoneIndex = skeleton.bones.length;
  35810. }
  35811. else {
  35812. return;
  35813. }
  35814. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35815. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35816. var matricesWeights = parsedGeometry.matricesWeights;
  35817. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35818. var influencers = parsedGeometry.numBoneInfluencer;
  35819. var size = matricesWeights.length;
  35820. for (var i = 0; i < size; i += 4) {
  35821. var weight = 0.0;
  35822. var firstZeroWeight = -1;
  35823. for (var j = 0; j < 4; j++) {
  35824. var w = matricesWeights[i + j];
  35825. weight += w;
  35826. if (w < epsilon && firstZeroWeight < 0) {
  35827. firstZeroWeight = j;
  35828. }
  35829. }
  35830. if (matricesWeightsExtra) {
  35831. for (var j = 0; j < 4; j++) {
  35832. var w = matricesWeightsExtra[i + j];
  35833. weight += w;
  35834. if (w < epsilon && firstZeroWeight < 0) {
  35835. firstZeroWeight = j + 4;
  35836. }
  35837. }
  35838. }
  35839. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35840. firstZeroWeight = influencers - 1;
  35841. }
  35842. if (weight > epsilon) {
  35843. var mweight = 1.0 / weight;
  35844. for (var j = 0; j < 4; j++) {
  35845. matricesWeights[i + j] *= mweight;
  35846. }
  35847. if (matricesWeightsExtra) {
  35848. for (var j = 0; j < 4; j++) {
  35849. matricesWeightsExtra[i + j] *= mweight;
  35850. }
  35851. }
  35852. }
  35853. else {
  35854. if (firstZeroWeight >= 4) {
  35855. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35856. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35857. }
  35858. else {
  35859. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35860. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35861. }
  35862. }
  35863. }
  35864. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35865. if (parsedGeometry.matricesWeightsExtra) {
  35866. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35867. }
  35868. };
  35869. /**
  35870. * Create a new geometry from persisted data (Using .babylon file format)
  35871. * @param parsedVertexData defines the persisted data
  35872. * @param scene defines the hosting scene
  35873. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35874. * @returns the new geometry object
  35875. */
  35876. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35877. if (scene.getGeometryByID(parsedVertexData.id)) {
  35878. return null; // null since geometry could be something else than a box...
  35879. }
  35880. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35881. if (BABYLON.Tags) {
  35882. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35883. }
  35884. if (parsedVertexData.delayLoadingFile) {
  35885. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35886. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35887. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35888. geometry._delayInfo = [];
  35889. if (parsedVertexData.hasUVs) {
  35890. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35891. }
  35892. if (parsedVertexData.hasUVs2) {
  35893. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35894. }
  35895. if (parsedVertexData.hasUVs3) {
  35896. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35897. }
  35898. if (parsedVertexData.hasUVs4) {
  35899. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35900. }
  35901. if (parsedVertexData.hasUVs5) {
  35902. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35903. }
  35904. if (parsedVertexData.hasUVs6) {
  35905. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35906. }
  35907. if (parsedVertexData.hasColors) {
  35908. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35909. }
  35910. if (parsedVertexData.hasMatricesIndices) {
  35911. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35912. }
  35913. if (parsedVertexData.hasMatricesWeights) {
  35914. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35915. }
  35916. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35917. }
  35918. else {
  35919. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35920. }
  35921. scene.pushGeometry(geometry, true);
  35922. return geometry;
  35923. };
  35924. return Geometry;
  35925. }());
  35926. BABYLON.Geometry = Geometry;
  35927. // Primitives
  35928. /// Abstract class
  35929. /**
  35930. * Abstract class used to provide common services for all typed geometries
  35931. */
  35932. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35933. __extends(_PrimitiveGeometry, _super);
  35934. /**
  35935. * Creates a new typed geometry
  35936. * @param id defines the unique ID of the geometry
  35937. * @param scene defines the hosting scene
  35938. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35939. * @param mesh defines the hosting mesh (can be null)
  35940. */
  35941. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35942. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35943. if (mesh === void 0) { mesh = null; }
  35944. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35945. _this._canBeRegenerated = _canBeRegenerated;
  35946. _this._beingRegenerated = true;
  35947. _this.regenerate();
  35948. _this._beingRegenerated = false;
  35949. return _this;
  35950. }
  35951. /**
  35952. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35953. * @returns true if the geometry can be regenerated
  35954. */
  35955. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35956. return this._canBeRegenerated;
  35957. };
  35958. /**
  35959. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35960. */
  35961. _PrimitiveGeometry.prototype.regenerate = function () {
  35962. if (!this._canBeRegenerated) {
  35963. return;
  35964. }
  35965. this._beingRegenerated = true;
  35966. this.setAllVerticesData(this._regenerateVertexData(), false);
  35967. this._beingRegenerated = false;
  35968. };
  35969. /**
  35970. * Clone the geometry
  35971. * @param id defines the unique ID of the new geometry
  35972. * @returns the new geometry
  35973. */
  35974. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35975. return _super.prototype.copy.call(this, id);
  35976. };
  35977. // overrides
  35978. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35979. if (!this._beingRegenerated) {
  35980. return;
  35981. }
  35982. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35983. };
  35984. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35985. if (!this._beingRegenerated) {
  35986. return;
  35987. }
  35988. _super.prototype.setVerticesData.call(this, kind, data, false);
  35989. };
  35990. // to override
  35991. /** @ignore */
  35992. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35993. throw new Error("Abstract method");
  35994. };
  35995. _PrimitiveGeometry.prototype.copy = function (id) {
  35996. throw new Error("Must be overriden in sub-classes.");
  35997. };
  35998. _PrimitiveGeometry.prototype.serialize = function () {
  35999. var serializationObject = _super.prototype.serialize.call(this);
  36000. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36001. return serializationObject;
  36002. };
  36003. return _PrimitiveGeometry;
  36004. }(Geometry));
  36005. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36006. /**
  36007. * Creates a ribbon geometry
  36008. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36009. */
  36010. var RibbonGeometry = /** @class */ (function (_super) {
  36011. __extends(RibbonGeometry, _super);
  36012. /**
  36013. * Creates a ribbon geometry
  36014. * @param id defines the unique ID of the geometry
  36015. * @param scene defines the hosting scene
  36016. * @param pathArray defines the array of paths to use
  36017. * @param closeArray defines if the last path and the first path must be joined
  36018. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36019. * @param offset defines the offset between points
  36020. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36021. * @param mesh defines the hosting mesh (can be null)
  36022. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36023. */
  36024. function RibbonGeometry(id, scene,
  36025. /**
  36026. * Defines the array of paths to use
  36027. */
  36028. pathArray,
  36029. /**
  36030. * Defines if the last and first points of each path in your pathArray must be joined
  36031. */
  36032. closeArray,
  36033. /**
  36034. * Defines if the last and first points of each path in your pathArray must be joined
  36035. */
  36036. closePath,
  36037. /**
  36038. * Defines the offset between points
  36039. */
  36040. offset, canBeRegenerated, mesh,
  36041. /**
  36042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36043. */
  36044. side) {
  36045. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36046. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36047. _this.pathArray = pathArray;
  36048. _this.closeArray = closeArray;
  36049. _this.closePath = closePath;
  36050. _this.offset = offset;
  36051. _this.side = side;
  36052. return _this;
  36053. }
  36054. /** @ignore */
  36055. RibbonGeometry.prototype._regenerateVertexData = function () {
  36056. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36057. };
  36058. RibbonGeometry.prototype.copy = function (id) {
  36059. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36060. };
  36061. return RibbonGeometry;
  36062. }(_PrimitiveGeometry));
  36063. BABYLON.RibbonGeometry = RibbonGeometry;
  36064. /**
  36065. * Creates a box geometry
  36066. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36067. */
  36068. var BoxGeometry = /** @class */ (function (_super) {
  36069. __extends(BoxGeometry, _super);
  36070. /**
  36071. * Creates a box geometry
  36072. * @param id defines the unique ID of the geometry
  36073. * @param scene defines the hosting scene
  36074. * @param size defines the zise of the box (width, height and depth are the same)
  36075. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36076. * @param mesh defines the hosting mesh (can be null)
  36077. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36078. */
  36079. function BoxGeometry(id, scene,
  36080. /**
  36081. * Defines the zise of the box (width, height and depth are the same)
  36082. */
  36083. size, canBeRegenerated, mesh,
  36084. /**
  36085. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36086. */
  36087. side) {
  36088. if (mesh === void 0) { mesh = null; }
  36089. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36090. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36091. _this.size = size;
  36092. _this.side = side;
  36093. return _this;
  36094. }
  36095. BoxGeometry.prototype._regenerateVertexData = function () {
  36096. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36097. };
  36098. BoxGeometry.prototype.copy = function (id) {
  36099. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36100. };
  36101. BoxGeometry.prototype.serialize = function () {
  36102. var serializationObject = _super.prototype.serialize.call(this);
  36103. serializationObject.size = this.size;
  36104. return serializationObject;
  36105. };
  36106. BoxGeometry.Parse = function (parsedBox, scene) {
  36107. if (scene.getGeometryByID(parsedBox.id)) {
  36108. return null; // null since geometry could be something else than a box...
  36109. }
  36110. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36111. if (BABYLON.Tags) {
  36112. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36113. }
  36114. scene.pushGeometry(box, true);
  36115. return box;
  36116. };
  36117. return BoxGeometry;
  36118. }(_PrimitiveGeometry));
  36119. BABYLON.BoxGeometry = BoxGeometry;
  36120. /**
  36121. * Creates a sphere geometry
  36122. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36123. */
  36124. var SphereGeometry = /** @class */ (function (_super) {
  36125. __extends(SphereGeometry, _super);
  36126. /**
  36127. * Create a new sphere geometry
  36128. * @param id defines the unique ID of the geometry
  36129. * @param scene defines the hosting scene
  36130. * @param segments defines the number of segments to use to create the sphere
  36131. * @param diameter defines the diameter of the sphere
  36132. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36133. * @param mesh defines the hosting mesh (can be null)
  36134. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36135. */
  36136. function SphereGeometry(id, scene,
  36137. /**
  36138. * Defines the number of segments to use to create the sphere
  36139. */
  36140. segments,
  36141. /**
  36142. * Defines the diameter of the sphere
  36143. */
  36144. diameter, canBeRegenerated, mesh,
  36145. /**
  36146. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36147. */
  36148. side) {
  36149. if (mesh === void 0) { mesh = null; }
  36150. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36151. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36152. _this.segments = segments;
  36153. _this.diameter = diameter;
  36154. _this.side = side;
  36155. return _this;
  36156. }
  36157. SphereGeometry.prototype._regenerateVertexData = function () {
  36158. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36159. };
  36160. SphereGeometry.prototype.copy = function (id) {
  36161. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36162. };
  36163. SphereGeometry.prototype.serialize = function () {
  36164. var serializationObject = _super.prototype.serialize.call(this);
  36165. serializationObject.segments = this.segments;
  36166. serializationObject.diameter = this.diameter;
  36167. return serializationObject;
  36168. };
  36169. SphereGeometry.Parse = function (parsedSphere, scene) {
  36170. if (scene.getGeometryByID(parsedSphere.id)) {
  36171. return null; // null since geometry could be something else than a sphere...
  36172. }
  36173. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36174. if (BABYLON.Tags) {
  36175. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36176. }
  36177. scene.pushGeometry(sphere, true);
  36178. return sphere;
  36179. };
  36180. return SphereGeometry;
  36181. }(_PrimitiveGeometry));
  36182. BABYLON.SphereGeometry = SphereGeometry;
  36183. /**
  36184. * Creates a disc geometry
  36185. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36186. */
  36187. var DiscGeometry = /** @class */ (function (_super) {
  36188. __extends(DiscGeometry, _super);
  36189. /**
  36190. * Creates a new disc geometry
  36191. * @param id defines the unique ID of the geometry
  36192. * @param scene defines the hosting scene
  36193. * @param radius defines the radius of the disc
  36194. * @param tessellation defines the tesselation factor to apply to the disc
  36195. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36196. * @param mesh defines the hosting mesh (can be null)
  36197. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36198. */
  36199. function DiscGeometry(id, scene,
  36200. /**
  36201. * Defines the radius of the disc
  36202. */
  36203. radius,
  36204. /**
  36205. * Defines the tesselation factor to apply to the disc
  36206. */
  36207. tessellation, canBeRegenerated, mesh,
  36208. /**
  36209. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36210. */
  36211. side) {
  36212. if (mesh === void 0) { mesh = null; }
  36213. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36214. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36215. _this.radius = radius;
  36216. _this.tessellation = tessellation;
  36217. _this.side = side;
  36218. return _this;
  36219. }
  36220. DiscGeometry.prototype._regenerateVertexData = function () {
  36221. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36222. };
  36223. DiscGeometry.prototype.copy = function (id) {
  36224. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36225. };
  36226. return DiscGeometry;
  36227. }(_PrimitiveGeometry));
  36228. BABYLON.DiscGeometry = DiscGeometry;
  36229. /**
  36230. * Creates a new cylinder geometry
  36231. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36232. */
  36233. var CylinderGeometry = /** @class */ (function (_super) {
  36234. __extends(CylinderGeometry, _super);
  36235. /**
  36236. * Creates a new cylinder geometry
  36237. * @param id defines the unique ID of the geometry
  36238. * @param scene defines the hosting scene
  36239. * @param height defines the height of the cylinder
  36240. * @param diameterTop defines the diameter of the cylinder's top cap
  36241. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36242. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36243. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36245. * @param mesh defines the hosting mesh (can be null)
  36246. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36247. */
  36248. function CylinderGeometry(id, scene,
  36249. /**
  36250. * Defines the height of the cylinder
  36251. */
  36252. height,
  36253. /**
  36254. * Defines the diameter of the cylinder's top cap
  36255. */
  36256. diameterTop,
  36257. /**
  36258. * Defines the diameter of the cylinder's bottom cap
  36259. */
  36260. diameterBottom,
  36261. /**
  36262. * Defines the tessellation factor to apply to the cylinder
  36263. */
  36264. tessellation,
  36265. /**
  36266. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36267. */
  36268. subdivisions, canBeRegenerated, mesh,
  36269. /**
  36270. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36271. */
  36272. side) {
  36273. if (subdivisions === void 0) { subdivisions = 1; }
  36274. if (mesh === void 0) { mesh = null; }
  36275. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36276. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36277. _this.height = height;
  36278. _this.diameterTop = diameterTop;
  36279. _this.diameterBottom = diameterBottom;
  36280. _this.tessellation = tessellation;
  36281. _this.subdivisions = subdivisions;
  36282. _this.side = side;
  36283. return _this;
  36284. }
  36285. CylinderGeometry.prototype._regenerateVertexData = function () {
  36286. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36287. };
  36288. CylinderGeometry.prototype.copy = function (id) {
  36289. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36290. };
  36291. CylinderGeometry.prototype.serialize = function () {
  36292. var serializationObject = _super.prototype.serialize.call(this);
  36293. serializationObject.height = this.height;
  36294. serializationObject.diameterTop = this.diameterTop;
  36295. serializationObject.diameterBottom = this.diameterBottom;
  36296. serializationObject.tessellation = this.tessellation;
  36297. return serializationObject;
  36298. };
  36299. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36300. if (scene.getGeometryByID(parsedCylinder.id)) {
  36301. return null; // null since geometry could be something else than a cylinder...
  36302. }
  36303. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36304. if (BABYLON.Tags) {
  36305. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36306. }
  36307. scene.pushGeometry(cylinder, true);
  36308. return cylinder;
  36309. };
  36310. return CylinderGeometry;
  36311. }(_PrimitiveGeometry));
  36312. BABYLON.CylinderGeometry = CylinderGeometry;
  36313. /**
  36314. * Creates a new torus geometry
  36315. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36316. */
  36317. var TorusGeometry = /** @class */ (function (_super) {
  36318. __extends(TorusGeometry, _super);
  36319. /**
  36320. * Creates a new torus geometry
  36321. * @param id defines the unique ID of the geometry
  36322. * @param scene defines the hosting scene
  36323. * @param diameter defines the diameter of the torus
  36324. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36325. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36326. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36327. * @param mesh defines the hosting mesh (can be null)
  36328. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36329. */
  36330. function TorusGeometry(id, scene,
  36331. /**
  36332. * Defines the diameter of the torus
  36333. */
  36334. diameter,
  36335. /**
  36336. * Defines the thickness of the torus (ie. internal diameter)
  36337. */
  36338. thickness,
  36339. /**
  36340. * Defines the tesselation factor to apply to the torus
  36341. */
  36342. tessellation, canBeRegenerated, mesh,
  36343. /**
  36344. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36345. */
  36346. side) {
  36347. if (mesh === void 0) { mesh = null; }
  36348. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36349. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36350. _this.diameter = diameter;
  36351. _this.thickness = thickness;
  36352. _this.tessellation = tessellation;
  36353. _this.side = side;
  36354. return _this;
  36355. }
  36356. TorusGeometry.prototype._regenerateVertexData = function () {
  36357. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36358. };
  36359. TorusGeometry.prototype.copy = function (id) {
  36360. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36361. };
  36362. TorusGeometry.prototype.serialize = function () {
  36363. var serializationObject = _super.prototype.serialize.call(this);
  36364. serializationObject.diameter = this.diameter;
  36365. serializationObject.thickness = this.thickness;
  36366. serializationObject.tessellation = this.tessellation;
  36367. return serializationObject;
  36368. };
  36369. TorusGeometry.Parse = function (parsedTorus, scene) {
  36370. if (scene.getGeometryByID(parsedTorus.id)) {
  36371. return null; // null since geometry could be something else than a torus...
  36372. }
  36373. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36374. if (BABYLON.Tags) {
  36375. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36376. }
  36377. scene.pushGeometry(torus, true);
  36378. return torus;
  36379. };
  36380. return TorusGeometry;
  36381. }(_PrimitiveGeometry));
  36382. BABYLON.TorusGeometry = TorusGeometry;
  36383. /**
  36384. * Creates a new ground geometry
  36385. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36386. */
  36387. var GroundGeometry = /** @class */ (function (_super) {
  36388. __extends(GroundGeometry, _super);
  36389. /**
  36390. * Creates a new ground geometry
  36391. * @param id defines the unique ID of the geometry
  36392. * @param scene defines the hosting scene
  36393. * @param width defines the width of the ground
  36394. * @param height defines the height of the ground
  36395. * @param subdivisions defines the subdivisions to apply to the ground
  36396. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36397. * @param mesh defines the hosting mesh (can be null)
  36398. */
  36399. function GroundGeometry(id, scene,
  36400. /**
  36401. * Defines the width of the ground
  36402. */
  36403. width,
  36404. /**
  36405. * Defines the height of the ground
  36406. */
  36407. height,
  36408. /**
  36409. * Defines the subdivisions to apply to the ground
  36410. */
  36411. subdivisions, canBeRegenerated, mesh) {
  36412. if (mesh === void 0) { mesh = null; }
  36413. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36414. _this.width = width;
  36415. _this.height = height;
  36416. _this.subdivisions = subdivisions;
  36417. return _this;
  36418. }
  36419. GroundGeometry.prototype._regenerateVertexData = function () {
  36420. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36421. };
  36422. GroundGeometry.prototype.copy = function (id) {
  36423. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36424. };
  36425. GroundGeometry.prototype.serialize = function () {
  36426. var serializationObject = _super.prototype.serialize.call(this);
  36427. serializationObject.width = this.width;
  36428. serializationObject.height = this.height;
  36429. serializationObject.subdivisions = this.subdivisions;
  36430. return serializationObject;
  36431. };
  36432. GroundGeometry.Parse = function (parsedGround, scene) {
  36433. if (scene.getGeometryByID(parsedGround.id)) {
  36434. return null; // null since geometry could be something else than a ground...
  36435. }
  36436. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36437. if (BABYLON.Tags) {
  36438. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36439. }
  36440. scene.pushGeometry(ground, true);
  36441. return ground;
  36442. };
  36443. return GroundGeometry;
  36444. }(_PrimitiveGeometry));
  36445. BABYLON.GroundGeometry = GroundGeometry;
  36446. /**
  36447. * Creates a tiled ground geometry
  36448. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36449. */
  36450. var TiledGroundGeometry = /** @class */ (function (_super) {
  36451. __extends(TiledGroundGeometry, _super);
  36452. /**
  36453. * Creates a tiled ground geometry
  36454. * @param id defines the unique ID of the geometry
  36455. * @param scene defines the hosting scene
  36456. * @param xmin defines the minimum value on X axis
  36457. * @param zmin defines the minimum value on Z axis
  36458. * @param xmax defines the maximum value on X axis
  36459. * @param zmax defines the maximum value on Z axis
  36460. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36461. * @param precision defines the precision to use when computing the tiles
  36462. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36463. * @param mesh defines the hosting mesh (can be null)
  36464. */
  36465. function TiledGroundGeometry(id, scene,
  36466. /**
  36467. * Defines the minimum value on X axis
  36468. */
  36469. xmin,
  36470. /**
  36471. * Defines the minimum value on Z axis
  36472. */
  36473. zmin,
  36474. /**
  36475. * Defines the maximum value on X axis
  36476. */
  36477. xmax,
  36478. /**
  36479. * Defines the maximum value on Z axis
  36480. */
  36481. zmax,
  36482. /**
  36483. * Defines the subdivisions to apply to the ground
  36484. */
  36485. subdivisions,
  36486. /**
  36487. * Defines the precision to use when computing the tiles
  36488. */
  36489. precision, canBeRegenerated, mesh) {
  36490. if (mesh === void 0) { mesh = null; }
  36491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36492. _this.xmin = xmin;
  36493. _this.zmin = zmin;
  36494. _this.xmax = xmax;
  36495. _this.zmax = zmax;
  36496. _this.subdivisions = subdivisions;
  36497. _this.precision = precision;
  36498. return _this;
  36499. }
  36500. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36501. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36502. };
  36503. TiledGroundGeometry.prototype.copy = function (id) {
  36504. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36505. };
  36506. return TiledGroundGeometry;
  36507. }(_PrimitiveGeometry));
  36508. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36509. /**
  36510. * Creates a plane geometry
  36511. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36512. */
  36513. var PlaneGeometry = /** @class */ (function (_super) {
  36514. __extends(PlaneGeometry, _super);
  36515. /**
  36516. * Creates a plane geometry
  36517. * @param id defines the unique ID of the geometry
  36518. * @param scene defines the hosting scene
  36519. * @param size defines the size of the plane (width === height)
  36520. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36521. * @param mesh defines the hosting mesh (can be null)
  36522. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36523. */
  36524. function PlaneGeometry(id, scene,
  36525. /**
  36526. * Defines the size of the plane (width === height)
  36527. */
  36528. size, canBeRegenerated, mesh,
  36529. /**
  36530. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36531. */
  36532. side) {
  36533. if (mesh === void 0) { mesh = null; }
  36534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36536. _this.size = size;
  36537. _this.side = side;
  36538. return _this;
  36539. }
  36540. PlaneGeometry.prototype._regenerateVertexData = function () {
  36541. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36542. };
  36543. PlaneGeometry.prototype.copy = function (id) {
  36544. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36545. };
  36546. PlaneGeometry.prototype.serialize = function () {
  36547. var serializationObject = _super.prototype.serialize.call(this);
  36548. serializationObject.size = this.size;
  36549. return serializationObject;
  36550. };
  36551. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36552. if (scene.getGeometryByID(parsedPlane.id)) {
  36553. return null; // null since geometry could be something else than a ground...
  36554. }
  36555. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36556. if (BABYLON.Tags) {
  36557. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36558. }
  36559. scene.pushGeometry(plane, true);
  36560. return plane;
  36561. };
  36562. return PlaneGeometry;
  36563. }(_PrimitiveGeometry));
  36564. BABYLON.PlaneGeometry = PlaneGeometry;
  36565. /**
  36566. * Creates a torus knot geometry
  36567. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36568. */
  36569. var TorusKnotGeometry = /** @class */ (function (_super) {
  36570. __extends(TorusKnotGeometry, _super);
  36571. /**
  36572. * Creates a torus knot geometry
  36573. * @param id defines the unique ID of the geometry
  36574. * @param scene defines the hosting scene
  36575. * @param radius defines the radius of the torus knot
  36576. * @param tube defines the thickness of the torus knot tube
  36577. * @param radialSegments defines the number of radial segments
  36578. * @param tubularSegments defines the number of tubular segments
  36579. * @param p defines the first number of windings
  36580. * @param q defines the second number of windings
  36581. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36582. * @param mesh defines the hosting mesh (can be null)
  36583. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36584. */
  36585. function TorusKnotGeometry(id, scene,
  36586. /**
  36587. * Defines the radius of the torus knot
  36588. */
  36589. radius,
  36590. /**
  36591. * Defines the thickness of the torus knot tube
  36592. */
  36593. tube,
  36594. /**
  36595. * Defines the number of radial segments
  36596. */
  36597. radialSegments,
  36598. /**
  36599. * Defines the number of tubular segments
  36600. */
  36601. tubularSegments,
  36602. /**
  36603. * Defines the first number of windings
  36604. */
  36605. p,
  36606. /**
  36607. * Defines the second number of windings
  36608. */
  36609. q, canBeRegenerated, mesh,
  36610. /**
  36611. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36612. */
  36613. side) {
  36614. if (mesh === void 0) { mesh = null; }
  36615. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36617. _this.radius = radius;
  36618. _this.tube = tube;
  36619. _this.radialSegments = radialSegments;
  36620. _this.tubularSegments = tubularSegments;
  36621. _this.p = p;
  36622. _this.q = q;
  36623. _this.side = side;
  36624. return _this;
  36625. }
  36626. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36627. 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 });
  36628. };
  36629. TorusKnotGeometry.prototype.copy = function (id) {
  36630. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36631. };
  36632. TorusKnotGeometry.prototype.serialize = function () {
  36633. var serializationObject = _super.prototype.serialize.call(this);
  36634. serializationObject.radius = this.radius;
  36635. serializationObject.tube = this.tube;
  36636. serializationObject.radialSegments = this.radialSegments;
  36637. serializationObject.tubularSegments = this.tubularSegments;
  36638. serializationObject.p = this.p;
  36639. serializationObject.q = this.q;
  36640. return serializationObject;
  36641. };
  36642. ;
  36643. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36644. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36645. return null; // null since geometry could be something else than a ground...
  36646. }
  36647. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36648. if (BABYLON.Tags) {
  36649. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36650. }
  36651. scene.pushGeometry(torusKnot, true);
  36652. return torusKnot;
  36653. };
  36654. return TorusKnotGeometry;
  36655. }(_PrimitiveGeometry));
  36656. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36657. //}
  36658. })(BABYLON || (BABYLON = {}));
  36659. //# sourceMappingURL=babylon.geometry.js.map
  36660. var BABYLON;
  36661. (function (BABYLON) {
  36662. /**
  36663. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36664. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36665. */
  36666. var PostProcessManager = /** @class */ (function () {
  36667. /**
  36668. * Creates a new instance of @see PostProcess
  36669. * @param scene The scene that the post process is associated with.
  36670. */
  36671. function PostProcessManager(scene) {
  36672. this._vertexBuffers = {};
  36673. this._scene = scene;
  36674. }
  36675. PostProcessManager.prototype._prepareBuffers = function () {
  36676. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36677. return;
  36678. }
  36679. // VBO
  36680. var vertices = [];
  36681. vertices.push(1, 1);
  36682. vertices.push(-1, 1);
  36683. vertices.push(-1, -1);
  36684. vertices.push(1, -1);
  36685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36686. this._buildIndexBuffer();
  36687. };
  36688. PostProcessManager.prototype._buildIndexBuffer = function () {
  36689. // Indices
  36690. var indices = [];
  36691. indices.push(0);
  36692. indices.push(1);
  36693. indices.push(2);
  36694. indices.push(0);
  36695. indices.push(2);
  36696. indices.push(3);
  36697. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36698. };
  36699. /**
  36700. * Rebuilds the vertex buffers of the manager.
  36701. */
  36702. PostProcessManager.prototype._rebuild = function () {
  36703. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36704. if (!vb) {
  36705. return;
  36706. }
  36707. vb._rebuild();
  36708. this._buildIndexBuffer();
  36709. };
  36710. // Methods
  36711. /**
  36712. * Prepares a frame to be run through a post process.
  36713. * @param sourceTexture The input texture to the post procesess. (default: null)
  36714. * @param postProcesses An array of post processes to be run. (default: null)
  36715. * @returns True if the post processes were able to be run.
  36716. */
  36717. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36718. if (sourceTexture === void 0) { sourceTexture = null; }
  36719. if (postProcesses === void 0) { postProcesses = null; }
  36720. var camera = this._scene.activeCamera;
  36721. if (!camera) {
  36722. return false;
  36723. }
  36724. var postProcesses = postProcesses || camera._postProcesses;
  36725. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36726. return false;
  36727. }
  36728. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36729. return true;
  36730. };
  36731. /**
  36732. * Manually render a set of post processes to a texture.
  36733. * @param postProcesses An array of post processes to be run.
  36734. * @param targetTexture The target texture to render to.
  36735. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36736. */
  36737. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36738. if (targetTexture === void 0) { targetTexture = null; }
  36739. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36740. var engine = this._scene.getEngine();
  36741. for (var index = 0; index < postProcesses.length; index++) {
  36742. if (index < postProcesses.length - 1) {
  36743. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36744. }
  36745. else {
  36746. if (targetTexture) {
  36747. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36748. }
  36749. else {
  36750. engine.restoreDefaultFramebuffer();
  36751. }
  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 depth buffer
  36766. engine.setDepthBuffer(true);
  36767. engine.setDepthWrite(true);
  36768. };
  36769. /**
  36770. * Finalize the result of the output of the postprocesses.
  36771. * @param doNotPresent If true the result will not be displayed to the screen.
  36772. * @param targetTexture The target texture to render to.
  36773. * @param faceIndex The index of the face to bind the target texture to.
  36774. * @param postProcesses The array of post processes to render.
  36775. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36776. */
  36777. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36778. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36779. var camera = this._scene.activeCamera;
  36780. if (!camera) {
  36781. return;
  36782. }
  36783. postProcesses = postProcesses || camera._postProcesses;
  36784. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36785. return;
  36786. }
  36787. var engine = this._scene.getEngine();
  36788. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36789. if (index < len - 1) {
  36790. postProcesses[index + 1].activate(camera, targetTexture);
  36791. }
  36792. else {
  36793. if (targetTexture) {
  36794. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36795. }
  36796. else {
  36797. engine.restoreDefaultFramebuffer();
  36798. }
  36799. }
  36800. if (doNotPresent) {
  36801. break;
  36802. }
  36803. var pp = postProcesses[index];
  36804. var effect = pp.apply();
  36805. if (effect) {
  36806. pp.onBeforeRenderObservable.notifyObservers(effect);
  36807. // VBOs
  36808. this._prepareBuffers();
  36809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36810. // Draw order
  36811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36812. pp.onAfterRenderObservable.notifyObservers(effect);
  36813. }
  36814. }
  36815. // Restore states
  36816. engine.setDepthBuffer(true);
  36817. engine.setDepthWrite(true);
  36818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36819. };
  36820. /**
  36821. * Disposes of the post process manager.
  36822. */
  36823. PostProcessManager.prototype.dispose = function () {
  36824. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36825. if (buffer) {
  36826. buffer.dispose();
  36827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36828. }
  36829. if (this._indexBuffer) {
  36830. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36831. this._indexBuffer = null;
  36832. }
  36833. };
  36834. return PostProcessManager;
  36835. }());
  36836. BABYLON.PostProcessManager = PostProcessManager;
  36837. })(BABYLON || (BABYLON = {}));
  36838. //# sourceMappingURL=babylon.postProcessManager.js.map
  36839. var BABYLON;
  36840. (function (BABYLON) {
  36841. /**
  36842. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36843. */
  36844. var PerformanceMonitor = /** @class */ (function () {
  36845. /**
  36846. * constructor
  36847. * @param frameSampleSize The number of samples required to saturate the sliding window
  36848. */
  36849. function PerformanceMonitor(frameSampleSize) {
  36850. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36851. this._enabled = true;
  36852. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36853. }
  36854. /**
  36855. * Samples current frame
  36856. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36857. */
  36858. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36859. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36860. if (!this._enabled)
  36861. return;
  36862. if (this._lastFrameTimeMs != null) {
  36863. var dt = timeMs - this._lastFrameTimeMs;
  36864. this._rollingFrameTime.add(dt);
  36865. }
  36866. this._lastFrameTimeMs = timeMs;
  36867. };
  36868. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36869. /**
  36870. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36871. * @return Average frame time in milliseconds
  36872. */
  36873. get: function () {
  36874. return this._rollingFrameTime.average;
  36875. },
  36876. enumerable: true,
  36877. configurable: true
  36878. });
  36879. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36880. /**
  36881. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36882. * @return Frame time variance in milliseconds squared
  36883. */
  36884. get: function () {
  36885. return this._rollingFrameTime.variance;
  36886. },
  36887. enumerable: true,
  36888. configurable: true
  36889. });
  36890. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36891. /**
  36892. * Returns the frame time of the most recent frame
  36893. * @return Frame time in milliseconds
  36894. */
  36895. get: function () {
  36896. return this._rollingFrameTime.history(0);
  36897. },
  36898. enumerable: true,
  36899. configurable: true
  36900. });
  36901. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36902. /**
  36903. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36904. * @return Framerate in frames per second
  36905. */
  36906. get: function () {
  36907. return 1000.0 / this._rollingFrameTime.average;
  36908. },
  36909. enumerable: true,
  36910. configurable: true
  36911. });
  36912. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36913. /**
  36914. * Returns the average framerate in frames per second using the most recent frame time
  36915. * @return Framerate in frames per second
  36916. */
  36917. get: function () {
  36918. var history = this._rollingFrameTime.history(0);
  36919. if (history === 0) {
  36920. return 0;
  36921. }
  36922. return 1000.0 / history;
  36923. },
  36924. enumerable: true,
  36925. configurable: true
  36926. });
  36927. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36928. /**
  36929. * Returns true if enough samples have been taken to completely fill the sliding window
  36930. * @return true if saturated
  36931. */
  36932. get: function () {
  36933. return this._rollingFrameTime.isSaturated();
  36934. },
  36935. enumerable: true,
  36936. configurable: true
  36937. });
  36938. /**
  36939. * Enables contributions to the sliding window sample set
  36940. */
  36941. PerformanceMonitor.prototype.enable = function () {
  36942. this._enabled = true;
  36943. };
  36944. /**
  36945. * Disables contributions to the sliding window sample set
  36946. * Samples will not be interpolated over the disabled period
  36947. */
  36948. PerformanceMonitor.prototype.disable = function () {
  36949. this._enabled = false;
  36950. //clear last sample to avoid interpolating over the disabled period when next enabled
  36951. this._lastFrameTimeMs = null;
  36952. };
  36953. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36954. /**
  36955. * Returns true if sampling is enabled
  36956. * @return true if enabled
  36957. */
  36958. get: function () {
  36959. return this._enabled;
  36960. },
  36961. enumerable: true,
  36962. configurable: true
  36963. });
  36964. /**
  36965. * Resets performance monitor
  36966. */
  36967. PerformanceMonitor.prototype.reset = function () {
  36968. //clear last sample to avoid interpolating over the disabled period when next enabled
  36969. this._lastFrameTimeMs = null;
  36970. //wipe record
  36971. this._rollingFrameTime.reset();
  36972. };
  36973. return PerformanceMonitor;
  36974. }());
  36975. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36976. /**
  36977. * RollingAverage
  36978. *
  36979. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36980. */
  36981. var RollingAverage = /** @class */ (function () {
  36982. /**
  36983. * constructor
  36984. * @param length The number of samples required to saturate the sliding window
  36985. */
  36986. function RollingAverage(length) {
  36987. this._samples = new Array(length);
  36988. this.reset();
  36989. }
  36990. /**
  36991. * Adds a sample to the sample set
  36992. * @param v The sample value
  36993. */
  36994. RollingAverage.prototype.add = function (v) {
  36995. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36996. var delta;
  36997. //we need to check if we've already wrapped round
  36998. if (this.isSaturated()) {
  36999. //remove bottom of stack from mean
  37000. var bottomValue = this._samples[this._pos];
  37001. delta = bottomValue - this.average;
  37002. this.average -= delta / (this._sampleCount - 1);
  37003. this._m2 -= delta * (bottomValue - this.average);
  37004. }
  37005. else {
  37006. this._sampleCount++;
  37007. }
  37008. //add new value to mean
  37009. delta = v - this.average;
  37010. this.average += delta / (this._sampleCount);
  37011. this._m2 += delta * (v - this.average);
  37012. //set the new variance
  37013. this.variance = this._m2 / (this._sampleCount - 1);
  37014. this._samples[this._pos] = v;
  37015. this._pos++;
  37016. this._pos %= this._samples.length; //positive wrap around
  37017. };
  37018. /**
  37019. * Returns previously added values or null if outside of history or outside the sliding window domain
  37020. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37021. * @return Value previously recorded with add() or null if outside of range
  37022. */
  37023. RollingAverage.prototype.history = function (i) {
  37024. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37025. return 0;
  37026. }
  37027. var i0 = this._wrapPosition(this._pos - 1.0);
  37028. return this._samples[this._wrapPosition(i0 - i)];
  37029. };
  37030. /**
  37031. * Returns true if enough samples have been taken to completely fill the sliding window
  37032. * @return true if sample-set saturated
  37033. */
  37034. RollingAverage.prototype.isSaturated = function () {
  37035. return this._sampleCount >= this._samples.length;
  37036. };
  37037. /**
  37038. * Resets the rolling average (equivalent to 0 samples taken so far)
  37039. */
  37040. RollingAverage.prototype.reset = function () {
  37041. this.average = 0;
  37042. this.variance = 0;
  37043. this._sampleCount = 0;
  37044. this._pos = 0;
  37045. this._m2 = 0;
  37046. };
  37047. /**
  37048. * Wraps a value around the sample range boundaries
  37049. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37050. * @return Wrapped position in sample range
  37051. */
  37052. RollingAverage.prototype._wrapPosition = function (i) {
  37053. var max = this._samples.length;
  37054. return ((i % max) + max) % max;
  37055. };
  37056. return RollingAverage;
  37057. }());
  37058. BABYLON.RollingAverage = RollingAverage;
  37059. })(BABYLON || (BABYLON = {}));
  37060. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37061. var BABYLON;
  37062. (function (BABYLON) {
  37063. /**
  37064. * This groups together the common properties used for image processing either in direct forward pass
  37065. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37066. * or not.
  37067. */
  37068. var ImageProcessingConfiguration = /** @class */ (function () {
  37069. function ImageProcessingConfiguration() {
  37070. /**
  37071. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37072. */
  37073. this.colorCurves = new BABYLON.ColorCurves();
  37074. this._colorCurvesEnabled = false;
  37075. this._colorGradingEnabled = false;
  37076. this._colorGradingWithGreenDepth = true;
  37077. this._colorGradingBGR = true;
  37078. this._exposure = 1.0;
  37079. this._toneMappingEnabled = false;
  37080. this._contrast = 1.0;
  37081. /**
  37082. * Vignette stretch size.
  37083. */
  37084. this.vignetteStretch = 0;
  37085. /**
  37086. * Vignette centre X Offset.
  37087. */
  37088. this.vignetteCentreX = 0;
  37089. /**
  37090. * Vignette centre Y Offset.
  37091. */
  37092. this.vignetteCentreY = 0;
  37093. /**
  37094. * Vignette weight or intensity of the vignette effect.
  37095. */
  37096. this.vignetteWeight = 1.5;
  37097. /**
  37098. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37099. * if vignetteEnabled is set to true.
  37100. */
  37101. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37102. /**
  37103. * Camera field of view used by the Vignette effect.
  37104. */
  37105. this.vignetteCameraFov = 0.5;
  37106. this._grainEnabled = false;
  37107. this._grainIntensity = 30;
  37108. this._grainAnimated = false;
  37109. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37110. this._vignetteEnabled = false;
  37111. this._applyByPostProcess = false;
  37112. this._isEnabled = true;
  37113. /**
  37114. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37115. * @type {BABYLON.Observable}
  37116. */
  37117. this.onUpdateParameters = new BABYLON.Observable();
  37118. }
  37119. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37120. /**
  37121. * Gets wether the color curves effect is enabled.
  37122. */
  37123. get: function () {
  37124. return this._colorCurvesEnabled;
  37125. },
  37126. /**
  37127. * Sets wether the color curves effect is enabled.
  37128. */
  37129. set: function (value) {
  37130. if (this._colorCurvesEnabled === value) {
  37131. return;
  37132. }
  37133. this._colorCurvesEnabled = value;
  37134. this._updateParameters();
  37135. },
  37136. enumerable: true,
  37137. configurable: true
  37138. });
  37139. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37140. /**
  37141. * Gets wether the color grading effect is enabled.
  37142. */
  37143. get: function () {
  37144. return this._colorGradingEnabled;
  37145. },
  37146. /**
  37147. * Sets wether the color grading effect is enabled.
  37148. */
  37149. set: function (value) {
  37150. if (this._colorGradingEnabled === value) {
  37151. return;
  37152. }
  37153. this._colorGradingEnabled = value;
  37154. this._updateParameters();
  37155. },
  37156. enumerable: true,
  37157. configurable: true
  37158. });
  37159. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37160. /**
  37161. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37162. */
  37163. get: function () {
  37164. return this._colorGradingWithGreenDepth;
  37165. },
  37166. /**
  37167. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37168. */
  37169. set: function (value) {
  37170. if (this._colorGradingWithGreenDepth === value) {
  37171. return;
  37172. }
  37173. this._colorGradingWithGreenDepth = value;
  37174. this._updateParameters();
  37175. },
  37176. enumerable: true,
  37177. configurable: true
  37178. });
  37179. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37180. /**
  37181. * Gets wether the color grading texture contains BGR values.
  37182. */
  37183. get: function () {
  37184. return this._colorGradingBGR;
  37185. },
  37186. /**
  37187. * Sets wether the color grading texture contains BGR values.
  37188. */
  37189. set: function (value) {
  37190. if (this._colorGradingBGR === value) {
  37191. return;
  37192. }
  37193. this._colorGradingBGR = value;
  37194. this._updateParameters();
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37200. /**
  37201. * Gets the Exposure used in the effect.
  37202. */
  37203. get: function () {
  37204. return this._exposure;
  37205. },
  37206. /**
  37207. * Sets the Exposure used in the effect.
  37208. */
  37209. set: function (value) {
  37210. if (this._exposure === value) {
  37211. return;
  37212. }
  37213. this._exposure = value;
  37214. this._updateParameters();
  37215. },
  37216. enumerable: true,
  37217. configurable: true
  37218. });
  37219. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37220. /**
  37221. * Gets wether the tone mapping effect is enabled.
  37222. */
  37223. get: function () {
  37224. return this._toneMappingEnabled;
  37225. },
  37226. /**
  37227. * Sets wether the tone mapping effect is enabled.
  37228. */
  37229. set: function (value) {
  37230. if (this._toneMappingEnabled === value) {
  37231. return;
  37232. }
  37233. this._toneMappingEnabled = value;
  37234. this._updateParameters();
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37240. /**
  37241. * Gets the contrast used in the effect.
  37242. */
  37243. get: function () {
  37244. return this._contrast;
  37245. },
  37246. /**
  37247. * Sets the contrast used in the effect.
  37248. */
  37249. set: function (value) {
  37250. if (this._contrast === value) {
  37251. return;
  37252. }
  37253. this._contrast = value;
  37254. this._updateParameters();
  37255. },
  37256. enumerable: true,
  37257. configurable: true
  37258. });
  37259. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37260. /**
  37261. * If the grain effect should be enabled.
  37262. */
  37263. get: function () {
  37264. return this._grainEnabled;
  37265. },
  37266. set: function (value) {
  37267. if (this._grainEnabled === value) {
  37268. return;
  37269. }
  37270. this._grainEnabled = value;
  37271. this._updateParameters();
  37272. },
  37273. enumerable: true,
  37274. configurable: true
  37275. });
  37276. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37277. /**
  37278. * Amount of grain to be applied by the grain effect.
  37279. */
  37280. get: function () {
  37281. return this._grainIntensity;
  37282. },
  37283. set: function (value) {
  37284. if (this._grainIntensity === value) {
  37285. return;
  37286. }
  37287. this._grainIntensity = value;
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37293. /**
  37294. * If the grain effect should be animated.
  37295. */
  37296. get: function () {
  37297. return this._grainAnimated;
  37298. },
  37299. set: function (value) {
  37300. if (this._grainAnimated === value) {
  37301. return;
  37302. }
  37303. this._grainAnimated = value;
  37304. this._updateParameters();
  37305. },
  37306. enumerable: true,
  37307. configurable: true
  37308. });
  37309. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37310. /**
  37311. * Gets the vignette blend mode allowing different kind of effect.
  37312. */
  37313. get: function () {
  37314. return this._vignetteBlendMode;
  37315. },
  37316. /**
  37317. * Sets the vignette blend mode allowing different kind of effect.
  37318. */
  37319. set: function (value) {
  37320. if (this._vignetteBlendMode === value) {
  37321. return;
  37322. }
  37323. this._vignetteBlendMode = value;
  37324. this._updateParameters();
  37325. },
  37326. enumerable: true,
  37327. configurable: true
  37328. });
  37329. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37330. /**
  37331. * Gets wether the vignette effect is enabled.
  37332. */
  37333. get: function () {
  37334. return this._vignetteEnabled;
  37335. },
  37336. /**
  37337. * Sets wether the vignette effect is enabled.
  37338. */
  37339. set: function (value) {
  37340. if (this._vignetteEnabled === value) {
  37341. return;
  37342. }
  37343. this._vignetteEnabled = value;
  37344. this._updateParameters();
  37345. },
  37346. enumerable: true,
  37347. configurable: true
  37348. });
  37349. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37350. /**
  37351. * Gets wether the image processing is applied through a post process or not.
  37352. */
  37353. get: function () {
  37354. return this._applyByPostProcess;
  37355. },
  37356. /**
  37357. * Sets wether the image processing is applied through a post process or not.
  37358. */
  37359. set: function (value) {
  37360. if (this._applyByPostProcess === value) {
  37361. return;
  37362. }
  37363. this._applyByPostProcess = value;
  37364. this._updateParameters();
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37370. /**
  37371. * Gets wether the image processing is enabled or not.
  37372. */
  37373. get: function () {
  37374. return this._isEnabled;
  37375. },
  37376. /**
  37377. * Sets wether the image processing is enabled or not.
  37378. */
  37379. set: function (value) {
  37380. if (this._isEnabled === value) {
  37381. return;
  37382. }
  37383. this._isEnabled = value;
  37384. this._updateParameters();
  37385. },
  37386. enumerable: true,
  37387. configurable: true
  37388. });
  37389. /**
  37390. * Method called each time the image processing information changes requires to recompile the effect.
  37391. */
  37392. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37393. this.onUpdateParameters.notifyObservers(this);
  37394. };
  37395. ImageProcessingConfiguration.prototype.getClassName = function () {
  37396. return "ImageProcessingConfiguration";
  37397. };
  37398. /**
  37399. * Prepare the list of uniforms associated with the Image Processing effects.
  37400. * @param uniformsList The list of uniforms used in the effect
  37401. * @param defines the list of defines currently in use
  37402. */
  37403. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37404. if (defines.EXPOSURE) {
  37405. uniforms.push("exposureLinear");
  37406. }
  37407. if (defines.CONTRAST) {
  37408. uniforms.push("contrast");
  37409. }
  37410. if (defines.COLORGRADING) {
  37411. uniforms.push("colorTransformSettings");
  37412. }
  37413. if (defines.VIGNETTE) {
  37414. uniforms.push("vInverseScreenSize");
  37415. uniforms.push("vignetteSettings1");
  37416. uniforms.push("vignetteSettings2");
  37417. }
  37418. if (defines.COLORCURVES) {
  37419. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37420. }
  37421. if (defines.GRAIN) {
  37422. uniforms.push("grainVarianceAmount");
  37423. uniforms.push("grainAnimatedSeed");
  37424. }
  37425. };
  37426. /**
  37427. * Prepare the list of samplers associated with the Image Processing effects.
  37428. * @param uniformsList The list of uniforms used in the effect
  37429. * @param defines the list of defines currently in use
  37430. */
  37431. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37432. if (defines.COLORGRADING) {
  37433. samplersList.push("txColorTransform");
  37434. }
  37435. };
  37436. /**
  37437. * Prepare the list of defines associated to the shader.
  37438. * @param defines the list of defines to complete
  37439. */
  37440. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37441. if (forPostProcess === void 0) { forPostProcess = false; }
  37442. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37443. defines.VIGNETTE = false;
  37444. defines.TONEMAPPING = false;
  37445. defines.CONTRAST = false;
  37446. defines.EXPOSURE = false;
  37447. defines.COLORCURVES = false;
  37448. defines.COLORGRADING = false;
  37449. defines.COLORGRADING3D = false;
  37450. defines.IMAGEPROCESSING = false;
  37451. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37452. return;
  37453. }
  37454. defines.VIGNETTE = this.vignetteEnabled;
  37455. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37456. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37457. defines.TONEMAPPING = this.toneMappingEnabled;
  37458. defines.CONTRAST = (this.contrast !== 1.0);
  37459. defines.EXPOSURE = (this.exposure !== 1.0);
  37460. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37461. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37462. if (defines.COLORGRADING) {
  37463. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37464. }
  37465. else {
  37466. defines.COLORGRADING3D = false;
  37467. }
  37468. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37469. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37470. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37471. defines.GRAIN = this.grainEnabled;
  37472. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37473. };
  37474. /**
  37475. * Returns true if all the image processing information are ready.
  37476. */
  37477. ImageProcessingConfiguration.prototype.isReady = function () {
  37478. // Color Grading texure can not be none blocking.
  37479. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37480. };
  37481. /**
  37482. * Binds the image processing to the shader.
  37483. * @param effect The effect to bind to
  37484. */
  37485. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37486. if (aspectRatio === void 0) { aspectRatio = 1; }
  37487. // Color Curves
  37488. if (this._colorCurvesEnabled && this.colorCurves) {
  37489. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37490. }
  37491. // Vignette
  37492. if (this._vignetteEnabled) {
  37493. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37494. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37495. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37496. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37497. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37498. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37499. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37500. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37501. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37502. var vignettePower = -2.0 * this.vignetteWeight;
  37503. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37504. }
  37505. // Exposure
  37506. effect.setFloat("exposureLinear", this.exposure);
  37507. // Contrast
  37508. effect.setFloat("contrast", this.contrast);
  37509. // Color transform settings
  37510. if (this.colorGradingTexture) {
  37511. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37512. var textureSize = this.colorGradingTexture.getSize().height;
  37513. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37514. 0.5 / textureSize, // textureOffset
  37515. textureSize, // textureSize
  37516. this.colorGradingTexture.level // weight
  37517. );
  37518. }
  37519. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37520. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37521. };
  37522. /**
  37523. * Clones the current image processing instance.
  37524. * @return The cloned image processing
  37525. */
  37526. ImageProcessingConfiguration.prototype.clone = function () {
  37527. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37528. };
  37529. /**
  37530. * Serializes the current image processing instance to a json representation.
  37531. * @return a JSON representation
  37532. */
  37533. ImageProcessingConfiguration.prototype.serialize = function () {
  37534. return BABYLON.SerializationHelper.Serialize(this);
  37535. };
  37536. /**
  37537. * Parses the image processing from a json representation.
  37538. * @param source the JSON source to parse
  37539. * @return The parsed image processing
  37540. */
  37541. ImageProcessingConfiguration.Parse = function (source) {
  37542. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37543. };
  37544. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37545. /**
  37546. * Used to apply the vignette as a mix with the pixel color.
  37547. */
  37548. get: function () {
  37549. return this._VIGNETTEMODE_MULTIPLY;
  37550. },
  37551. enumerable: true,
  37552. configurable: true
  37553. });
  37554. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37555. /**
  37556. * Used to apply the vignette as a replacement of the pixel color.
  37557. */
  37558. get: function () {
  37559. return this._VIGNETTEMODE_OPAQUE;
  37560. },
  37561. enumerable: true,
  37562. configurable: true
  37563. });
  37564. // Static constants associated to the image processing.
  37565. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37566. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37567. __decorate([
  37568. BABYLON.serializeAsColorCurves()
  37569. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37570. __decorate([
  37571. BABYLON.serialize()
  37572. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37573. __decorate([
  37574. BABYLON.serializeAsTexture()
  37575. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37576. __decorate([
  37577. BABYLON.serialize()
  37578. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37579. __decorate([
  37580. BABYLON.serialize()
  37581. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37582. __decorate([
  37583. BABYLON.serialize()
  37584. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37585. __decorate([
  37586. BABYLON.serialize()
  37587. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37588. __decorate([
  37589. BABYLON.serialize()
  37590. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37591. __decorate([
  37592. BABYLON.serialize()
  37593. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37594. __decorate([
  37595. BABYLON.serialize()
  37596. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37597. __decorate([
  37598. BABYLON.serialize()
  37599. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37600. __decorate([
  37601. BABYLON.serialize()
  37602. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37603. __decorate([
  37604. BABYLON.serialize()
  37605. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37606. __decorate([
  37607. BABYLON.serializeAsColor4()
  37608. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37609. __decorate([
  37610. BABYLON.serialize()
  37611. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37612. __decorate([
  37613. BABYLON.serialize()
  37614. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37615. __decorate([
  37616. BABYLON.serialize()
  37617. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37618. __decorate([
  37619. BABYLON.serialize()
  37620. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37621. __decorate([
  37622. BABYLON.serialize()
  37623. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37624. __decorate([
  37625. BABYLON.serialize()
  37626. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37627. __decorate([
  37628. BABYLON.serialize()
  37629. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37630. __decorate([
  37631. BABYLON.serialize()
  37632. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37633. return ImageProcessingConfiguration;
  37634. }());
  37635. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37636. })(BABYLON || (BABYLON = {}));
  37637. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37638. var BABYLON;
  37639. (function (BABYLON) {
  37640. /**
  37641. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37642. * It can help converting any input color in a desired output one. This can then be used to create effects
  37643. * from sepia, black and white to sixties or futuristic rendering...
  37644. *
  37645. * The only supported format is currently 3dl.
  37646. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37647. */
  37648. var ColorGradingTexture = /** @class */ (function (_super) {
  37649. __extends(ColorGradingTexture, _super);
  37650. /**
  37651. * Instantiates a ColorGradingTexture from the following parameters.
  37652. *
  37653. * @param url The location of the color gradind data (currently only supporting 3dl)
  37654. * @param scene The scene the texture will be used in
  37655. */
  37656. function ColorGradingTexture(url, scene) {
  37657. var _this = _super.call(this, scene) || this;
  37658. if (!url) {
  37659. return _this;
  37660. }
  37661. _this._engine = scene.getEngine();
  37662. _this._textureMatrix = BABYLON.Matrix.Identity();
  37663. _this.name = url;
  37664. _this.url = url;
  37665. _this.hasAlpha = false;
  37666. _this.isCube = false;
  37667. _this.is3D = _this._engine.webGLVersion > 1;
  37668. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37669. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37670. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37671. _this.anisotropicFilteringLevel = 1;
  37672. _this._texture = _this._getFromCache(url, true);
  37673. if (!_this._texture) {
  37674. if (!scene.useDelayedTextureLoading) {
  37675. _this.loadTexture();
  37676. }
  37677. else {
  37678. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37679. }
  37680. }
  37681. return _this;
  37682. }
  37683. /**
  37684. * Returns the texture matrix used in most of the material.
  37685. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37686. */
  37687. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37688. return this._textureMatrix;
  37689. };
  37690. /**
  37691. * Occurs when the file being loaded is a .3dl LUT file.
  37692. */
  37693. ColorGradingTexture.prototype.load3dlTexture = function () {
  37694. var engine = this._engine;
  37695. var texture;
  37696. if (engine.webGLVersion === 1) {
  37697. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37698. }
  37699. else {
  37700. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37701. }
  37702. this._texture = texture;
  37703. var callback = function (text) {
  37704. if (typeof text !== "string") {
  37705. return;
  37706. }
  37707. var data = null;
  37708. var tempData = null;
  37709. var line;
  37710. var lines = text.split('\n');
  37711. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37712. var maxColor = 0;
  37713. for (var i = 0; i < lines.length; i++) {
  37714. line = lines[i];
  37715. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37716. continue;
  37717. if (line.indexOf('#') === 0)
  37718. continue;
  37719. var words = line.split(" ");
  37720. if (size === 0) {
  37721. // Number of space + one
  37722. size = words.length;
  37723. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37724. tempData = new Float32Array(size * size * size * 4);
  37725. continue;
  37726. }
  37727. if (size != 0) {
  37728. var r = Math.max(parseInt(words[0]), 0);
  37729. var g = Math.max(parseInt(words[1]), 0);
  37730. var b = Math.max(parseInt(words[2]), 0);
  37731. maxColor = Math.max(r, maxColor);
  37732. maxColor = Math.max(g, maxColor);
  37733. maxColor = Math.max(b, maxColor);
  37734. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37735. if (tempData) {
  37736. tempData[pixelStorageIndex + 0] = r;
  37737. tempData[pixelStorageIndex + 1] = g;
  37738. tempData[pixelStorageIndex + 2] = b;
  37739. }
  37740. pixelIndexSlice++;
  37741. if (pixelIndexSlice % size == 0) {
  37742. pixelIndexH++;
  37743. pixelIndexSlice = 0;
  37744. if (pixelIndexH % size == 0) {
  37745. pixelIndexW++;
  37746. pixelIndexH = 0;
  37747. }
  37748. }
  37749. }
  37750. }
  37751. if (tempData && data) {
  37752. for (var i = 0; i < tempData.length; i++) {
  37753. if (i > 0 && (i + 1) % 4 === 0) {
  37754. data[i] = 255;
  37755. }
  37756. else {
  37757. var value = tempData[i];
  37758. data[i] = (value / maxColor * 255);
  37759. }
  37760. }
  37761. }
  37762. if (texture.is3D) {
  37763. texture.updateSize(size, size, size);
  37764. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37765. }
  37766. else {
  37767. texture.updateSize(size * size, size);
  37768. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37769. }
  37770. };
  37771. var scene = this.getScene();
  37772. if (scene) {
  37773. scene._loadFile(this.url, callback);
  37774. }
  37775. else {
  37776. this._engine._loadFile(this.url, callback);
  37777. }
  37778. return this._texture;
  37779. };
  37780. /**
  37781. * Starts the loading process of the texture.
  37782. */
  37783. ColorGradingTexture.prototype.loadTexture = function () {
  37784. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37785. this.load3dlTexture();
  37786. }
  37787. };
  37788. /**
  37789. * Clones the color gradind texture.
  37790. */
  37791. ColorGradingTexture.prototype.clone = function () {
  37792. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37793. // Base texture
  37794. newTexture.level = this.level;
  37795. return newTexture;
  37796. };
  37797. /**
  37798. * Called during delayed load for textures.
  37799. */
  37800. ColorGradingTexture.prototype.delayLoad = function () {
  37801. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37802. return;
  37803. }
  37804. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37805. this._texture = this._getFromCache(this.url, true);
  37806. if (!this._texture) {
  37807. this.loadTexture();
  37808. }
  37809. };
  37810. /**
  37811. * Parses a color grading texture serialized by Babylon.
  37812. * @param parsedTexture The texture information being parsedTexture
  37813. * @param scene The scene to load the texture in
  37814. * @param rootUrl The root url of the data assets to load
  37815. * @return A color gradind texture
  37816. */
  37817. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37818. var texture = null;
  37819. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37820. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37821. texture.name = parsedTexture.name;
  37822. texture.level = parsedTexture.level;
  37823. }
  37824. return texture;
  37825. };
  37826. /**
  37827. * Serializes the LUT texture to json format.
  37828. */
  37829. ColorGradingTexture.prototype.serialize = function () {
  37830. if (!this.name) {
  37831. return null;
  37832. }
  37833. var serializationObject = {};
  37834. serializationObject.name = this.name;
  37835. serializationObject.level = this.level;
  37836. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37837. return serializationObject;
  37838. };
  37839. /**
  37840. * Empty line regex stored for GC.
  37841. */
  37842. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37843. return ColorGradingTexture;
  37844. }(BABYLON.BaseTexture));
  37845. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37846. })(BABYLON || (BABYLON = {}));
  37847. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37848. var BABYLON;
  37849. (function (BABYLON) {
  37850. /**
  37851. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37852. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37853. * 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;
  37854. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37855. */
  37856. var ColorCurves = /** @class */ (function () {
  37857. function ColorCurves() {
  37858. this._dirty = true;
  37859. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37860. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37861. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37862. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37863. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37864. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37865. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37866. this._globalHue = 30;
  37867. this._globalDensity = 0;
  37868. this._globalSaturation = 0;
  37869. this._globalExposure = 0;
  37870. this._highlightsHue = 30;
  37871. this._highlightsDensity = 0;
  37872. this._highlightsSaturation = 0;
  37873. this._highlightsExposure = 0;
  37874. this._midtonesHue = 30;
  37875. this._midtonesDensity = 0;
  37876. this._midtonesSaturation = 0;
  37877. this._midtonesExposure = 0;
  37878. this._shadowsHue = 30;
  37879. this._shadowsDensity = 0;
  37880. this._shadowsSaturation = 0;
  37881. this._shadowsExposure = 0;
  37882. }
  37883. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37884. /**
  37885. * Gets the global Hue value.
  37886. * 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).
  37887. */
  37888. get: function () {
  37889. return this._globalHue;
  37890. },
  37891. /**
  37892. * Sets the global Hue value.
  37893. * 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).
  37894. */
  37895. set: function (value) {
  37896. this._globalHue = value;
  37897. this._dirty = true;
  37898. },
  37899. enumerable: true,
  37900. configurable: true
  37901. });
  37902. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37903. /**
  37904. * Gets the global Density value.
  37905. * 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.
  37906. * Values less than zero provide a filter of opposite hue.
  37907. */
  37908. get: function () {
  37909. return this._globalDensity;
  37910. },
  37911. /**
  37912. * Sets the global Density value.
  37913. * 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.
  37914. * Values less than zero provide a filter of opposite hue.
  37915. */
  37916. set: function (value) {
  37917. this._globalDensity = value;
  37918. this._dirty = true;
  37919. },
  37920. enumerable: true,
  37921. configurable: true
  37922. });
  37923. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37924. /**
  37925. * Gets the global Saturation value.
  37926. * 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.
  37927. */
  37928. get: function () {
  37929. return this._globalSaturation;
  37930. },
  37931. /**
  37932. * Sets the global Saturation value.
  37933. * 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.
  37934. */
  37935. set: function (value) {
  37936. this._globalSaturation = value;
  37937. this._dirty = true;
  37938. },
  37939. enumerable: true,
  37940. configurable: true
  37941. });
  37942. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37943. /**
  37944. * Gets the highlights Hue value.
  37945. * 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).
  37946. */
  37947. get: function () {
  37948. return this._highlightsHue;
  37949. },
  37950. /**
  37951. * Sets the highlights Hue value.
  37952. * 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).
  37953. */
  37954. set: function (value) {
  37955. this._highlightsHue = value;
  37956. this._dirty = true;
  37957. },
  37958. enumerable: true,
  37959. configurable: true
  37960. });
  37961. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37962. /**
  37963. * Gets the highlights Density value.
  37964. * 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.
  37965. * Values less than zero provide a filter of opposite hue.
  37966. */
  37967. get: function () {
  37968. return this._highlightsDensity;
  37969. },
  37970. /**
  37971. * Sets the highlights Density value.
  37972. * 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.
  37973. * Values less than zero provide a filter of opposite hue.
  37974. */
  37975. set: function (value) {
  37976. this._highlightsDensity = value;
  37977. this._dirty = true;
  37978. },
  37979. enumerable: true,
  37980. configurable: true
  37981. });
  37982. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37983. /**
  37984. * Gets the highlights Saturation value.
  37985. * 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.
  37986. */
  37987. get: function () {
  37988. return this._highlightsSaturation;
  37989. },
  37990. /**
  37991. * Sets the highlights Saturation value.
  37992. * 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.
  37993. */
  37994. set: function (value) {
  37995. this._highlightsSaturation = value;
  37996. this._dirty = true;
  37997. },
  37998. enumerable: true,
  37999. configurable: true
  38000. });
  38001. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38002. /**
  38003. * Gets the highlights Exposure value.
  38004. * 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.
  38005. */
  38006. get: function () {
  38007. return this._highlightsExposure;
  38008. },
  38009. /**
  38010. * Sets the highlights Exposure value.
  38011. * 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.
  38012. */
  38013. set: function (value) {
  38014. this._highlightsExposure = value;
  38015. this._dirty = true;
  38016. },
  38017. enumerable: true,
  38018. configurable: true
  38019. });
  38020. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38021. /**
  38022. * Gets the midtones Hue value.
  38023. * 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).
  38024. */
  38025. get: function () {
  38026. return this._midtonesHue;
  38027. },
  38028. /**
  38029. * Sets the midtones Hue value.
  38030. * 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).
  38031. */
  38032. set: function (value) {
  38033. this._midtonesHue = value;
  38034. this._dirty = true;
  38035. },
  38036. enumerable: true,
  38037. configurable: true
  38038. });
  38039. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38040. /**
  38041. * Gets the midtones Density value.
  38042. * 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.
  38043. * Values less than zero provide a filter of opposite hue.
  38044. */
  38045. get: function () {
  38046. return this._midtonesDensity;
  38047. },
  38048. /**
  38049. * Sets the midtones Density value.
  38050. * 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.
  38051. * Values less than zero provide a filter of opposite hue.
  38052. */
  38053. set: function (value) {
  38054. this._midtonesDensity = value;
  38055. this._dirty = true;
  38056. },
  38057. enumerable: true,
  38058. configurable: true
  38059. });
  38060. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38061. /**
  38062. * Gets the midtones Saturation value.
  38063. * 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.
  38064. */
  38065. get: function () {
  38066. return this._midtonesSaturation;
  38067. },
  38068. /**
  38069. * Sets the midtones Saturation value.
  38070. * 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.
  38071. */
  38072. set: function (value) {
  38073. this._midtonesSaturation = value;
  38074. this._dirty = true;
  38075. },
  38076. enumerable: true,
  38077. configurable: true
  38078. });
  38079. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38080. /**
  38081. * Gets the midtones Exposure value.
  38082. * 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.
  38083. */
  38084. get: function () {
  38085. return this._midtonesExposure;
  38086. },
  38087. /**
  38088. * Sets the midtones Exposure value.
  38089. * 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.
  38090. */
  38091. set: function (value) {
  38092. this._midtonesExposure = value;
  38093. this._dirty = true;
  38094. },
  38095. enumerable: true,
  38096. configurable: true
  38097. });
  38098. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38099. /**
  38100. * Gets the shadows Hue value.
  38101. * 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).
  38102. */
  38103. get: function () {
  38104. return this._shadowsHue;
  38105. },
  38106. /**
  38107. * Sets the shadows Hue value.
  38108. * 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).
  38109. */
  38110. set: function (value) {
  38111. this._shadowsHue = value;
  38112. this._dirty = true;
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38118. /**
  38119. * Gets the shadows Density value.
  38120. * 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.
  38121. * Values less than zero provide a filter of opposite hue.
  38122. */
  38123. get: function () {
  38124. return this._shadowsDensity;
  38125. },
  38126. /**
  38127. * Sets the shadows Density value.
  38128. * 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.
  38129. * Values less than zero provide a filter of opposite hue.
  38130. */
  38131. set: function (value) {
  38132. this._shadowsDensity = value;
  38133. this._dirty = true;
  38134. },
  38135. enumerable: true,
  38136. configurable: true
  38137. });
  38138. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38139. /**
  38140. * Gets the shadows Saturation value.
  38141. * 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.
  38142. */
  38143. get: function () {
  38144. return this._shadowsSaturation;
  38145. },
  38146. /**
  38147. * Sets the shadows Saturation value.
  38148. * 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.
  38149. */
  38150. set: function (value) {
  38151. this._shadowsSaturation = value;
  38152. this._dirty = true;
  38153. },
  38154. enumerable: true,
  38155. configurable: true
  38156. });
  38157. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38158. /**
  38159. * Gets the shadows Exposure value.
  38160. * 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.
  38161. */
  38162. get: function () {
  38163. return this._shadowsExposure;
  38164. },
  38165. /**
  38166. * Sets the shadows Exposure value.
  38167. * 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.
  38168. */
  38169. set: function (value) {
  38170. this._shadowsExposure = value;
  38171. this._dirty = true;
  38172. },
  38173. enumerable: true,
  38174. configurable: true
  38175. });
  38176. ColorCurves.prototype.getClassName = function () {
  38177. return "ColorCurves";
  38178. };
  38179. /**
  38180. * Binds the color curves to the shader.
  38181. * @param colorCurves The color curve to bind
  38182. * @param effect The effect to bind to
  38183. */
  38184. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38185. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38186. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38187. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38188. if (colorCurves._dirty) {
  38189. colorCurves._dirty = false;
  38190. // Fill in global info.
  38191. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38192. // Compute highlights info.
  38193. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38194. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38195. // Compute midtones info.
  38196. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38197. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38198. // Compute shadows info.
  38199. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38200. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38201. // Compute deltas (neutral is midtones).
  38202. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38203. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38204. }
  38205. if (effect) {
  38206. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38207. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38208. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38209. }
  38210. };
  38211. /**
  38212. * Prepare the list of uniforms associated with the ColorCurves effects.
  38213. * @param uniformsList The list of uniforms used in the effect
  38214. */
  38215. ColorCurves.PrepareUniforms = function (uniformsList) {
  38216. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38217. };
  38218. /**
  38219. * Returns color grading data based on a hue, density, saturation and exposure value.
  38220. * @param filterHue The hue of the color filter.
  38221. * @param filterDensity The density of the color filter.
  38222. * @param saturation The saturation.
  38223. * @param exposure The exposure.
  38224. * @param result The result data container.
  38225. */
  38226. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38227. if (hue == null) {
  38228. return;
  38229. }
  38230. hue = ColorCurves.clamp(hue, 0, 360);
  38231. density = ColorCurves.clamp(density, -100, 100);
  38232. saturation = ColorCurves.clamp(saturation, -100, 100);
  38233. exposure = ColorCurves.clamp(exposure, -100, 100);
  38234. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38235. // so that the maximum filter density is only 50% control. This provides fine control
  38236. // for small values and reasonable range.
  38237. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38238. density *= 0.5;
  38239. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38240. if (density < 0) {
  38241. density *= -1;
  38242. hue = (hue + 180) % 360;
  38243. }
  38244. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38245. result.scaleToRef(2, result);
  38246. result.a = 1 + 0.01 * saturation;
  38247. };
  38248. /**
  38249. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38250. * @param value The input slider value in range [-100,100].
  38251. * @returns Adjusted value.
  38252. */
  38253. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38254. value /= 100;
  38255. var x = Math.abs(value);
  38256. x = Math.pow(x, 2);
  38257. if (value < 0) {
  38258. x *= -1;
  38259. }
  38260. x *= 100;
  38261. return x;
  38262. };
  38263. /**
  38264. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38265. * @param hue The hue (H) input.
  38266. * @param saturation The saturation (S) input.
  38267. * @param brightness The brightness (B) input.
  38268. * @result An RGBA color represented as Vector4.
  38269. */
  38270. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38271. var h = ColorCurves.clamp(hue, 0, 360);
  38272. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38273. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38274. if (s === 0) {
  38275. result.r = v;
  38276. result.g = v;
  38277. result.b = v;
  38278. }
  38279. else {
  38280. // sector 0 to 5
  38281. h /= 60;
  38282. var i = Math.floor(h);
  38283. // fractional part of h
  38284. var f = h - i;
  38285. var p = v * (1 - s);
  38286. var q = v * (1 - s * f);
  38287. var t = v * (1 - s * (1 - f));
  38288. switch (i) {
  38289. case 0:
  38290. result.r = v;
  38291. result.g = t;
  38292. result.b = p;
  38293. break;
  38294. case 1:
  38295. result.r = q;
  38296. result.g = v;
  38297. result.b = p;
  38298. break;
  38299. case 2:
  38300. result.r = p;
  38301. result.g = v;
  38302. result.b = t;
  38303. break;
  38304. case 3:
  38305. result.r = p;
  38306. result.g = q;
  38307. result.b = v;
  38308. break;
  38309. case 4:
  38310. result.r = t;
  38311. result.g = p;
  38312. result.b = v;
  38313. break;
  38314. default:// case 5:
  38315. result.r = v;
  38316. result.g = p;
  38317. result.b = q;
  38318. break;
  38319. }
  38320. }
  38321. result.a = 1;
  38322. };
  38323. /**
  38324. * Returns a value clamped between min and max
  38325. * @param value The value to clamp
  38326. * @param min The minimum of value
  38327. * @param max The maximum of value
  38328. * @returns The clamped value.
  38329. */
  38330. ColorCurves.clamp = function (value, min, max) {
  38331. return Math.min(Math.max(value, min), max);
  38332. };
  38333. /**
  38334. * Clones the current color curve instance.
  38335. * @return The cloned curves
  38336. */
  38337. ColorCurves.prototype.clone = function () {
  38338. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38339. };
  38340. /**
  38341. * Serializes the current color curve instance to a json representation.
  38342. * @return a JSON representation
  38343. */
  38344. ColorCurves.prototype.serialize = function () {
  38345. return BABYLON.SerializationHelper.Serialize(this);
  38346. };
  38347. /**
  38348. * Parses the color curve from a json representation.
  38349. * @param source the JSON source to parse
  38350. * @return The parsed curves
  38351. */
  38352. ColorCurves.Parse = function (source) {
  38353. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38354. };
  38355. __decorate([
  38356. BABYLON.serialize()
  38357. ], ColorCurves.prototype, "_globalHue", void 0);
  38358. __decorate([
  38359. BABYLON.serialize()
  38360. ], ColorCurves.prototype, "_globalDensity", void 0);
  38361. __decorate([
  38362. BABYLON.serialize()
  38363. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38364. __decorate([
  38365. BABYLON.serialize()
  38366. ], ColorCurves.prototype, "_globalExposure", void 0);
  38367. __decorate([
  38368. BABYLON.serialize()
  38369. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38370. __decorate([
  38371. BABYLON.serialize()
  38372. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38373. __decorate([
  38374. BABYLON.serialize()
  38375. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38376. __decorate([
  38377. BABYLON.serialize()
  38378. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38379. __decorate([
  38380. BABYLON.serialize()
  38381. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38382. __decorate([
  38383. BABYLON.serialize()
  38384. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38385. __decorate([
  38386. BABYLON.serialize()
  38387. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38388. __decorate([
  38389. BABYLON.serialize()
  38390. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38391. return ColorCurves;
  38392. }());
  38393. BABYLON.ColorCurves = ColorCurves;
  38394. })(BABYLON || (BABYLON = {}));
  38395. //# sourceMappingURL=babylon.colorCurves.js.map
  38396. //# sourceMappingURL=babylon.behavior.js.map
  38397. var BABYLON;
  38398. (function (BABYLON) {
  38399. /**
  38400. * "Static Class" containing the most commonly used helper while dealing with material for
  38401. * rendering purpose.
  38402. *
  38403. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38404. *
  38405. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38406. */
  38407. var MaterialHelper = /** @class */ (function () {
  38408. function MaterialHelper() {
  38409. }
  38410. /**
  38411. * Bind the current view position to an effect.
  38412. * @param effect The effect to be bound
  38413. * @param scene The scene the eyes position is used from
  38414. */
  38415. MaterialHelper.BindEyePosition = function (effect, scene) {
  38416. if (scene._forcedViewPosition) {
  38417. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38418. return;
  38419. }
  38420. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38421. };
  38422. /**
  38423. * Helps preparing the defines values about the UVs in used in the effect.
  38424. * UVs are shared as much as we can accross chanels in the shaders.
  38425. * @param texture The texture we are preparing the UVs for
  38426. * @param defines The defines to update
  38427. * @param key The chanel key "diffuse", "specular"... used in the shader
  38428. */
  38429. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38430. defines._needUVs = true;
  38431. defines[key] = true;
  38432. if (texture.getTextureMatrix().isIdentity(true)) {
  38433. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38434. if (texture.coordinatesIndex === 0) {
  38435. defines["MAINUV1"] = true;
  38436. }
  38437. else {
  38438. defines["MAINUV2"] = true;
  38439. }
  38440. }
  38441. else {
  38442. defines[key + "DIRECTUV"] = 0;
  38443. }
  38444. };
  38445. /**
  38446. * Binds a texture matrix value to its corrsponding uniform
  38447. * @param texture The texture to bind the matrix for
  38448. * @param uniformBuffer The uniform buffer receivin the data
  38449. * @param key The chanel key "diffuse", "specular"... used in the shader
  38450. */
  38451. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38452. var matrix = texture.getTextureMatrix();
  38453. if (!matrix.isIdentity(true)) {
  38454. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38455. }
  38456. };
  38457. /**
  38458. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38459. * @param mesh defines the current mesh
  38460. * @param scene defines the current scene
  38461. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38462. * @param pointsCloud defines if point cloud rendering has to be turned on
  38463. * @param fogEnabled defines if fog has to be turned on
  38464. * @param alphaTest defines if alpha testing has to be turned on
  38465. * @param defines defines the current list of defines
  38466. */
  38467. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38468. if (defines._areMiscDirty) {
  38469. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38470. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38471. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38472. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38473. defines["ALPHATEST"] = alphaTest;
  38474. }
  38475. };
  38476. /**
  38477. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38478. * @param scene defines the current scene
  38479. * @param engine defines the current engine
  38480. * @param defines specifies the list of active defines
  38481. * @param useInstances defines if instances have to be turned on
  38482. * @param useClipPlane defines if clip plane have to be turned on
  38483. */
  38484. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38485. if (useClipPlane === void 0) { useClipPlane = null; }
  38486. var changed = false;
  38487. if (useClipPlane == null) {
  38488. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38489. }
  38490. if (defines["CLIPPLANE"] !== useClipPlane) {
  38491. defines["CLIPPLANE"] = useClipPlane;
  38492. changed = true;
  38493. }
  38494. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38495. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38496. changed = true;
  38497. }
  38498. if (defines["INSTANCES"] !== useInstances) {
  38499. defines["INSTANCES"] = useInstances;
  38500. changed = true;
  38501. }
  38502. if (changed) {
  38503. defines.markAsUnprocessed();
  38504. }
  38505. };
  38506. /**
  38507. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38508. * @param mesh The mesh containing the geometry data we will draw
  38509. * @param defines The defines to update
  38510. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38511. * @param useBones Precise whether bones should be used or not (override mesh info)
  38512. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38513. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38514. * @returns false if defines are considered not dirty and have not been checked
  38515. */
  38516. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38517. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38518. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38519. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38520. return false;
  38521. }
  38522. defines._normals = defines._needNormals;
  38523. defines._uvs = defines._needUVs;
  38524. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38525. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38526. defines["TANGENT"] = true;
  38527. }
  38528. if (defines._needUVs) {
  38529. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38530. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38531. }
  38532. else {
  38533. defines["UV1"] = false;
  38534. defines["UV2"] = false;
  38535. }
  38536. if (useVertexColor) {
  38537. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38538. defines["VERTEXCOLOR"] = hasVertexColors;
  38539. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38540. }
  38541. if (useBones) {
  38542. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38543. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38544. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38545. }
  38546. else {
  38547. defines["NUM_BONE_INFLUENCERS"] = 0;
  38548. defines["BonesPerMesh"] = 0;
  38549. }
  38550. }
  38551. if (useMorphTargets) {
  38552. var manager = mesh.morphTargetManager;
  38553. if (manager) {
  38554. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38555. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38556. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38557. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38558. }
  38559. else {
  38560. defines["MORPHTARGETS_TANGENT"] = false;
  38561. defines["MORPHTARGETS_NORMAL"] = false;
  38562. defines["MORPHTARGETS"] = false;
  38563. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38564. }
  38565. }
  38566. return true;
  38567. };
  38568. /**
  38569. * Prepares the defines related to the light information passed in parameter
  38570. * @param scene The scene we are intending to draw
  38571. * @param mesh The mesh the effect is compiling for
  38572. * @param defines The defines to update
  38573. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38574. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38575. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38576. * @returns true if normals will be required for the rest of the effect
  38577. */
  38578. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38579. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38580. if (disableLighting === void 0) { disableLighting = false; }
  38581. if (!defines._areLightsDirty) {
  38582. return defines._needNormals;
  38583. }
  38584. var lightIndex = 0;
  38585. var needNormals = false;
  38586. var needRebuild = false;
  38587. var lightmapMode = false;
  38588. var shadowEnabled = false;
  38589. var specularEnabled = false;
  38590. if (scene.lightsEnabled && !disableLighting) {
  38591. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38592. var light = _a[_i];
  38593. needNormals = true;
  38594. if (defines["LIGHT" + lightIndex] === undefined) {
  38595. needRebuild = true;
  38596. }
  38597. defines["LIGHT" + lightIndex] = true;
  38598. defines["SPOTLIGHT" + lightIndex] = false;
  38599. defines["HEMILIGHT" + lightIndex] = false;
  38600. defines["POINTLIGHT" + lightIndex] = false;
  38601. defines["DIRLIGHT" + lightIndex] = false;
  38602. var type;
  38603. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38604. type = "SPOTLIGHT" + lightIndex;
  38605. var spotLight = light;
  38606. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38607. }
  38608. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38609. type = "HEMILIGHT" + lightIndex;
  38610. }
  38611. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38612. type = "POINTLIGHT" + lightIndex;
  38613. }
  38614. else {
  38615. type = "DIRLIGHT" + lightIndex;
  38616. }
  38617. defines[type] = true;
  38618. // Specular
  38619. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38620. specularEnabled = true;
  38621. }
  38622. // Shadows
  38623. defines["SHADOW" + lightIndex] = false;
  38624. defines["SHADOWPCF" + lightIndex] = false;
  38625. defines["SHADOWESM" + lightIndex] = false;
  38626. defines["SHADOWCUBE" + lightIndex] = false;
  38627. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38628. var shadowGenerator = light.getShadowGenerator();
  38629. if (shadowGenerator) {
  38630. shadowEnabled = true;
  38631. shadowGenerator.prepareDefines(defines, lightIndex);
  38632. }
  38633. }
  38634. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38635. lightmapMode = true;
  38636. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38637. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38638. }
  38639. else {
  38640. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38641. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38642. }
  38643. lightIndex++;
  38644. if (lightIndex === maxSimultaneousLights)
  38645. break;
  38646. }
  38647. }
  38648. defines["SPECULARTERM"] = specularEnabled;
  38649. defines["SHADOWS"] = shadowEnabled;
  38650. // Resetting all other lights if any
  38651. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38652. if (defines["LIGHT" + index] !== undefined) {
  38653. defines["LIGHT" + index] = false;
  38654. defines["HEMILIGHT" + lightIndex] = false;
  38655. defines["POINTLIGHT" + lightIndex] = false;
  38656. defines["DIRLIGHT" + lightIndex] = false;
  38657. defines["SPOTLIGHT" + lightIndex] = false;
  38658. defines["SHADOW" + lightIndex] = false;
  38659. }
  38660. }
  38661. var caps = scene.getEngine().getCaps();
  38662. if (defines["SHADOWFLOAT"] === undefined) {
  38663. needRebuild = true;
  38664. }
  38665. defines["SHADOWFLOAT"] = shadowEnabled &&
  38666. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38667. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38668. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38669. if (needRebuild) {
  38670. defines.rebuild();
  38671. }
  38672. return needNormals;
  38673. };
  38674. /**
  38675. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38676. * that won t be acctive due to defines being turned off.
  38677. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38678. * @param samplersList The samplers list
  38679. * @param defines The defines helping in the list generation
  38680. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38681. */
  38682. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38683. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38684. var uniformsList;
  38685. var uniformBuffersList = null;
  38686. if (uniformsListOrOptions.uniformsNames) {
  38687. var options = uniformsListOrOptions;
  38688. uniformsList = options.uniformsNames;
  38689. uniformBuffersList = options.uniformBuffersNames;
  38690. samplersList = options.samplers;
  38691. defines = options.defines;
  38692. maxSimultaneousLights = options.maxSimultaneousLights;
  38693. }
  38694. else {
  38695. uniformsList = uniformsListOrOptions;
  38696. if (!samplersList) {
  38697. samplersList = [];
  38698. }
  38699. }
  38700. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38701. if (!defines["LIGHT" + lightIndex]) {
  38702. break;
  38703. }
  38704. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38705. if (uniformBuffersList) {
  38706. uniformBuffersList.push("Light" + lightIndex);
  38707. }
  38708. samplersList.push("shadowSampler" + lightIndex);
  38709. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38710. samplersList.push("projectionLightSampler" + lightIndex);
  38711. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38712. }
  38713. }
  38714. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38715. uniformsList.push("morphTargetInfluences");
  38716. }
  38717. };
  38718. /**
  38719. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38720. * @param defines The defines to update while falling back
  38721. * @param fallbacks The authorized effect fallbacks
  38722. * @param maxSimultaneousLights The maximum number of lights allowed
  38723. * @param rank the current rank of the Effect
  38724. * @returns The newly affected rank
  38725. */
  38726. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38727. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38728. if (rank === void 0) { rank = 0; }
  38729. var lightFallbackRank = 0;
  38730. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38731. if (!defines["LIGHT" + lightIndex]) {
  38732. break;
  38733. }
  38734. if (lightIndex > 0) {
  38735. lightFallbackRank = rank + lightIndex;
  38736. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38737. }
  38738. if (!defines["SHADOWS"]) {
  38739. if (defines["SHADOW" + lightIndex]) {
  38740. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38741. }
  38742. if (defines["SHADOWPCF" + lightIndex]) {
  38743. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38744. }
  38745. if (defines["SHADOWESM" + lightIndex]) {
  38746. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38747. }
  38748. }
  38749. }
  38750. return lightFallbackRank++;
  38751. };
  38752. /**
  38753. * Prepares the list of attributes required for morph targets according to the effect defines.
  38754. * @param attribs The current list of supported attribs
  38755. * @param mesh The mesh to prepare the morph targets attributes for
  38756. * @param defines The current Defines of the effect
  38757. */
  38758. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38759. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38760. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38761. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38762. var manager = mesh.morphTargetManager;
  38763. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38764. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38765. for (var index = 0; index < influencers; index++) {
  38766. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38767. if (normal) {
  38768. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38769. }
  38770. if (tangent) {
  38771. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38772. }
  38773. if (attribs.length > maxAttributesCount) {
  38774. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38775. }
  38776. }
  38777. }
  38778. };
  38779. /**
  38780. * Prepares the list of attributes required for bones according to the effect defines.
  38781. * @param attribs The current list of supported attribs
  38782. * @param mesh The mesh to prepare the bones attributes for
  38783. * @param defines The current Defines of the effect
  38784. * @param fallbacks The current efffect fallback strategy
  38785. */
  38786. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38787. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38788. fallbacks.addCPUSkinningFallback(0, mesh);
  38789. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38790. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38791. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38792. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38793. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38794. }
  38795. }
  38796. };
  38797. /**
  38798. * Prepares the list of attributes required for instances according to the effect defines.
  38799. * @param attribs The current list of supported attribs
  38800. * @param defines The current Defines of the effect
  38801. */
  38802. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38803. if (defines["INSTANCES"]) {
  38804. attribs.push("world0");
  38805. attribs.push("world1");
  38806. attribs.push("world2");
  38807. attribs.push("world3");
  38808. }
  38809. };
  38810. /**
  38811. * Binds the light shadow information to the effect for the given mesh.
  38812. * @param light The light containing the generator
  38813. * @param scene The scene the lights belongs to
  38814. * @param mesh The mesh we are binding the information to render
  38815. * @param lightIndex The light index in the effect used to render the mesh
  38816. * @param effect The effect we are binding the data to
  38817. */
  38818. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38819. if (light.shadowEnabled && mesh.receiveShadows) {
  38820. var shadowGenerator = light.getShadowGenerator();
  38821. if (shadowGenerator) {
  38822. shadowGenerator.bindShadowLight(lightIndex, effect);
  38823. }
  38824. }
  38825. };
  38826. /**
  38827. * Binds the light information to the effect.
  38828. * @param light The light containing the generator
  38829. * @param effect The effect we are binding the data to
  38830. * @param lightIndex The light index in the effect used to render
  38831. */
  38832. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38833. light.transferToEffect(effect, lightIndex + "");
  38834. };
  38835. /**
  38836. * Binds the lights information from the scene to the effect for the given mesh.
  38837. * @param scene The scene the lights belongs to
  38838. * @param mesh The mesh we are binding the information to render
  38839. * @param effect The effect we are binding the data to
  38840. * @param defines The generated defines for the effect
  38841. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38842. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38843. */
  38844. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38845. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38846. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38847. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38848. for (var i = 0; i < len; i++) {
  38849. var light = mesh._lightSources[i];
  38850. var iAsString = i.toString();
  38851. var scaledIntensity = light.getScaledIntensity();
  38852. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38853. MaterialHelper.BindLightProperties(light, effect, i);
  38854. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38855. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38856. if (defines["SPECULARTERM"]) {
  38857. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38858. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38859. }
  38860. // Shadows
  38861. if (scene.shadowsEnabled) {
  38862. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38863. }
  38864. light._uniformBuffer.update();
  38865. }
  38866. };
  38867. /**
  38868. * Binds the fog information from the scene to the effect for the given mesh.
  38869. * @param scene The scene the lights belongs to
  38870. * @param mesh The mesh we are binding the information to render
  38871. * @param effect The effect we are binding the data to
  38872. */
  38873. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38874. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38875. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38876. effect.setColor3("vFogColor", scene.fogColor);
  38877. }
  38878. };
  38879. /**
  38880. * Binds the bones information from the mesh to the effect.
  38881. * @param mesh The mesh we are binding the information to render
  38882. * @param effect The effect we are binding the data to
  38883. */
  38884. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38885. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38886. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38887. if (matrices && effect) {
  38888. effect.setMatrices("mBones", matrices);
  38889. }
  38890. }
  38891. };
  38892. /**
  38893. * Binds the morph targets information from the mesh to the effect.
  38894. * @param abstractMesh The mesh we are binding the information to render
  38895. * @param effect The effect we are binding the data to
  38896. */
  38897. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38898. var manager = abstractMesh.morphTargetManager;
  38899. if (!abstractMesh || !manager) {
  38900. return;
  38901. }
  38902. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38903. };
  38904. /**
  38905. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38906. * @param defines The generated defines used in the effect
  38907. * @param effect The effect we are binding the data to
  38908. * @param scene The scene we are willing to render with logarithmic scale for
  38909. */
  38910. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38911. if (defines["LOGARITHMICDEPTH"]) {
  38912. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38913. }
  38914. };
  38915. /**
  38916. * Binds the clip plane information from the scene to the effect.
  38917. * @param scene The scene the clip plane information are extracted from
  38918. * @param effect The effect we are binding the data to
  38919. */
  38920. MaterialHelper.BindClipPlane = function (effect, scene) {
  38921. if (scene.clipPlane) {
  38922. var clipPlane = scene.clipPlane;
  38923. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38924. }
  38925. };
  38926. return MaterialHelper;
  38927. }());
  38928. BABYLON.MaterialHelper = MaterialHelper;
  38929. })(BABYLON || (BABYLON = {}));
  38930. //# sourceMappingURL=babylon.materialHelper.js.map
  38931. var BABYLON;
  38932. (function (BABYLON) {
  38933. var PushMaterial = /** @class */ (function (_super) {
  38934. __extends(PushMaterial, _super);
  38935. function PushMaterial(name, scene) {
  38936. var _this = _super.call(this, name, scene) || this;
  38937. _this._normalMatrix = new BABYLON.Matrix();
  38938. _this.storeEffectOnSubMeshes = true;
  38939. return _this;
  38940. }
  38941. PushMaterial.prototype.getEffect = function () {
  38942. return this._activeEffect;
  38943. };
  38944. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38945. if (!mesh) {
  38946. return false;
  38947. }
  38948. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38949. return true;
  38950. }
  38951. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38952. };
  38953. /**
  38954. * Binds the given world matrix to the active effect
  38955. *
  38956. * @param world the matrix to bind
  38957. */
  38958. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38959. this._activeEffect.setMatrix("world", world);
  38960. };
  38961. /**
  38962. * Binds the given normal matrix to the active effect
  38963. *
  38964. * @param normalMatrix the matrix to bind
  38965. */
  38966. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38967. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38968. };
  38969. PushMaterial.prototype.bind = function (world, mesh) {
  38970. if (!mesh) {
  38971. return;
  38972. }
  38973. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38974. };
  38975. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38976. if (effect === void 0) { effect = null; }
  38977. _super.prototype._afterBind.call(this, mesh);
  38978. this.getScene()._cachedEffect = effect;
  38979. };
  38980. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38981. if (visibility === void 0) { visibility = 1; }
  38982. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38983. };
  38984. return PushMaterial;
  38985. }(BABYLON.Material));
  38986. BABYLON.PushMaterial = PushMaterial;
  38987. })(BABYLON || (BABYLON = {}));
  38988. //# sourceMappingURL=babylon.pushMaterial.js.map
  38989. var BABYLON;
  38990. (function (BABYLON) {
  38991. /** @ignore */
  38992. var StandardMaterialDefines = /** @class */ (function (_super) {
  38993. __extends(StandardMaterialDefines, _super);
  38994. function StandardMaterialDefines() {
  38995. var _this = _super.call(this) || this;
  38996. _this.MAINUV1 = false;
  38997. _this.MAINUV2 = false;
  38998. _this.DIFFUSE = false;
  38999. _this.DIFFUSEDIRECTUV = 0;
  39000. _this.AMBIENT = false;
  39001. _this.AMBIENTDIRECTUV = 0;
  39002. _this.OPACITY = false;
  39003. _this.OPACITYDIRECTUV = 0;
  39004. _this.OPACITYRGB = false;
  39005. _this.REFLECTION = false;
  39006. _this.EMISSIVE = false;
  39007. _this.EMISSIVEDIRECTUV = 0;
  39008. _this.SPECULAR = false;
  39009. _this.SPECULARDIRECTUV = 0;
  39010. _this.BUMP = false;
  39011. _this.BUMPDIRECTUV = 0;
  39012. _this.PARALLAX = false;
  39013. _this.PARALLAXOCCLUSION = false;
  39014. _this.SPECULAROVERALPHA = false;
  39015. _this.CLIPPLANE = false;
  39016. _this.ALPHATEST = false;
  39017. _this.DEPTHPREPASS = false;
  39018. _this.ALPHAFROMDIFFUSE = false;
  39019. _this.POINTSIZE = false;
  39020. _this.FOG = false;
  39021. _this.SPECULARTERM = false;
  39022. _this.DIFFUSEFRESNEL = false;
  39023. _this.OPACITYFRESNEL = false;
  39024. _this.REFLECTIONFRESNEL = false;
  39025. _this.REFRACTIONFRESNEL = false;
  39026. _this.EMISSIVEFRESNEL = false;
  39027. _this.FRESNEL = false;
  39028. _this.NORMAL = false;
  39029. _this.UV1 = false;
  39030. _this.UV2 = false;
  39031. _this.VERTEXCOLOR = false;
  39032. _this.VERTEXALPHA = false;
  39033. _this.NUM_BONE_INFLUENCERS = 0;
  39034. _this.BonesPerMesh = 0;
  39035. _this.INSTANCES = false;
  39036. _this.GLOSSINESS = false;
  39037. _this.ROUGHNESS = false;
  39038. _this.EMISSIVEASILLUMINATION = false;
  39039. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39040. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39041. _this.LIGHTMAP = false;
  39042. _this.LIGHTMAPDIRECTUV = 0;
  39043. _this.OBJECTSPACE_NORMALMAP = false;
  39044. _this.USELIGHTMAPASSHADOWMAP = false;
  39045. _this.REFLECTIONMAP_3D = false;
  39046. _this.REFLECTIONMAP_SPHERICAL = false;
  39047. _this.REFLECTIONMAP_PLANAR = false;
  39048. _this.REFLECTIONMAP_CUBIC = false;
  39049. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39050. _this.REFLECTIONMAP_PROJECTION = false;
  39051. _this.REFLECTIONMAP_SKYBOX = false;
  39052. _this.REFLECTIONMAP_EXPLICIT = false;
  39053. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39054. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39055. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39056. _this.INVERTCUBICMAP = false;
  39057. _this.LOGARITHMICDEPTH = false;
  39058. _this.REFRACTION = false;
  39059. _this.REFRACTIONMAP_3D = false;
  39060. _this.REFLECTIONOVERALPHA = false;
  39061. _this.TWOSIDEDLIGHTING = false;
  39062. _this.SHADOWFLOAT = false;
  39063. _this.MORPHTARGETS = false;
  39064. _this.MORPHTARGETS_NORMAL = false;
  39065. _this.MORPHTARGETS_TANGENT = false;
  39066. _this.NUM_MORPH_INFLUENCERS = 0;
  39067. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39068. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39069. _this.IMAGEPROCESSING = false;
  39070. _this.VIGNETTE = false;
  39071. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39072. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39073. _this.TONEMAPPING = false;
  39074. _this.CONTRAST = false;
  39075. _this.COLORCURVES = false;
  39076. _this.COLORGRADING = false;
  39077. _this.COLORGRADING3D = false;
  39078. _this.SAMPLER3DGREENDEPTH = false;
  39079. _this.SAMPLER3DBGRMAP = false;
  39080. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39081. _this.EXPOSURE = false;
  39082. _this.GRAIN = false;
  39083. _this.rebuild();
  39084. return _this;
  39085. }
  39086. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39087. var modes = [
  39088. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39089. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39090. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39091. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39092. ];
  39093. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39094. var mode = modes_1[_i];
  39095. this[mode] = (mode === modeToEnable);
  39096. }
  39097. };
  39098. return StandardMaterialDefines;
  39099. }(BABYLON.MaterialDefines));
  39100. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39101. var StandardMaterial = /** @class */ (function (_super) {
  39102. __extends(StandardMaterial, _super);
  39103. function StandardMaterial(name, scene) {
  39104. var _this = _super.call(this, name, scene) || this;
  39105. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39106. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39107. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39108. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39109. _this.specularPower = 64;
  39110. _this._useAlphaFromDiffuseTexture = false;
  39111. _this._useEmissiveAsIllumination = false;
  39112. _this._linkEmissiveWithDiffuse = false;
  39113. _this._useSpecularOverAlpha = false;
  39114. _this._useReflectionOverAlpha = false;
  39115. _this._disableLighting = false;
  39116. _this._useObjectSpaceNormalMap = false;
  39117. _this._useParallax = false;
  39118. _this._useParallaxOcclusion = false;
  39119. _this.parallaxScaleBias = 0.05;
  39120. _this._roughness = 0;
  39121. _this.indexOfRefraction = 0.98;
  39122. _this.invertRefractionY = true;
  39123. _this._useLightmapAsShadowmap = false;
  39124. _this._useReflectionFresnelFromSpecular = false;
  39125. _this._useGlossinessFromSpecularMapAlpha = false;
  39126. _this._maxSimultaneousLights = 4;
  39127. /**
  39128. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39129. */
  39130. _this._invertNormalMapX = false;
  39131. /**
  39132. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39133. */
  39134. _this._invertNormalMapY = false;
  39135. /**
  39136. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39137. */
  39138. _this._twoSidedLighting = false;
  39139. _this._renderTargets = new BABYLON.SmartArray(16);
  39140. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39141. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39142. // Setup the default processing configuration to the scene.
  39143. _this._attachImageProcessingConfiguration(null);
  39144. _this.getRenderTargetTextures = function () {
  39145. _this._renderTargets.reset();
  39146. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39147. _this._renderTargets.push(_this._reflectionTexture);
  39148. }
  39149. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39150. _this._renderTargets.push(_this._refractionTexture);
  39151. }
  39152. return _this._renderTargets;
  39153. };
  39154. return _this;
  39155. }
  39156. ;
  39157. ;
  39158. ;
  39159. ;
  39160. ;
  39161. ;
  39162. ;
  39163. ;
  39164. ;
  39165. ;
  39166. ;
  39167. ;
  39168. ;
  39169. ;
  39170. ;
  39171. ;
  39172. ;
  39173. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39174. /**
  39175. * Gets the image processing configuration used either in this material.
  39176. */
  39177. get: function () {
  39178. return this._imageProcessingConfiguration;
  39179. },
  39180. /**
  39181. * Sets the Default image processing configuration used either in the this material.
  39182. *
  39183. * If sets to null, the scene one is in use.
  39184. */
  39185. set: function (value) {
  39186. this._attachImageProcessingConfiguration(value);
  39187. // Ensure the effect will be rebuilt.
  39188. this._markAllSubMeshesAsTexturesDirty();
  39189. },
  39190. enumerable: true,
  39191. configurable: true
  39192. });
  39193. /**
  39194. * Attaches a new image processing configuration to the Standard Material.
  39195. * @param configuration
  39196. */
  39197. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39198. var _this = this;
  39199. if (configuration === this._imageProcessingConfiguration) {
  39200. return;
  39201. }
  39202. // Detaches observer.
  39203. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39204. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39205. }
  39206. // Pick the scene configuration if needed.
  39207. if (!configuration) {
  39208. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39209. }
  39210. else {
  39211. this._imageProcessingConfiguration = configuration;
  39212. }
  39213. // Attaches observer.
  39214. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39215. _this._markAllSubMeshesAsImageProcessingDirty();
  39216. });
  39217. };
  39218. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39219. /**
  39220. * Gets wether the color curves effect is enabled.
  39221. */
  39222. get: function () {
  39223. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39224. },
  39225. /**
  39226. * Sets wether the color curves effect is enabled.
  39227. */
  39228. set: function (value) {
  39229. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39230. },
  39231. enumerable: true,
  39232. configurable: true
  39233. });
  39234. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39235. /**
  39236. * Gets wether the color grading effect is enabled.
  39237. */
  39238. get: function () {
  39239. return this.imageProcessingConfiguration.colorGradingEnabled;
  39240. },
  39241. /**
  39242. * Gets wether the color grading effect is enabled.
  39243. */
  39244. set: function (value) {
  39245. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39246. },
  39247. enumerable: true,
  39248. configurable: true
  39249. });
  39250. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39251. /**
  39252. * Gets wether tonemapping is enabled or not.
  39253. */
  39254. get: function () {
  39255. return this._imageProcessingConfiguration.toneMappingEnabled;
  39256. },
  39257. /**
  39258. * Sets wether tonemapping is enabled or not
  39259. */
  39260. set: function (value) {
  39261. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. ;
  39267. ;
  39268. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39269. /**
  39270. * The camera exposure used on this material.
  39271. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39272. * This corresponds to a photographic exposure.
  39273. */
  39274. get: function () {
  39275. return this._imageProcessingConfiguration.exposure;
  39276. },
  39277. /**
  39278. * The camera exposure used on this material.
  39279. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39280. * This corresponds to a photographic exposure.
  39281. */
  39282. set: function (value) {
  39283. this._imageProcessingConfiguration.exposure = value;
  39284. },
  39285. enumerable: true,
  39286. configurable: true
  39287. });
  39288. ;
  39289. ;
  39290. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39291. /**
  39292. * Gets The camera contrast used on this material.
  39293. */
  39294. get: function () {
  39295. return this._imageProcessingConfiguration.contrast;
  39296. },
  39297. /**
  39298. * Sets The camera contrast used on this material.
  39299. */
  39300. set: function (value) {
  39301. this._imageProcessingConfiguration.contrast = value;
  39302. },
  39303. enumerable: true,
  39304. configurable: true
  39305. });
  39306. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39307. /**
  39308. * Gets the Color Grading 2D Lookup Texture.
  39309. */
  39310. get: function () {
  39311. return this._imageProcessingConfiguration.colorGradingTexture;
  39312. },
  39313. /**
  39314. * Sets the Color Grading 2D Lookup Texture.
  39315. */
  39316. set: function (value) {
  39317. this._imageProcessingConfiguration.colorGradingTexture = value;
  39318. },
  39319. enumerable: true,
  39320. configurable: true
  39321. });
  39322. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39323. /**
  39324. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39325. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39326. * 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;
  39327. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39328. */
  39329. get: function () {
  39330. return this._imageProcessingConfiguration.colorCurves;
  39331. },
  39332. /**
  39333. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39334. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39335. * 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;
  39336. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39337. */
  39338. set: function (value) {
  39339. this._imageProcessingConfiguration.colorCurves = value;
  39340. },
  39341. enumerable: true,
  39342. configurable: true
  39343. });
  39344. StandardMaterial.prototype.getClassName = function () {
  39345. return "StandardMaterial";
  39346. };
  39347. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39348. get: function () {
  39349. return this._useLogarithmicDepth;
  39350. },
  39351. set: function (value) {
  39352. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39353. this._markAllSubMeshesAsMiscDirty();
  39354. },
  39355. enumerable: true,
  39356. configurable: true
  39357. });
  39358. StandardMaterial.prototype.needAlphaBlending = function () {
  39359. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39360. };
  39361. StandardMaterial.prototype.needAlphaTesting = function () {
  39362. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39363. };
  39364. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39365. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39366. };
  39367. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39368. return this._diffuseTexture;
  39369. };
  39370. /**
  39371. * Child classes can use it to update shaders
  39372. */
  39373. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39374. if (useInstances === void 0) { useInstances = false; }
  39375. if (subMesh.effect && this.isFrozen) {
  39376. if (this._wasPreviouslyReady && subMesh.effect) {
  39377. return true;
  39378. }
  39379. }
  39380. if (!subMesh._materialDefines) {
  39381. subMesh._materialDefines = new StandardMaterialDefines();
  39382. }
  39383. var scene = this.getScene();
  39384. var defines = subMesh._materialDefines;
  39385. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39386. if (defines._renderId === scene.getRenderId()) {
  39387. return true;
  39388. }
  39389. }
  39390. var engine = scene.getEngine();
  39391. // Lights
  39392. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39393. // Textures
  39394. if (defines._areTexturesDirty) {
  39395. defines._needUVs = false;
  39396. defines.MAINUV1 = false;
  39397. defines.MAINUV2 = false;
  39398. if (scene.texturesEnabled) {
  39399. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39400. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39401. return false;
  39402. }
  39403. else {
  39404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39405. }
  39406. }
  39407. else {
  39408. defines.DIFFUSE = false;
  39409. }
  39410. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39411. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39412. return false;
  39413. }
  39414. else {
  39415. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39416. }
  39417. }
  39418. else {
  39419. defines.AMBIENT = false;
  39420. }
  39421. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39422. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39423. return false;
  39424. }
  39425. else {
  39426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39427. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39428. }
  39429. }
  39430. else {
  39431. defines.OPACITY = false;
  39432. }
  39433. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39434. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39435. return false;
  39436. }
  39437. else {
  39438. defines._needNormals = true;
  39439. defines.REFLECTION = true;
  39440. defines.ROUGHNESS = (this._roughness > 0);
  39441. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39442. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39443. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39444. switch (this._reflectionTexture.coordinatesMode) {
  39445. case BABYLON.Texture.CUBIC_MODE:
  39446. case BABYLON.Texture.INVCUBIC_MODE:
  39447. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39448. break;
  39449. case BABYLON.Texture.EXPLICIT_MODE:
  39450. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39451. break;
  39452. case BABYLON.Texture.PLANAR_MODE:
  39453. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39454. break;
  39455. case BABYLON.Texture.PROJECTION_MODE:
  39456. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39457. break;
  39458. case BABYLON.Texture.SKYBOX_MODE:
  39459. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39460. break;
  39461. case BABYLON.Texture.SPHERICAL_MODE:
  39462. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39463. break;
  39464. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39465. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39466. break;
  39467. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39468. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39469. break;
  39470. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39471. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39472. break;
  39473. }
  39474. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39475. }
  39476. }
  39477. else {
  39478. defines.REFLECTION = false;
  39479. }
  39480. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39481. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39482. return false;
  39483. }
  39484. else {
  39485. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39486. }
  39487. }
  39488. else {
  39489. defines.EMISSIVE = false;
  39490. }
  39491. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39492. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39493. return false;
  39494. }
  39495. else {
  39496. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39497. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39498. }
  39499. }
  39500. else {
  39501. defines.LIGHTMAP = false;
  39502. }
  39503. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39504. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39505. return false;
  39506. }
  39507. else {
  39508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39509. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39510. }
  39511. }
  39512. else {
  39513. defines.SPECULAR = false;
  39514. }
  39515. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39516. // Bump texure can not be not blocking.
  39517. if (!this._bumpTexture.isReady()) {
  39518. return false;
  39519. }
  39520. else {
  39521. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39522. defines.PARALLAX = this._useParallax;
  39523. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39524. }
  39525. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39526. }
  39527. else {
  39528. defines.BUMP = false;
  39529. }
  39530. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39531. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39532. return false;
  39533. }
  39534. else {
  39535. defines._needUVs = true;
  39536. defines.REFRACTION = true;
  39537. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39538. }
  39539. }
  39540. else {
  39541. defines.REFRACTION = false;
  39542. }
  39543. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39544. }
  39545. else {
  39546. defines.DIFFUSE = false;
  39547. defines.AMBIENT = false;
  39548. defines.OPACITY = false;
  39549. defines.REFLECTION = false;
  39550. defines.EMISSIVE = false;
  39551. defines.LIGHTMAP = false;
  39552. defines.BUMP = false;
  39553. defines.REFRACTION = false;
  39554. }
  39555. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39556. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39557. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39558. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39559. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39560. }
  39561. if (defines._areImageProcessingDirty) {
  39562. if (!this._imageProcessingConfiguration.isReady()) {
  39563. return false;
  39564. }
  39565. this._imageProcessingConfiguration.prepareDefines(defines);
  39566. }
  39567. if (defines._areFresnelDirty) {
  39568. if (StandardMaterial.FresnelEnabled) {
  39569. // Fresnel
  39570. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39571. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39572. this._reflectionFresnelParameters) {
  39573. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39574. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39575. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39576. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39577. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39578. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39579. defines._needNormals = true;
  39580. defines.FRESNEL = true;
  39581. }
  39582. }
  39583. else {
  39584. defines.FRESNEL = false;
  39585. }
  39586. }
  39587. // Misc.
  39588. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39589. // Attribs
  39590. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39591. // Values that need to be evaluated on every frame
  39592. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39593. // Get correct effect
  39594. if (defines.isDirty) {
  39595. defines.markAsProcessed();
  39596. scene.resetCachedMaterial();
  39597. // Fallbacks
  39598. var fallbacks = new BABYLON.EffectFallbacks();
  39599. if (defines.REFLECTION) {
  39600. fallbacks.addFallback(0, "REFLECTION");
  39601. }
  39602. if (defines.SPECULAR) {
  39603. fallbacks.addFallback(0, "SPECULAR");
  39604. }
  39605. if (defines.BUMP) {
  39606. fallbacks.addFallback(0, "BUMP");
  39607. }
  39608. if (defines.PARALLAX) {
  39609. fallbacks.addFallback(1, "PARALLAX");
  39610. }
  39611. if (defines.PARALLAXOCCLUSION) {
  39612. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39613. }
  39614. if (defines.SPECULAROVERALPHA) {
  39615. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39616. }
  39617. if (defines.FOG) {
  39618. fallbacks.addFallback(1, "FOG");
  39619. }
  39620. if (defines.POINTSIZE) {
  39621. fallbacks.addFallback(0, "POINTSIZE");
  39622. }
  39623. if (defines.LOGARITHMICDEPTH) {
  39624. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39625. }
  39626. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39627. if (defines.SPECULARTERM) {
  39628. fallbacks.addFallback(0, "SPECULARTERM");
  39629. }
  39630. if (defines.DIFFUSEFRESNEL) {
  39631. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39632. }
  39633. if (defines.OPACITYFRESNEL) {
  39634. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39635. }
  39636. if (defines.REFLECTIONFRESNEL) {
  39637. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39638. }
  39639. if (defines.EMISSIVEFRESNEL) {
  39640. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39641. }
  39642. if (defines.FRESNEL) {
  39643. fallbacks.addFallback(4, "FRESNEL");
  39644. }
  39645. //Attributes
  39646. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39647. if (defines.NORMAL) {
  39648. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39649. }
  39650. if (defines.UV1) {
  39651. attribs.push(BABYLON.VertexBuffer.UVKind);
  39652. }
  39653. if (defines.UV2) {
  39654. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39655. }
  39656. if (defines.VERTEXCOLOR) {
  39657. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39658. }
  39659. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39660. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39661. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39662. var shaderName = "default";
  39663. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39664. "vFogInfos", "vFogColor", "pointSize",
  39665. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39666. "mBones",
  39667. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39668. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39669. "vReflectionPosition", "vReflectionSize",
  39670. "logarithmicDepthConstant", "vTangentSpaceParams"
  39671. ];
  39672. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39673. var uniformBuffers = ["Material", "Scene"];
  39674. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39675. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39676. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39677. uniformsNames: uniforms,
  39678. uniformBuffersNames: uniformBuffers,
  39679. samplers: samplers,
  39680. defines: defines,
  39681. maxSimultaneousLights: this._maxSimultaneousLights
  39682. });
  39683. if (this.customShaderNameResolve) {
  39684. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39685. }
  39686. var join = defines.toString();
  39687. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39688. attributes: attribs,
  39689. uniformsNames: uniforms,
  39690. uniformBuffersNames: uniformBuffers,
  39691. samplers: samplers,
  39692. defines: join,
  39693. fallbacks: fallbacks,
  39694. onCompiled: this.onCompiled,
  39695. onError: this.onError,
  39696. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39697. }, engine), defines);
  39698. this.buildUniformLayout();
  39699. }
  39700. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39701. return false;
  39702. }
  39703. defines._renderId = scene.getRenderId();
  39704. this._wasPreviouslyReady = true;
  39705. return true;
  39706. };
  39707. StandardMaterial.prototype.buildUniformLayout = function () {
  39708. // Order is important !
  39709. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39710. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39711. this._uniformBuffer.addUniform("opacityParts", 4);
  39712. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39713. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39714. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39715. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39716. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39717. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39718. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39719. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39720. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39721. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39722. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39723. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39724. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39725. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39726. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39727. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39728. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39729. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39730. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39731. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39732. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39733. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39734. this._uniformBuffer.addUniform("specularMatrix", 16);
  39735. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39736. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39737. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39738. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39739. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39740. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39741. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39742. this._uniformBuffer.addUniform("pointSize", 1);
  39743. this._uniformBuffer.create();
  39744. };
  39745. StandardMaterial.prototype.unbind = function () {
  39746. if (this._activeEffect) {
  39747. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39748. this._activeEffect.setTexture("reflection2DSampler", null);
  39749. }
  39750. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39751. this._activeEffect.setTexture("refraction2DSampler", null);
  39752. }
  39753. }
  39754. _super.prototype.unbind.call(this);
  39755. };
  39756. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39757. var scene = this.getScene();
  39758. var defines = subMesh._materialDefines;
  39759. if (!defines) {
  39760. return;
  39761. }
  39762. var effect = subMesh.effect;
  39763. if (!effect) {
  39764. return;
  39765. }
  39766. this._activeEffect = effect;
  39767. // Matrices
  39768. this.bindOnlyWorldMatrix(world);
  39769. // Normal Matrix
  39770. if (defines.OBJECTSPACE_NORMALMAP) {
  39771. world.toNormalMatrix(this._normalMatrix);
  39772. this.bindOnlyNormalMatrix(this._normalMatrix);
  39773. }
  39774. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39775. // Bones
  39776. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39777. if (mustRebind) {
  39778. this._uniformBuffer.bindToEffect(effect, "Material");
  39779. this.bindViewProjection(effect);
  39780. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39781. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39782. // Fresnel
  39783. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39784. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39785. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39786. }
  39787. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39788. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39789. }
  39790. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39791. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39792. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39793. }
  39794. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39795. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39796. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39797. }
  39798. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39799. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39800. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39801. }
  39802. }
  39803. // Textures
  39804. if (scene.texturesEnabled) {
  39805. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39806. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39807. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39808. }
  39809. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39810. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39811. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39812. }
  39813. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39814. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39815. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39816. }
  39817. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39818. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39819. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39820. if (this._reflectionTexture.boundingBoxSize) {
  39821. var cubeTexture = this._reflectionTexture;
  39822. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39823. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39824. }
  39825. }
  39826. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39827. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39828. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39829. }
  39830. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39831. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39832. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39833. }
  39834. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39835. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39836. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39837. }
  39838. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39839. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39840. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39841. if (scene._mirroredCameraPosition) {
  39842. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39843. }
  39844. else {
  39845. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39846. }
  39847. }
  39848. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39849. var depth = 1.0;
  39850. if (!this._refractionTexture.isCube) {
  39851. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39852. if (this._refractionTexture.depth) {
  39853. depth = this._refractionTexture.depth;
  39854. }
  39855. }
  39856. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39857. }
  39858. }
  39859. // Point size
  39860. if (this.pointsCloud) {
  39861. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39862. }
  39863. if (defines.SPECULARTERM) {
  39864. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39865. }
  39866. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39867. // Diffuse
  39868. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39869. }
  39870. // Textures
  39871. if (scene.texturesEnabled) {
  39872. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39873. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39874. }
  39875. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39876. effect.setTexture("ambientSampler", this._ambientTexture);
  39877. }
  39878. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39879. effect.setTexture("opacitySampler", this._opacityTexture);
  39880. }
  39881. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39882. if (this._reflectionTexture.isCube) {
  39883. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39884. }
  39885. else {
  39886. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39887. }
  39888. }
  39889. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39890. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39891. }
  39892. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39893. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39894. }
  39895. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39896. effect.setTexture("specularSampler", this._specularTexture);
  39897. }
  39898. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39899. effect.setTexture("bumpSampler", this._bumpTexture);
  39900. }
  39901. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39902. var depth = 1.0;
  39903. if (this._refractionTexture.isCube) {
  39904. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39905. }
  39906. else {
  39907. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39908. }
  39909. }
  39910. }
  39911. // Clip plane
  39912. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39913. // Colors
  39914. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39915. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39916. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39917. }
  39918. if (mustRebind || !this.isFrozen) {
  39919. // Lights
  39920. if (scene.lightsEnabled && !this._disableLighting) {
  39921. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39922. }
  39923. // View
  39924. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39925. this.bindView(effect);
  39926. }
  39927. // Fog
  39928. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39929. // Morph targets
  39930. if (defines.NUM_MORPH_INFLUENCERS) {
  39931. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39932. }
  39933. // Log. depth
  39934. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39935. // image processing
  39936. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39937. this._imageProcessingConfiguration.bind(this._activeEffect);
  39938. }
  39939. }
  39940. this._uniformBuffer.update();
  39941. this._afterBind(mesh, this._activeEffect);
  39942. };
  39943. StandardMaterial.prototype.getAnimatables = function () {
  39944. var results = [];
  39945. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39946. results.push(this._diffuseTexture);
  39947. }
  39948. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39949. results.push(this._ambientTexture);
  39950. }
  39951. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39952. results.push(this._opacityTexture);
  39953. }
  39954. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39955. results.push(this._reflectionTexture);
  39956. }
  39957. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39958. results.push(this._emissiveTexture);
  39959. }
  39960. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39961. results.push(this._specularTexture);
  39962. }
  39963. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39964. results.push(this._bumpTexture);
  39965. }
  39966. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39967. results.push(this._lightmapTexture);
  39968. }
  39969. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39970. results.push(this._refractionTexture);
  39971. }
  39972. return results;
  39973. };
  39974. StandardMaterial.prototype.getActiveTextures = function () {
  39975. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39976. if (this._diffuseTexture) {
  39977. activeTextures.push(this._diffuseTexture);
  39978. }
  39979. if (this._ambientTexture) {
  39980. activeTextures.push(this._ambientTexture);
  39981. }
  39982. if (this._opacityTexture) {
  39983. activeTextures.push(this._opacityTexture);
  39984. }
  39985. if (this._reflectionTexture) {
  39986. activeTextures.push(this._reflectionTexture);
  39987. }
  39988. if (this._emissiveTexture) {
  39989. activeTextures.push(this._emissiveTexture);
  39990. }
  39991. if (this._specularTexture) {
  39992. activeTextures.push(this._specularTexture);
  39993. }
  39994. if (this._bumpTexture) {
  39995. activeTextures.push(this._bumpTexture);
  39996. }
  39997. if (this._lightmapTexture) {
  39998. activeTextures.push(this._lightmapTexture);
  39999. }
  40000. if (this._refractionTexture) {
  40001. activeTextures.push(this._refractionTexture);
  40002. }
  40003. return activeTextures;
  40004. };
  40005. StandardMaterial.prototype.hasTexture = function (texture) {
  40006. if (_super.prototype.hasTexture.call(this, texture)) {
  40007. return true;
  40008. }
  40009. if (this._diffuseTexture === texture) {
  40010. return true;
  40011. }
  40012. if (this._ambientTexture === texture) {
  40013. return true;
  40014. }
  40015. if (this._opacityTexture === texture) {
  40016. return true;
  40017. }
  40018. if (this._reflectionTexture === texture) {
  40019. return true;
  40020. }
  40021. if (this._emissiveTexture === texture) {
  40022. return true;
  40023. }
  40024. if (this._specularTexture === texture) {
  40025. return true;
  40026. }
  40027. if (this._bumpTexture === texture) {
  40028. return true;
  40029. }
  40030. if (this._lightmapTexture === texture) {
  40031. return true;
  40032. }
  40033. if (this._refractionTexture === texture) {
  40034. return true;
  40035. }
  40036. return false;
  40037. };
  40038. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40039. if (forceDisposeTextures) {
  40040. if (this._diffuseTexture) {
  40041. this._diffuseTexture.dispose();
  40042. }
  40043. if (this._ambientTexture) {
  40044. this._ambientTexture.dispose();
  40045. }
  40046. if (this._opacityTexture) {
  40047. this._opacityTexture.dispose();
  40048. }
  40049. if (this._reflectionTexture) {
  40050. this._reflectionTexture.dispose();
  40051. }
  40052. if (this._emissiveTexture) {
  40053. this._emissiveTexture.dispose();
  40054. }
  40055. if (this._specularTexture) {
  40056. this._specularTexture.dispose();
  40057. }
  40058. if (this._bumpTexture) {
  40059. this._bumpTexture.dispose();
  40060. }
  40061. if (this._lightmapTexture) {
  40062. this._lightmapTexture.dispose();
  40063. }
  40064. if (this._refractionTexture) {
  40065. this._refractionTexture.dispose();
  40066. }
  40067. }
  40068. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40069. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40070. }
  40071. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40072. };
  40073. StandardMaterial.prototype.clone = function (name) {
  40074. var _this = this;
  40075. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40076. result.name = name;
  40077. result.id = name;
  40078. return result;
  40079. };
  40080. StandardMaterial.prototype.serialize = function () {
  40081. return BABYLON.SerializationHelper.Serialize(this);
  40082. };
  40083. // Statics
  40084. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40085. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40086. };
  40087. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40088. get: function () {
  40089. return StandardMaterial._DiffuseTextureEnabled;
  40090. },
  40091. set: function (value) {
  40092. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40093. return;
  40094. }
  40095. StandardMaterial._DiffuseTextureEnabled = value;
  40096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40097. },
  40098. enumerable: true,
  40099. configurable: true
  40100. });
  40101. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40102. get: function () {
  40103. return StandardMaterial._AmbientTextureEnabled;
  40104. },
  40105. set: function (value) {
  40106. if (StandardMaterial._AmbientTextureEnabled === value) {
  40107. return;
  40108. }
  40109. StandardMaterial._AmbientTextureEnabled = value;
  40110. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40111. },
  40112. enumerable: true,
  40113. configurable: true
  40114. });
  40115. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40116. get: function () {
  40117. return StandardMaterial._OpacityTextureEnabled;
  40118. },
  40119. set: function (value) {
  40120. if (StandardMaterial._OpacityTextureEnabled === value) {
  40121. return;
  40122. }
  40123. StandardMaterial._OpacityTextureEnabled = value;
  40124. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40125. },
  40126. enumerable: true,
  40127. configurable: true
  40128. });
  40129. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40130. get: function () {
  40131. return StandardMaterial._ReflectionTextureEnabled;
  40132. },
  40133. set: function (value) {
  40134. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40135. return;
  40136. }
  40137. StandardMaterial._ReflectionTextureEnabled = value;
  40138. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40144. get: function () {
  40145. return StandardMaterial._EmissiveTextureEnabled;
  40146. },
  40147. set: function (value) {
  40148. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40149. return;
  40150. }
  40151. StandardMaterial._EmissiveTextureEnabled = value;
  40152. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40158. get: function () {
  40159. return StandardMaterial._SpecularTextureEnabled;
  40160. },
  40161. set: function (value) {
  40162. if (StandardMaterial._SpecularTextureEnabled === value) {
  40163. return;
  40164. }
  40165. StandardMaterial._SpecularTextureEnabled = value;
  40166. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40167. },
  40168. enumerable: true,
  40169. configurable: true
  40170. });
  40171. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40172. get: function () {
  40173. return StandardMaterial._BumpTextureEnabled;
  40174. },
  40175. set: function (value) {
  40176. if (StandardMaterial._BumpTextureEnabled === value) {
  40177. return;
  40178. }
  40179. StandardMaterial._BumpTextureEnabled = value;
  40180. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40181. },
  40182. enumerable: true,
  40183. configurable: true
  40184. });
  40185. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40186. get: function () {
  40187. return StandardMaterial._LightmapTextureEnabled;
  40188. },
  40189. set: function (value) {
  40190. if (StandardMaterial._LightmapTextureEnabled === value) {
  40191. return;
  40192. }
  40193. StandardMaterial._LightmapTextureEnabled = value;
  40194. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40195. },
  40196. enumerable: true,
  40197. configurable: true
  40198. });
  40199. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40200. get: function () {
  40201. return StandardMaterial._RefractionTextureEnabled;
  40202. },
  40203. set: function (value) {
  40204. if (StandardMaterial._RefractionTextureEnabled === value) {
  40205. return;
  40206. }
  40207. StandardMaterial._RefractionTextureEnabled = value;
  40208. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40209. },
  40210. enumerable: true,
  40211. configurable: true
  40212. });
  40213. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40214. get: function () {
  40215. return StandardMaterial._ColorGradingTextureEnabled;
  40216. },
  40217. set: function (value) {
  40218. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40219. return;
  40220. }
  40221. StandardMaterial._ColorGradingTextureEnabled = value;
  40222. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40223. },
  40224. enumerable: true,
  40225. configurable: true
  40226. });
  40227. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40228. get: function () {
  40229. return StandardMaterial._FresnelEnabled;
  40230. },
  40231. set: function (value) {
  40232. if (StandardMaterial._FresnelEnabled === value) {
  40233. return;
  40234. }
  40235. StandardMaterial._FresnelEnabled = value;
  40236. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40237. },
  40238. enumerable: true,
  40239. configurable: true
  40240. });
  40241. // Flags used to enable or disable a type of texture for all Standard Materials
  40242. StandardMaterial._DiffuseTextureEnabled = true;
  40243. StandardMaterial._AmbientTextureEnabled = true;
  40244. StandardMaterial._OpacityTextureEnabled = true;
  40245. StandardMaterial._ReflectionTextureEnabled = true;
  40246. StandardMaterial._EmissiveTextureEnabled = true;
  40247. StandardMaterial._SpecularTextureEnabled = true;
  40248. StandardMaterial._BumpTextureEnabled = true;
  40249. StandardMaterial._LightmapTextureEnabled = true;
  40250. StandardMaterial._RefractionTextureEnabled = true;
  40251. StandardMaterial._ColorGradingTextureEnabled = true;
  40252. StandardMaterial._FresnelEnabled = true;
  40253. __decorate([
  40254. BABYLON.serializeAsTexture("diffuseTexture")
  40255. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40256. __decorate([
  40257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40258. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40259. __decorate([
  40260. BABYLON.serializeAsTexture("ambientTexture")
  40261. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40262. __decorate([
  40263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40264. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40265. __decorate([
  40266. BABYLON.serializeAsTexture("opacityTexture")
  40267. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40268. __decorate([
  40269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40270. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40271. __decorate([
  40272. BABYLON.serializeAsTexture("reflectionTexture")
  40273. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40274. __decorate([
  40275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40276. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40277. __decorate([
  40278. BABYLON.serializeAsTexture("emissiveTexture")
  40279. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40280. __decorate([
  40281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40282. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40283. __decorate([
  40284. BABYLON.serializeAsTexture("specularTexture")
  40285. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40286. __decorate([
  40287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40288. ], StandardMaterial.prototype, "specularTexture", void 0);
  40289. __decorate([
  40290. BABYLON.serializeAsTexture("bumpTexture")
  40291. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40292. __decorate([
  40293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40294. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40295. __decorate([
  40296. BABYLON.serializeAsTexture("lightmapTexture")
  40297. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40298. __decorate([
  40299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40300. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40301. __decorate([
  40302. BABYLON.serializeAsTexture("refractionTexture")
  40303. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40304. __decorate([
  40305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40306. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40307. __decorate([
  40308. BABYLON.serializeAsColor3("ambient")
  40309. ], StandardMaterial.prototype, "ambientColor", void 0);
  40310. __decorate([
  40311. BABYLON.serializeAsColor3("diffuse")
  40312. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40313. __decorate([
  40314. BABYLON.serializeAsColor3("specular")
  40315. ], StandardMaterial.prototype, "specularColor", void 0);
  40316. __decorate([
  40317. BABYLON.serializeAsColor3("emissive")
  40318. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40319. __decorate([
  40320. BABYLON.serialize()
  40321. ], StandardMaterial.prototype, "specularPower", void 0);
  40322. __decorate([
  40323. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40324. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40325. __decorate([
  40326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40327. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40328. __decorate([
  40329. BABYLON.serialize("useEmissiveAsIllumination")
  40330. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40331. __decorate([
  40332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40333. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40334. __decorate([
  40335. BABYLON.serialize("linkEmissiveWithDiffuse")
  40336. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40337. __decorate([
  40338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40339. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40340. __decorate([
  40341. BABYLON.serialize("useSpecularOverAlpha")
  40342. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40343. __decorate([
  40344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40345. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40346. __decorate([
  40347. BABYLON.serialize("useReflectionOverAlpha")
  40348. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40349. __decorate([
  40350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40351. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40352. __decorate([
  40353. BABYLON.serialize("disableLighting")
  40354. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40355. __decorate([
  40356. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40357. ], StandardMaterial.prototype, "disableLighting", void 0);
  40358. __decorate([
  40359. BABYLON.serialize("useObjectSpaceNormalMap")
  40360. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40361. __decorate([
  40362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40363. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40364. __decorate([
  40365. BABYLON.serialize("useParallax")
  40366. ], StandardMaterial.prototype, "_useParallax", void 0);
  40367. __decorate([
  40368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40369. ], StandardMaterial.prototype, "useParallax", void 0);
  40370. __decorate([
  40371. BABYLON.serialize("useParallaxOcclusion")
  40372. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40373. __decorate([
  40374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40375. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40376. __decorate([
  40377. BABYLON.serialize()
  40378. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40379. __decorate([
  40380. BABYLON.serialize("roughness")
  40381. ], StandardMaterial.prototype, "_roughness", void 0);
  40382. __decorate([
  40383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40384. ], StandardMaterial.prototype, "roughness", void 0);
  40385. __decorate([
  40386. BABYLON.serialize()
  40387. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40388. __decorate([
  40389. BABYLON.serialize()
  40390. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40391. __decorate([
  40392. BABYLON.serialize("useLightmapAsShadowmap")
  40393. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40394. __decorate([
  40395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40396. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40397. __decorate([
  40398. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40399. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40400. __decorate([
  40401. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40402. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40403. __decorate([
  40404. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40405. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40406. __decorate([
  40407. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40408. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40409. __decorate([
  40410. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40411. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40412. __decorate([
  40413. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40414. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40415. __decorate([
  40416. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40417. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40418. __decorate([
  40419. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40420. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40421. __decorate([
  40422. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40423. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40424. __decorate([
  40425. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40426. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40427. __decorate([
  40428. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40429. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40430. __decorate([
  40431. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40432. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40433. __decorate([
  40434. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40435. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40436. __decorate([
  40437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40438. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40439. __decorate([
  40440. BABYLON.serialize("maxSimultaneousLights")
  40441. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40442. __decorate([
  40443. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40444. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40445. __decorate([
  40446. BABYLON.serialize("invertNormalMapX")
  40447. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40448. __decorate([
  40449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40450. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40451. __decorate([
  40452. BABYLON.serialize("invertNormalMapY")
  40453. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40454. __decorate([
  40455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40456. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40457. __decorate([
  40458. BABYLON.serialize("twoSidedLighting")
  40459. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40460. __decorate([
  40461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40462. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40463. __decorate([
  40464. BABYLON.serialize()
  40465. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40466. return StandardMaterial;
  40467. }(BABYLON.PushMaterial));
  40468. BABYLON.StandardMaterial = StandardMaterial;
  40469. })(BABYLON || (BABYLON = {}));
  40470. //# sourceMappingURL=babylon.standardMaterial.js.map
  40471. var BABYLON;
  40472. (function (BABYLON) {
  40473. /**
  40474. * Manages the defines for the PBR Material.
  40475. */
  40476. var PBRMaterialDefines = /** @class */ (function (_super) {
  40477. __extends(PBRMaterialDefines, _super);
  40478. /**
  40479. * Initializes the PBR Material defines.
  40480. */
  40481. function PBRMaterialDefines() {
  40482. var _this = _super.call(this) || this;
  40483. _this.PBR = true;
  40484. _this.MAINUV1 = false;
  40485. _this.MAINUV2 = false;
  40486. _this.UV1 = false;
  40487. _this.UV2 = false;
  40488. _this.ALBEDO = false;
  40489. _this.ALBEDODIRECTUV = 0;
  40490. _this.VERTEXCOLOR = false;
  40491. _this.AMBIENT = false;
  40492. _this.AMBIENTDIRECTUV = 0;
  40493. _this.AMBIENTINGRAYSCALE = false;
  40494. _this.OPACITY = false;
  40495. _this.VERTEXALPHA = false;
  40496. _this.OPACITYDIRECTUV = 0;
  40497. _this.OPACITYRGB = false;
  40498. _this.ALPHATEST = false;
  40499. _this.DEPTHPREPASS = false;
  40500. _this.ALPHABLEND = false;
  40501. _this.ALPHAFROMALBEDO = false;
  40502. _this.ALPHATESTVALUE = 0.5;
  40503. _this.SPECULAROVERALPHA = false;
  40504. _this.RADIANCEOVERALPHA = false;
  40505. _this.ALPHAFRESNEL = false;
  40506. _this.LINEARALPHAFRESNEL = false;
  40507. _this.PREMULTIPLYALPHA = false;
  40508. _this.EMISSIVE = false;
  40509. _this.EMISSIVEDIRECTUV = 0;
  40510. _this.REFLECTIVITY = false;
  40511. _this.REFLECTIVITYDIRECTUV = 0;
  40512. _this.SPECULARTERM = false;
  40513. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40514. _this.MICROSURFACEAUTOMATIC = false;
  40515. _this.LODBASEDMICROSFURACE = false;
  40516. _this.MICROSURFACEMAP = false;
  40517. _this.MICROSURFACEMAPDIRECTUV = 0;
  40518. _this.METALLICWORKFLOW = false;
  40519. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40520. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40521. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40522. _this.AOSTOREINMETALMAPRED = false;
  40523. _this.ENVIRONMENTBRDF = false;
  40524. _this.NORMAL = false;
  40525. _this.TANGENT = false;
  40526. _this.BUMP = false;
  40527. _this.BUMPDIRECTUV = 0;
  40528. _this.OBJECTSPACE_NORMALMAP = false;
  40529. _this.PARALLAX = false;
  40530. _this.PARALLAXOCCLUSION = false;
  40531. _this.NORMALXYSCALE = true;
  40532. _this.LIGHTMAP = false;
  40533. _this.LIGHTMAPDIRECTUV = 0;
  40534. _this.USELIGHTMAPASSHADOWMAP = false;
  40535. _this.REFLECTION = false;
  40536. _this.REFLECTIONMAP_3D = false;
  40537. _this.REFLECTIONMAP_SPHERICAL = false;
  40538. _this.REFLECTIONMAP_PLANAR = false;
  40539. _this.REFLECTIONMAP_CUBIC = false;
  40540. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40541. _this.REFLECTIONMAP_PROJECTION = false;
  40542. _this.REFLECTIONMAP_SKYBOX = false;
  40543. _this.REFLECTIONMAP_EXPLICIT = false;
  40544. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40545. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40546. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40547. _this.INVERTCUBICMAP = false;
  40548. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40549. _this.USESPHERICALINVERTEX = false;
  40550. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40551. _this.LODINREFLECTIONALPHA = false;
  40552. _this.GAMMAREFLECTION = false;
  40553. _this.RADIANCEOCCLUSION = false;
  40554. _this.HORIZONOCCLUSION = false;
  40555. _this.REFRACTION = false;
  40556. _this.REFRACTIONMAP_3D = false;
  40557. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40558. _this.LODINREFRACTIONALPHA = false;
  40559. _this.GAMMAREFRACTION = false;
  40560. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40561. _this.INSTANCES = false;
  40562. _this.NUM_BONE_INFLUENCERS = 0;
  40563. _this.BonesPerMesh = 0;
  40564. _this.NONUNIFORMSCALING = false;
  40565. _this.MORPHTARGETS = false;
  40566. _this.MORPHTARGETS_NORMAL = false;
  40567. _this.MORPHTARGETS_TANGENT = false;
  40568. _this.NUM_MORPH_INFLUENCERS = 0;
  40569. _this.IMAGEPROCESSING = false;
  40570. _this.VIGNETTE = false;
  40571. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40572. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40573. _this.TONEMAPPING = false;
  40574. _this.CONTRAST = false;
  40575. _this.COLORCURVES = false;
  40576. _this.COLORGRADING = false;
  40577. _this.COLORGRADING3D = false;
  40578. _this.SAMPLER3DGREENDEPTH = false;
  40579. _this.SAMPLER3DBGRMAP = false;
  40580. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40581. _this.EXPOSURE = false;
  40582. _this.GRAIN = false;
  40583. _this.USEPHYSICALLIGHTFALLOFF = false;
  40584. _this.TWOSIDEDLIGHTING = false;
  40585. _this.SHADOWFLOAT = false;
  40586. _this.CLIPPLANE = false;
  40587. _this.POINTSIZE = false;
  40588. _this.FOG = false;
  40589. _this.LOGARITHMICDEPTH = false;
  40590. _this.FORCENORMALFORWARD = false;
  40591. _this.rebuild();
  40592. return _this;
  40593. }
  40594. /**
  40595. * Resets the PBR Material defines.
  40596. */
  40597. PBRMaterialDefines.prototype.reset = function () {
  40598. _super.prototype.reset.call(this);
  40599. this.ALPHATESTVALUE = 0.5;
  40600. this.PBR = true;
  40601. };
  40602. return PBRMaterialDefines;
  40603. }(BABYLON.MaterialDefines));
  40604. /**
  40605. * The Physically based material base class of BJS.
  40606. *
  40607. * This offers the main features of a standard PBR material.
  40608. * For more information, please refer to the documentation :
  40609. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40610. */
  40611. var PBRBaseMaterial = /** @class */ (function (_super) {
  40612. __extends(PBRBaseMaterial, _super);
  40613. /**
  40614. * Instantiates a new PBRMaterial instance.
  40615. *
  40616. * @param name The material name
  40617. * @param scene The scene the material will be use in.
  40618. */
  40619. function PBRBaseMaterial(name, scene) {
  40620. var _this = _super.call(this, name, scene) || this;
  40621. /**
  40622. * Intensity of the direct lights e.g. the four lights available in your scene.
  40623. * This impacts both the direct diffuse and specular highlights.
  40624. */
  40625. _this._directIntensity = 1.0;
  40626. /**
  40627. * Intensity of the emissive part of the material.
  40628. * This helps controlling the emissive effect without modifying the emissive color.
  40629. */
  40630. _this._emissiveIntensity = 1.0;
  40631. /**
  40632. * Intensity of the environment e.g. how much the environment will light the object
  40633. * either through harmonics for rough material or through the refelction for shiny ones.
  40634. */
  40635. _this._environmentIntensity = 1.0;
  40636. /**
  40637. * This is a special control allowing the reduction of the specular highlights coming from the
  40638. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40639. */
  40640. _this._specularIntensity = 1.0;
  40641. /**
  40642. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40643. */
  40644. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40645. /**
  40646. * Debug Control allowing disabling the bump map on this material.
  40647. */
  40648. _this._disableBumpMap = false;
  40649. /**
  40650. * AKA Occlusion Texture Intensity in other nomenclature.
  40651. */
  40652. _this._ambientTextureStrength = 1.0;
  40653. /**
  40654. * The color of a material in ambient lighting.
  40655. */
  40656. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40657. /**
  40658. * AKA Diffuse Color in other nomenclature.
  40659. */
  40660. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40661. /**
  40662. * AKA Specular Color in other nomenclature.
  40663. */
  40664. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40665. /**
  40666. * The color applied when light is reflected from a material.
  40667. */
  40668. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40669. /**
  40670. * The color applied when light is emitted from a material.
  40671. */
  40672. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40673. /**
  40674. * AKA Glossiness in other nomenclature.
  40675. */
  40676. _this._microSurface = 0.9;
  40677. /**
  40678. * source material index of refraction (IOR)' / 'destination material IOR.
  40679. */
  40680. _this._indexOfRefraction = 0.66;
  40681. /**
  40682. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40683. */
  40684. _this._invertRefractionY = false;
  40685. /**
  40686. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40687. * Materials half opaque for instance using refraction could benefit from this control.
  40688. */
  40689. _this._linkRefractionWithTransparency = false;
  40690. /**
  40691. * Specifies that the material will use the light map as a show map.
  40692. */
  40693. _this._useLightmapAsShadowmap = false;
  40694. /**
  40695. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40696. * makes the reflect vector face the model (under horizon).
  40697. */
  40698. _this._useHorizonOcclusion = true;
  40699. /**
  40700. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40701. * too much the area relying on ambient texture to define their ambient occlusion.
  40702. */
  40703. _this._useRadianceOcclusion = true;
  40704. /**
  40705. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40706. */
  40707. _this._useAlphaFromAlbedoTexture = false;
  40708. /**
  40709. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40710. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40711. */
  40712. _this._useSpecularOverAlpha = true;
  40713. /**
  40714. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40715. */
  40716. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40717. /**
  40718. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40719. */
  40720. _this._useRoughnessFromMetallicTextureAlpha = true;
  40721. /**
  40722. * Specifies if the metallic texture contains the roughness information in its green channel.
  40723. */
  40724. _this._useRoughnessFromMetallicTextureGreen = false;
  40725. /**
  40726. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40727. */
  40728. _this._useMetallnessFromMetallicTextureBlue = false;
  40729. /**
  40730. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40731. */
  40732. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40733. /**
  40734. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40735. */
  40736. _this._useAmbientInGrayScale = false;
  40737. /**
  40738. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40739. * The material will try to infer what glossiness each pixel should be.
  40740. */
  40741. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40742. /**
  40743. * BJS is using an harcoded light falloff based on a manually sets up range.
  40744. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40745. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40746. */
  40747. _this._usePhysicalLightFalloff = true;
  40748. /**
  40749. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40750. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40751. */
  40752. _this._useRadianceOverAlpha = true;
  40753. /**
  40754. * Allows using an object space normal map (instead of tangent space).
  40755. */
  40756. _this._useObjectSpaceNormalMap = false;
  40757. /**
  40758. * Allows using the bump map in parallax mode.
  40759. */
  40760. _this._useParallax = false;
  40761. /**
  40762. * Allows using the bump map in parallax occlusion mode.
  40763. */
  40764. _this._useParallaxOcclusion = false;
  40765. /**
  40766. * Controls the scale bias of the parallax mode.
  40767. */
  40768. _this._parallaxScaleBias = 0.05;
  40769. /**
  40770. * If sets to true, disables all the lights affecting the material.
  40771. */
  40772. _this._disableLighting = false;
  40773. /**
  40774. * Number of Simultaneous lights allowed on the material.
  40775. */
  40776. _this._maxSimultaneousLights = 4;
  40777. /**
  40778. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40779. */
  40780. _this._invertNormalMapX = false;
  40781. /**
  40782. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40783. */
  40784. _this._invertNormalMapY = false;
  40785. /**
  40786. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40787. */
  40788. _this._twoSidedLighting = false;
  40789. /**
  40790. * Defines the alpha limits in alpha test mode.
  40791. */
  40792. _this._alphaCutOff = 0.4;
  40793. /**
  40794. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40795. */
  40796. _this._forceAlphaTest = false;
  40797. /**
  40798. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40799. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40800. */
  40801. _this._useAlphaFresnel = false;
  40802. /**
  40803. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40804. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40805. */
  40806. _this._useLinearAlphaFresnel = false;
  40807. /**
  40808. * The transparency mode of the material.
  40809. */
  40810. _this._transparencyMode = null;
  40811. /**
  40812. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40813. * from cos thetav and roughness:
  40814. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40815. */
  40816. _this._environmentBRDFTexture = null;
  40817. /**
  40818. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40819. */
  40820. _this._forceIrradianceInFragment = false;
  40821. /**
  40822. * Force normal to face away from face.
  40823. */
  40824. _this._forceNormalForward = false;
  40825. /**
  40826. * Stores the available render targets.
  40827. */
  40828. _this._renderTargets = new BABYLON.SmartArray(16);
  40829. /**
  40830. * Sets the global ambient color for the material used in lighting calculations.
  40831. */
  40832. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40833. // Setup the default processing configuration to the scene.
  40834. _this._attachImageProcessingConfiguration(null);
  40835. _this.getRenderTargetTextures = function () {
  40836. _this._renderTargets.reset();
  40837. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40838. _this._renderTargets.push(_this._reflectionTexture);
  40839. }
  40840. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40841. _this._renderTargets.push(_this._refractionTexture);
  40842. }
  40843. return _this._renderTargets;
  40844. };
  40845. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40846. return _this;
  40847. }
  40848. /**
  40849. * Attaches a new image processing configuration to the PBR Material.
  40850. * @param configuration
  40851. */
  40852. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40853. var _this = this;
  40854. if (configuration === this._imageProcessingConfiguration) {
  40855. return;
  40856. }
  40857. // Detaches observer.
  40858. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40859. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40860. }
  40861. // Pick the scene configuration if needed.
  40862. if (!configuration) {
  40863. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40864. }
  40865. else {
  40866. this._imageProcessingConfiguration = configuration;
  40867. }
  40868. // Attaches observer.
  40869. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40870. _this._markAllSubMeshesAsImageProcessingDirty();
  40871. });
  40872. };
  40873. /**
  40874. * Gets the name of the material class.
  40875. */
  40876. PBRBaseMaterial.prototype.getClassName = function () {
  40877. return "PBRBaseMaterial";
  40878. };
  40879. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40880. /**
  40881. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40882. */
  40883. get: function () {
  40884. return this._useLogarithmicDepth;
  40885. },
  40886. /**
  40887. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40888. */
  40889. set: function (value) {
  40890. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40891. },
  40892. enumerable: true,
  40893. configurable: true
  40894. });
  40895. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40896. /**
  40897. * Gets the current transparency mode.
  40898. */
  40899. get: function () {
  40900. return this._transparencyMode;
  40901. },
  40902. /**
  40903. * Sets the transparency mode of the material.
  40904. */
  40905. set: function (value) {
  40906. if (this._transparencyMode === value) {
  40907. return;
  40908. }
  40909. this._transparencyMode = value;
  40910. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40911. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40917. /**
  40918. * Returns true if alpha blending should be disabled.
  40919. */
  40920. get: function () {
  40921. return (this._linkRefractionWithTransparency ||
  40922. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40923. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40924. },
  40925. enumerable: true,
  40926. configurable: true
  40927. });
  40928. /**
  40929. * Specifies whether or not this material should be rendered in alpha blend mode.
  40930. */
  40931. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40932. if (this._disableAlphaBlending) {
  40933. return false;
  40934. }
  40935. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40936. };
  40937. /**
  40938. * Specifies if the mesh will require alpha blending.
  40939. * @param mesh - BJS mesh.
  40940. */
  40941. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40942. if (this._disableAlphaBlending) {
  40943. return false;
  40944. }
  40945. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40946. };
  40947. /**
  40948. * Specifies whether or not this material should be rendered in alpha test mode.
  40949. */
  40950. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40951. if (this._forceAlphaTest) {
  40952. return true;
  40953. }
  40954. if (this._linkRefractionWithTransparency) {
  40955. return false;
  40956. }
  40957. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40958. };
  40959. /**
  40960. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40961. */
  40962. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40963. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40964. };
  40965. /**
  40966. * Gets the texture used for the alpha test.
  40967. */
  40968. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40969. return this._albedoTexture;
  40970. };
  40971. /**
  40972. * Specifies that the submesh is ready to be used.
  40973. * @param mesh - BJS mesh.
  40974. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40975. * @param useInstances - Specifies that instances should be used.
  40976. * @returns - boolean indicating that the submesh is ready or not.
  40977. */
  40978. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40979. if (subMesh.effect && this.isFrozen) {
  40980. if (this._wasPreviouslyReady) {
  40981. return true;
  40982. }
  40983. }
  40984. if (!subMesh._materialDefines) {
  40985. subMesh._materialDefines = new PBRMaterialDefines();
  40986. }
  40987. var defines = subMesh._materialDefines;
  40988. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40989. if (defines._renderId === this.getScene().getRenderId()) {
  40990. return true;
  40991. }
  40992. }
  40993. var scene = this.getScene();
  40994. var engine = scene.getEngine();
  40995. if (defines._areTexturesDirty) {
  40996. if (scene.texturesEnabled) {
  40997. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40998. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40999. return false;
  41000. }
  41001. }
  41002. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41003. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41004. return false;
  41005. }
  41006. }
  41007. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41008. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41009. return false;
  41010. }
  41011. }
  41012. var reflectionTexture = this._getReflectionTexture();
  41013. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41014. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41015. return false;
  41016. }
  41017. }
  41018. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41019. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41020. return false;
  41021. }
  41022. }
  41023. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41024. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41025. return false;
  41026. }
  41027. }
  41028. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41029. if (this._metallicTexture) {
  41030. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41031. return false;
  41032. }
  41033. }
  41034. else if (this._reflectivityTexture) {
  41035. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41036. return false;
  41037. }
  41038. }
  41039. if (this._microSurfaceTexture) {
  41040. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41041. return false;
  41042. }
  41043. }
  41044. }
  41045. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41046. // Bump texture cannot be not blocking.
  41047. if (!this._bumpTexture.isReady()) {
  41048. return false;
  41049. }
  41050. }
  41051. var refractionTexture = this._getRefractionTexture();
  41052. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41053. if (!refractionTexture.isReadyOrNotBlocking()) {
  41054. return false;
  41055. }
  41056. }
  41057. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41058. // This is blocking.
  41059. if (!this._environmentBRDFTexture.isReady()) {
  41060. return false;
  41061. }
  41062. }
  41063. }
  41064. }
  41065. if (defines._areImageProcessingDirty) {
  41066. if (!this._imageProcessingConfiguration.isReady()) {
  41067. return false;
  41068. }
  41069. }
  41070. if (!engine.getCaps().standardDerivatives) {
  41071. var bufferMesh = null;
  41072. if (mesh.getClassName() === "InstancedMesh") {
  41073. bufferMesh = mesh.sourceMesh;
  41074. }
  41075. else if (mesh.getClassName() === "Mesh") {
  41076. bufferMesh = mesh;
  41077. }
  41078. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41079. bufferMesh.createNormals(true);
  41080. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41081. }
  41082. }
  41083. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41084. if (effect) {
  41085. scene.resetCachedMaterial();
  41086. subMesh.setEffect(effect, defines);
  41087. this.buildUniformLayout();
  41088. }
  41089. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41090. return false;
  41091. }
  41092. defines._renderId = scene.getRenderId();
  41093. this._wasPreviouslyReady = true;
  41094. return true;
  41095. };
  41096. /**
  41097. * Specifies if the material uses metallic roughness workflow.
  41098. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41099. */
  41100. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41101. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41102. return true;
  41103. }
  41104. return false;
  41105. };
  41106. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41107. if (onCompiled === void 0) { onCompiled = null; }
  41108. if (onError === void 0) { onError = null; }
  41109. if (useInstances === void 0) { useInstances = null; }
  41110. if (useClipPlane === void 0) { useClipPlane = null; }
  41111. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41112. if (!defines.isDirty) {
  41113. return null;
  41114. }
  41115. defines.markAsProcessed();
  41116. var scene = this.getScene();
  41117. var engine = scene.getEngine();
  41118. // Fallbacks
  41119. var fallbacks = new BABYLON.EffectFallbacks();
  41120. var fallbackRank = 0;
  41121. if (defines.USESPHERICALINVERTEX) {
  41122. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41123. }
  41124. if (defines.FOG) {
  41125. fallbacks.addFallback(fallbackRank, "FOG");
  41126. }
  41127. if (defines.POINTSIZE) {
  41128. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41129. }
  41130. if (defines.LOGARITHMICDEPTH) {
  41131. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41132. }
  41133. if (defines.PARALLAX) {
  41134. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41135. }
  41136. if (defines.PARALLAXOCCLUSION) {
  41137. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41138. }
  41139. if (defines.ENVIRONMENTBRDF) {
  41140. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41141. }
  41142. if (defines.TANGENT) {
  41143. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41144. }
  41145. if (defines.BUMP) {
  41146. fallbacks.addFallback(fallbackRank++, "BUMP");
  41147. }
  41148. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41149. if (defines.SPECULARTERM) {
  41150. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41151. }
  41152. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41153. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41154. }
  41155. if (defines.LIGHTMAP) {
  41156. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41157. }
  41158. if (defines.NORMAL) {
  41159. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41160. }
  41161. if (defines.AMBIENT) {
  41162. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41163. }
  41164. if (defines.EMISSIVE) {
  41165. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41166. }
  41167. if (defines.VERTEXCOLOR) {
  41168. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41169. }
  41170. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41171. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41172. }
  41173. if (defines.MORPHTARGETS) {
  41174. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41175. }
  41176. //Attributes
  41177. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41178. if (defines.NORMAL) {
  41179. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41180. }
  41181. if (defines.TANGENT) {
  41182. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41183. }
  41184. if (defines.UV1) {
  41185. attribs.push(BABYLON.VertexBuffer.UVKind);
  41186. }
  41187. if (defines.UV2) {
  41188. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41189. }
  41190. if (defines.VERTEXCOLOR) {
  41191. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41192. }
  41193. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41194. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41195. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41196. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41197. "vFogInfos", "vFogColor", "pointSize",
  41198. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41199. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41200. "mBones",
  41201. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41202. "vLightingIntensity",
  41203. "logarithmicDepthConstant",
  41204. "vSphericalX", "vSphericalY", "vSphericalZ",
  41205. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41206. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41207. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41208. "vTangentSpaceParams"
  41209. ];
  41210. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41211. "bumpSampler", "lightmapSampler", "opacitySampler",
  41212. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41213. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41214. "microSurfaceSampler", "environmentBrdfSampler"];
  41215. var uniformBuffers = ["Material", "Scene"];
  41216. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41217. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41218. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41219. uniformsNames: uniforms,
  41220. uniformBuffersNames: uniformBuffers,
  41221. samplers: samplers,
  41222. defines: defines,
  41223. maxSimultaneousLights: this._maxSimultaneousLights
  41224. });
  41225. var join = defines.toString();
  41226. return engine.createEffect("pbr", {
  41227. attributes: attribs,
  41228. uniformsNames: uniforms,
  41229. uniformBuffersNames: uniformBuffers,
  41230. samplers: samplers,
  41231. defines: join,
  41232. fallbacks: fallbacks,
  41233. onCompiled: onCompiled,
  41234. onError: onError,
  41235. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41236. }, engine);
  41237. };
  41238. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41239. if (useInstances === void 0) { useInstances = null; }
  41240. if (useClipPlane === void 0) { useClipPlane = null; }
  41241. var scene = this.getScene();
  41242. var engine = scene.getEngine();
  41243. // Lights
  41244. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41245. defines._needNormals = true;
  41246. // Textures
  41247. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41248. if (defines._areTexturesDirty) {
  41249. defines._needUVs = false;
  41250. if (scene.texturesEnabled) {
  41251. if (scene.getEngine().getCaps().textureLOD) {
  41252. defines.LODBASEDMICROSFURACE = true;
  41253. }
  41254. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41256. }
  41257. else {
  41258. defines.ALBEDO = false;
  41259. }
  41260. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41261. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41262. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41263. }
  41264. else {
  41265. defines.AMBIENT = false;
  41266. }
  41267. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41268. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41269. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41270. }
  41271. else {
  41272. defines.OPACITY = false;
  41273. }
  41274. var reflectionTexture = this._getReflectionTexture();
  41275. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41276. defines.REFLECTION = true;
  41277. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41278. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41279. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41280. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41281. defines.INVERTCUBICMAP = true;
  41282. }
  41283. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41284. switch (reflectionTexture.coordinatesMode) {
  41285. case BABYLON.Texture.CUBIC_MODE:
  41286. case BABYLON.Texture.INVCUBIC_MODE:
  41287. defines.REFLECTIONMAP_CUBIC = true;
  41288. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41289. break;
  41290. case BABYLON.Texture.EXPLICIT_MODE:
  41291. defines.REFLECTIONMAP_EXPLICIT = true;
  41292. break;
  41293. case BABYLON.Texture.PLANAR_MODE:
  41294. defines.REFLECTIONMAP_PLANAR = true;
  41295. break;
  41296. case BABYLON.Texture.PROJECTION_MODE:
  41297. defines.REFLECTIONMAP_PROJECTION = true;
  41298. break;
  41299. case BABYLON.Texture.SKYBOX_MODE:
  41300. defines.REFLECTIONMAP_SKYBOX = true;
  41301. break;
  41302. case BABYLON.Texture.SPHERICAL_MODE:
  41303. defines.REFLECTIONMAP_SPHERICAL = true;
  41304. break;
  41305. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41306. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41307. break;
  41308. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41309. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41310. break;
  41311. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41312. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41313. break;
  41314. }
  41315. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41316. if (reflectionTexture.sphericalPolynomial) {
  41317. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41318. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41319. defines.USESPHERICALINVERTEX = false;
  41320. }
  41321. else {
  41322. defines.USESPHERICALINVERTEX = true;
  41323. }
  41324. }
  41325. }
  41326. }
  41327. else {
  41328. defines.REFLECTION = false;
  41329. defines.REFLECTIONMAP_3D = false;
  41330. defines.REFLECTIONMAP_SPHERICAL = false;
  41331. defines.REFLECTIONMAP_PLANAR = false;
  41332. defines.REFLECTIONMAP_CUBIC = false;
  41333. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41334. defines.REFLECTIONMAP_PROJECTION = false;
  41335. defines.REFLECTIONMAP_SKYBOX = false;
  41336. defines.REFLECTIONMAP_EXPLICIT = false;
  41337. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41338. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41339. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41340. defines.INVERTCUBICMAP = false;
  41341. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41342. defines.USESPHERICALINVERTEX = false;
  41343. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41344. defines.LODINREFLECTIONALPHA = false;
  41345. defines.GAMMAREFLECTION = false;
  41346. }
  41347. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41349. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41350. }
  41351. else {
  41352. defines.LIGHTMAP = false;
  41353. }
  41354. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41356. }
  41357. else {
  41358. defines.EMISSIVE = false;
  41359. }
  41360. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41361. if (this._metallicTexture) {
  41362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41363. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41364. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41365. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41366. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41367. }
  41368. else if (this._reflectivityTexture) {
  41369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41370. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41371. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41372. }
  41373. else {
  41374. defines.REFLECTIVITY = false;
  41375. }
  41376. if (this._microSurfaceTexture) {
  41377. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41378. }
  41379. else {
  41380. defines.MICROSURFACEMAP = false;
  41381. }
  41382. }
  41383. else {
  41384. defines.REFLECTIVITY = false;
  41385. defines.MICROSURFACEMAP = false;
  41386. }
  41387. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41389. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41390. defines.PARALLAX = true;
  41391. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41392. }
  41393. else {
  41394. defines.PARALLAX = false;
  41395. }
  41396. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41397. }
  41398. else {
  41399. defines.BUMP = false;
  41400. }
  41401. var refractionTexture = this._getRefractionTexture();
  41402. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41403. defines.REFRACTION = true;
  41404. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41405. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41406. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41407. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41408. if (this._linkRefractionWithTransparency) {
  41409. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41410. }
  41411. }
  41412. else {
  41413. defines.REFRACTION = false;
  41414. }
  41415. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41416. defines.ENVIRONMENTBRDF = true;
  41417. }
  41418. else {
  41419. defines.ENVIRONMENTBRDF = false;
  41420. }
  41421. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41422. defines.ALPHAFROMALBEDO = true;
  41423. }
  41424. else {
  41425. defines.ALPHAFROMALBEDO = false;
  41426. }
  41427. }
  41428. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41429. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41430. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41431. if (!this.backFaceCulling && this._twoSidedLighting) {
  41432. defines.TWOSIDEDLIGHTING = true;
  41433. }
  41434. else {
  41435. defines.TWOSIDEDLIGHTING = false;
  41436. }
  41437. defines.ALPHATESTVALUE = this._alphaCutOff;
  41438. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41439. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41440. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41441. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41442. }
  41443. if (defines._areImageProcessingDirty) {
  41444. this._imageProcessingConfiguration.prepareDefines(defines);
  41445. }
  41446. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41447. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41448. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41449. // Misc.
  41450. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41451. // Values that need to be evaluated on every frame
  41452. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41453. // Attribs
  41454. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41455. };
  41456. /**
  41457. * Force shader compilation
  41458. */
  41459. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41460. var _this = this;
  41461. var localOptions = __assign({ clipPlane: false }, options);
  41462. var defines = new PBRMaterialDefines();
  41463. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41464. if (effect.isReady()) {
  41465. if (onCompiled) {
  41466. onCompiled(this);
  41467. }
  41468. }
  41469. else {
  41470. effect.onCompileObservable.add(function () {
  41471. if (onCompiled) {
  41472. onCompiled(_this);
  41473. }
  41474. });
  41475. }
  41476. };
  41477. /**
  41478. * Initializes the uniform buffer layout for the shader.
  41479. */
  41480. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41481. // Order is important !
  41482. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41483. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41484. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41485. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41486. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41487. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41488. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41489. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41490. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41491. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41492. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41493. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41494. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41495. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41496. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41497. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41498. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41499. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41500. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41501. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41502. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41503. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41504. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41505. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41506. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41507. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41508. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41509. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41510. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41511. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41512. this._uniformBuffer.addUniform("pointSize", 1);
  41513. this._uniformBuffer.create();
  41514. };
  41515. /**
  41516. * Unbinds the textures.
  41517. */
  41518. PBRBaseMaterial.prototype.unbind = function () {
  41519. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41520. this._uniformBuffer.setTexture("reflectionSampler", null);
  41521. }
  41522. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41523. this._uniformBuffer.setTexture("refractionSampler", null);
  41524. }
  41525. _super.prototype.unbind.call(this);
  41526. };
  41527. /**
  41528. * Binds the submesh data.
  41529. * @param world - The world matrix.
  41530. * @param mesh - The BJS mesh.
  41531. * @param subMesh - A submesh of the BJS mesh.
  41532. */
  41533. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41534. var scene = this.getScene();
  41535. var defines = subMesh._materialDefines;
  41536. if (!defines) {
  41537. return;
  41538. }
  41539. var effect = subMesh.effect;
  41540. if (!effect) {
  41541. return;
  41542. }
  41543. this._activeEffect = effect;
  41544. // Matrices
  41545. this.bindOnlyWorldMatrix(world);
  41546. // Normal Matrix
  41547. if (defines.OBJECTSPACE_NORMALMAP) {
  41548. world.toNormalMatrix(this._normalMatrix);
  41549. this.bindOnlyNormalMatrix(this._normalMatrix);
  41550. }
  41551. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41552. // Bones
  41553. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41554. var reflectionTexture = null;
  41555. if (mustRebind) {
  41556. this._uniformBuffer.bindToEffect(effect, "Material");
  41557. this.bindViewProjection(effect);
  41558. reflectionTexture = this._getReflectionTexture();
  41559. var refractionTexture = this._getRefractionTexture();
  41560. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41561. // Texture uniforms
  41562. if (scene.texturesEnabled) {
  41563. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41564. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41565. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41566. }
  41567. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41568. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41569. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41570. }
  41571. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41572. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41573. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41574. }
  41575. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41576. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41577. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41578. if (reflectionTexture.boundingBoxSize) {
  41579. var cubeTexture = reflectionTexture;
  41580. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41581. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41582. }
  41583. var polynomials = reflectionTexture.sphericalPolynomial;
  41584. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41585. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41586. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41587. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41588. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41589. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41590. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41591. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41592. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41593. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41594. }
  41595. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41596. }
  41597. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41598. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41599. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41600. }
  41601. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41602. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41603. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41604. }
  41605. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41606. if (this._metallicTexture) {
  41607. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41608. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41609. }
  41610. else if (this._reflectivityTexture) {
  41611. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41612. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41613. }
  41614. if (this._microSurfaceTexture) {
  41615. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41616. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41617. }
  41618. }
  41619. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41620. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41621. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41622. if (scene._mirroredCameraPosition) {
  41623. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41624. }
  41625. else {
  41626. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41627. }
  41628. }
  41629. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41630. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41631. var depth = 1.0;
  41632. if (!refractionTexture.isCube) {
  41633. if (refractionTexture.depth) {
  41634. depth = refractionTexture.depth;
  41635. }
  41636. }
  41637. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41638. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41639. }
  41640. }
  41641. // Point size
  41642. if (this.pointsCloud) {
  41643. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41644. }
  41645. // Colors
  41646. if (defines.METALLICWORKFLOW) {
  41647. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41648. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41649. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41650. }
  41651. else {
  41652. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41653. }
  41654. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41655. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41656. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41657. // Misc
  41658. this._lightingInfos.x = this._directIntensity;
  41659. this._lightingInfos.y = this._emissiveIntensity;
  41660. this._lightingInfos.z = this._environmentIntensity;
  41661. this._lightingInfos.w = this._specularIntensity;
  41662. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41663. }
  41664. // Textures
  41665. if (scene.texturesEnabled) {
  41666. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41667. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41668. }
  41669. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41670. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41671. }
  41672. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41673. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41674. }
  41675. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41676. if (defines.LODBASEDMICROSFURACE) {
  41677. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41678. }
  41679. else {
  41680. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41681. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41682. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41683. }
  41684. }
  41685. if (defines.ENVIRONMENTBRDF) {
  41686. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41687. }
  41688. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41689. if (defines.LODBASEDMICROSFURACE) {
  41690. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41691. }
  41692. else {
  41693. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41694. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41695. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41696. }
  41697. }
  41698. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41699. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41700. }
  41701. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41702. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41703. }
  41704. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41705. if (this._metallicTexture) {
  41706. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41707. }
  41708. else if (this._reflectivityTexture) {
  41709. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41710. }
  41711. if (this._microSurfaceTexture) {
  41712. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41713. }
  41714. }
  41715. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41716. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41717. }
  41718. }
  41719. // Clip plane
  41720. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41721. // Colors
  41722. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41723. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41724. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41725. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41726. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41727. }
  41728. if (mustRebind || !this.isFrozen) {
  41729. // Lights
  41730. if (scene.lightsEnabled && !this._disableLighting) {
  41731. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41732. }
  41733. // View
  41734. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41735. this.bindView(effect);
  41736. }
  41737. // Fog
  41738. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41739. // Morph targets
  41740. if (defines.NUM_MORPH_INFLUENCERS) {
  41741. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41742. }
  41743. // image processing
  41744. this._imageProcessingConfiguration.bind(this._activeEffect);
  41745. // Log. depth
  41746. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41747. }
  41748. this._uniformBuffer.update();
  41749. this._afterBind(mesh);
  41750. };
  41751. /**
  41752. * Returns the animatable textures.
  41753. * @returns - Array of animatable textures.
  41754. */
  41755. PBRBaseMaterial.prototype.getAnimatables = function () {
  41756. var results = [];
  41757. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41758. results.push(this._albedoTexture);
  41759. }
  41760. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41761. results.push(this._ambientTexture);
  41762. }
  41763. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41764. results.push(this._opacityTexture);
  41765. }
  41766. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41767. results.push(this._reflectionTexture);
  41768. }
  41769. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41770. results.push(this._emissiveTexture);
  41771. }
  41772. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41773. results.push(this._metallicTexture);
  41774. }
  41775. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41776. results.push(this._reflectivityTexture);
  41777. }
  41778. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41779. results.push(this._bumpTexture);
  41780. }
  41781. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41782. results.push(this._lightmapTexture);
  41783. }
  41784. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41785. results.push(this._refractionTexture);
  41786. }
  41787. return results;
  41788. };
  41789. /**
  41790. * Returns the texture used for reflections.
  41791. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41792. */
  41793. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41794. if (this._reflectionTexture) {
  41795. return this._reflectionTexture;
  41796. }
  41797. return this.getScene().environmentTexture;
  41798. };
  41799. /**
  41800. * Returns the texture used for refraction or null if none is used.
  41801. * @returns - Refection texture if present. If no refraction texture and refraction
  41802. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41803. */
  41804. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41805. if (this._refractionTexture) {
  41806. return this._refractionTexture;
  41807. }
  41808. if (this._linkRefractionWithTransparency) {
  41809. return this.getScene().environmentTexture;
  41810. }
  41811. return null;
  41812. };
  41813. /**
  41814. * Disposes the resources of the material.
  41815. * @param forceDisposeEffect - Forces the disposal of effects.
  41816. * @param forceDisposeTextures - Forces the disposal of all textures.
  41817. */
  41818. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41819. if (forceDisposeTextures) {
  41820. if (this._albedoTexture) {
  41821. this._albedoTexture.dispose();
  41822. }
  41823. if (this._ambientTexture) {
  41824. this._ambientTexture.dispose();
  41825. }
  41826. if (this._opacityTexture) {
  41827. this._opacityTexture.dispose();
  41828. }
  41829. if (this._reflectionTexture) {
  41830. this._reflectionTexture.dispose();
  41831. }
  41832. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41833. this._environmentBRDFTexture.dispose();
  41834. }
  41835. if (this._emissiveTexture) {
  41836. this._emissiveTexture.dispose();
  41837. }
  41838. if (this._metallicTexture) {
  41839. this._metallicTexture.dispose();
  41840. }
  41841. if (this._reflectivityTexture) {
  41842. this._reflectivityTexture.dispose();
  41843. }
  41844. if (this._bumpTexture) {
  41845. this._bumpTexture.dispose();
  41846. }
  41847. if (this._lightmapTexture) {
  41848. this._lightmapTexture.dispose();
  41849. }
  41850. if (this._refractionTexture) {
  41851. this._refractionTexture.dispose();
  41852. }
  41853. }
  41854. this._renderTargets.dispose();
  41855. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41856. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41857. }
  41858. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41859. };
  41860. /**
  41861. * Stores the reflectivity values based on metallic roughness workflow.
  41862. */
  41863. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41864. __decorate([
  41865. BABYLON.serializeAsImageProcessingConfiguration()
  41866. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41867. __decorate([
  41868. BABYLON.serialize()
  41869. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41870. __decorate([
  41871. BABYLON.serialize()
  41872. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41873. return PBRBaseMaterial;
  41874. }(BABYLON.PushMaterial));
  41875. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41876. })(BABYLON || (BABYLON = {}));
  41877. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41878. var BABYLON;
  41879. (function (BABYLON) {
  41880. /**
  41881. * The Physically based simple base material of BJS.
  41882. *
  41883. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41884. * It is used as the base class for both the specGloss and metalRough conventions.
  41885. */
  41886. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41887. __extends(PBRBaseSimpleMaterial, _super);
  41888. /**
  41889. * Instantiates a new PBRMaterial instance.
  41890. *
  41891. * @param name The material name
  41892. * @param scene The scene the material will be use in.
  41893. */
  41894. function PBRBaseSimpleMaterial(name, scene) {
  41895. var _this = _super.call(this, name, scene) || this;
  41896. /**
  41897. * Number of Simultaneous lights allowed on the material.
  41898. */
  41899. _this.maxSimultaneousLights = 4;
  41900. /**
  41901. * If sets to true, disables all the lights affecting the material.
  41902. */
  41903. _this.disableLighting = false;
  41904. /**
  41905. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41906. */
  41907. _this.invertNormalMapX = false;
  41908. /**
  41909. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41910. */
  41911. _this.invertNormalMapY = false;
  41912. /**
  41913. * Emissivie color used to self-illuminate the model.
  41914. */
  41915. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41916. /**
  41917. * Occlusion Channel Strenght.
  41918. */
  41919. _this.occlusionStrength = 1.0;
  41920. _this.useLightmapAsShadowmap = false;
  41921. _this._useAlphaFromAlbedoTexture = true;
  41922. _this._useAmbientInGrayScale = true;
  41923. return _this;
  41924. }
  41925. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41926. /**
  41927. * Gets the current double sided mode.
  41928. */
  41929. get: function () {
  41930. return this._twoSidedLighting;
  41931. },
  41932. /**
  41933. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41934. */
  41935. set: function (value) {
  41936. if (this._twoSidedLighting === value) {
  41937. return;
  41938. }
  41939. this._twoSidedLighting = value;
  41940. this.backFaceCulling = !value;
  41941. this._markAllSubMeshesAsTexturesDirty();
  41942. },
  41943. enumerable: true,
  41944. configurable: true
  41945. });
  41946. /**
  41947. * Return the active textures of the material.
  41948. */
  41949. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41950. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41951. if (this.environmentTexture) {
  41952. activeTextures.push(this.environmentTexture);
  41953. }
  41954. if (this.normalTexture) {
  41955. activeTextures.push(this.normalTexture);
  41956. }
  41957. if (this.emissiveTexture) {
  41958. activeTextures.push(this.emissiveTexture);
  41959. }
  41960. if (this.occlusionTexture) {
  41961. activeTextures.push(this.occlusionTexture);
  41962. }
  41963. if (this.lightmapTexture) {
  41964. activeTextures.push(this.lightmapTexture);
  41965. }
  41966. return activeTextures;
  41967. };
  41968. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41969. if (_super.prototype.hasTexture.call(this, texture)) {
  41970. return true;
  41971. }
  41972. if (this.lightmapTexture === texture) {
  41973. return true;
  41974. }
  41975. return false;
  41976. };
  41977. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41978. return "PBRBaseSimpleMaterial";
  41979. };
  41980. __decorate([
  41981. BABYLON.serialize(),
  41982. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41983. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41984. __decorate([
  41985. BABYLON.serialize(),
  41986. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41987. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41988. __decorate([
  41989. BABYLON.serializeAsTexture(),
  41990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41991. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41992. __decorate([
  41993. BABYLON.serialize(),
  41994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41995. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41996. __decorate([
  41997. BABYLON.serialize(),
  41998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41999. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42000. __decorate([
  42001. BABYLON.serializeAsTexture(),
  42002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42003. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42004. __decorate([
  42005. BABYLON.serializeAsColor3("emissive"),
  42006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42007. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42008. __decorate([
  42009. BABYLON.serializeAsTexture(),
  42010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42011. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42012. __decorate([
  42013. BABYLON.serialize(),
  42014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42015. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42016. __decorate([
  42017. BABYLON.serializeAsTexture(),
  42018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42019. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42020. __decorate([
  42021. BABYLON.serialize(),
  42022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42023. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42024. __decorate([
  42025. BABYLON.serialize()
  42026. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42027. __decorate([
  42028. BABYLON.serializeAsTexture(),
  42029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42030. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42031. __decorate([
  42032. BABYLON.serialize(),
  42033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42034. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42035. return PBRBaseSimpleMaterial;
  42036. }(BABYLON.PBRBaseMaterial));
  42037. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42038. })(BABYLON || (BABYLON = {}));
  42039. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42040. var BABYLON;
  42041. (function (BABYLON) {
  42042. /**
  42043. * The Physically based material of BJS.
  42044. *
  42045. * This offers the main features of a standard PBR material.
  42046. * For more information, please refer to the documentation :
  42047. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42048. */
  42049. var PBRMaterial = /** @class */ (function (_super) {
  42050. __extends(PBRMaterial, _super);
  42051. /**
  42052. * Instantiates a new PBRMaterial instance.
  42053. *
  42054. * @param name The material name
  42055. * @param scene The scene the material will be use in.
  42056. */
  42057. function PBRMaterial(name, scene) {
  42058. var _this = _super.call(this, name, scene) || this;
  42059. /**
  42060. * Intensity of the direct lights e.g. the four lights available in your scene.
  42061. * This impacts both the direct diffuse and specular highlights.
  42062. */
  42063. _this.directIntensity = 1.0;
  42064. /**
  42065. * Intensity of the emissive part of the material.
  42066. * This helps controlling the emissive effect without modifying the emissive color.
  42067. */
  42068. _this.emissiveIntensity = 1.0;
  42069. /**
  42070. * Intensity of the environment e.g. how much the environment will light the object
  42071. * either through harmonics for rough material or through the refelction for shiny ones.
  42072. */
  42073. _this.environmentIntensity = 1.0;
  42074. /**
  42075. * This is a special control allowing the reduction of the specular highlights coming from the
  42076. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42077. */
  42078. _this.specularIntensity = 1.0;
  42079. /**
  42080. * Debug Control allowing disabling the bump map on this material.
  42081. */
  42082. _this.disableBumpMap = false;
  42083. /**
  42084. * AKA Occlusion Texture Intensity in other nomenclature.
  42085. */
  42086. _this.ambientTextureStrength = 1.0;
  42087. /**
  42088. * The color of a material in ambient lighting.
  42089. */
  42090. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42091. /**
  42092. * AKA Diffuse Color in other nomenclature.
  42093. */
  42094. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42095. /**
  42096. * AKA Specular Color in other nomenclature.
  42097. */
  42098. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42099. /**
  42100. * The color reflected from the material.
  42101. */
  42102. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42103. /**
  42104. * The color emitted from the material.
  42105. */
  42106. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42107. /**
  42108. * AKA Glossiness in other nomenclature.
  42109. */
  42110. _this.microSurface = 1.0;
  42111. /**
  42112. * source material index of refraction (IOR)' / 'destination material IOR.
  42113. */
  42114. _this.indexOfRefraction = 0.66;
  42115. /**
  42116. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42117. */
  42118. _this.invertRefractionY = false;
  42119. /**
  42120. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42121. * Materials half opaque for instance using refraction could benefit from this control.
  42122. */
  42123. _this.linkRefractionWithTransparency = false;
  42124. _this.useLightmapAsShadowmap = false;
  42125. /**
  42126. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42127. */
  42128. _this.useAlphaFromAlbedoTexture = false;
  42129. /**
  42130. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42131. */
  42132. _this.forceAlphaTest = false;
  42133. /**
  42134. * Defines the alpha limits in alpha test mode.
  42135. */
  42136. _this.alphaCutOff = 0.4;
  42137. /**
  42138. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42139. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42140. */
  42141. _this.useSpecularOverAlpha = true;
  42142. /**
  42143. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42144. */
  42145. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42146. /**
  42147. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42148. */
  42149. _this.useRoughnessFromMetallicTextureAlpha = true;
  42150. /**
  42151. * Specifies if the metallic texture contains the roughness information in its green channel.
  42152. */
  42153. _this.useRoughnessFromMetallicTextureGreen = false;
  42154. /**
  42155. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42156. */
  42157. _this.useMetallnessFromMetallicTextureBlue = false;
  42158. /**
  42159. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42160. */
  42161. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42162. /**
  42163. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42164. */
  42165. _this.useAmbientInGrayScale = false;
  42166. /**
  42167. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42168. * The material will try to infer what glossiness each pixel should be.
  42169. */
  42170. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42171. /**
  42172. * BJS is using an harcoded light falloff based on a manually sets up range.
  42173. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42174. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42175. */
  42176. _this.usePhysicalLightFalloff = true;
  42177. /**
  42178. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42179. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42180. */
  42181. _this.useRadianceOverAlpha = true;
  42182. /**
  42183. * Allows using an object space normal map (instead of tangent space).
  42184. */
  42185. _this.useObjectSpaceNormalMap = false;
  42186. /**
  42187. * Allows using the bump map in parallax mode.
  42188. */
  42189. _this.useParallax = false;
  42190. /**
  42191. * Allows using the bump map in parallax occlusion mode.
  42192. */
  42193. _this.useParallaxOcclusion = false;
  42194. /**
  42195. * Controls the scale bias of the parallax mode.
  42196. */
  42197. _this.parallaxScaleBias = 0.05;
  42198. /**
  42199. * If sets to true, disables all the lights affecting the material.
  42200. */
  42201. _this.disableLighting = false;
  42202. /**
  42203. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42204. */
  42205. _this.forceIrradianceInFragment = false;
  42206. /**
  42207. * Number of Simultaneous lights allowed on the material.
  42208. */
  42209. _this.maxSimultaneousLights = 4;
  42210. /**
  42211. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42212. */
  42213. _this.invertNormalMapX = false;
  42214. /**
  42215. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42216. */
  42217. _this.invertNormalMapY = false;
  42218. /**
  42219. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42220. */
  42221. _this.twoSidedLighting = false;
  42222. /**
  42223. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42224. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42225. */
  42226. _this.useAlphaFresnel = false;
  42227. /**
  42228. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42229. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42230. */
  42231. _this.useLinearAlphaFresnel = false;
  42232. /**
  42233. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42234. * And/Or occlude the blended part.
  42235. */
  42236. _this.environmentBRDFTexture = null;
  42237. /**
  42238. * Force normal to face away from face.
  42239. */
  42240. _this.forceNormalForward = false;
  42241. /**
  42242. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42243. * makes the reflect vector face the model (under horizon).
  42244. */
  42245. _this.useHorizonOcclusion = true;
  42246. /**
  42247. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42248. * too much the area relying on ambient texture to define their ambient occlusion.
  42249. */
  42250. _this.useRadianceOcclusion = true;
  42251. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42252. return _this;
  42253. }
  42254. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42255. /**
  42256. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42257. */
  42258. get: function () {
  42259. return this._PBRMATERIAL_OPAQUE;
  42260. },
  42261. enumerable: true,
  42262. configurable: true
  42263. });
  42264. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42265. /**
  42266. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42267. */
  42268. get: function () {
  42269. return this._PBRMATERIAL_ALPHATEST;
  42270. },
  42271. enumerable: true,
  42272. configurable: true
  42273. });
  42274. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42275. /**
  42276. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42277. */
  42278. get: function () {
  42279. return this._PBRMATERIAL_ALPHABLEND;
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42285. /**
  42286. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42287. * They are also discarded below the alpha cutoff threshold to improve performances.
  42288. */
  42289. get: function () {
  42290. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42291. },
  42292. enumerable: true,
  42293. configurable: true
  42294. });
  42295. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42296. /**
  42297. * Gets the image processing configuration used either in this material.
  42298. */
  42299. get: function () {
  42300. return this._imageProcessingConfiguration;
  42301. },
  42302. /**
  42303. * Sets the Default image processing configuration used either in the this material.
  42304. *
  42305. * If sets to null, the scene one is in use.
  42306. */
  42307. set: function (value) {
  42308. this._attachImageProcessingConfiguration(value);
  42309. // Ensure the effect will be rebuilt.
  42310. this._markAllSubMeshesAsTexturesDirty();
  42311. },
  42312. enumerable: true,
  42313. configurable: true
  42314. });
  42315. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42316. /**
  42317. * Gets wether the color curves effect is enabled.
  42318. */
  42319. get: function () {
  42320. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42321. },
  42322. /**
  42323. * Sets wether the color curves effect is enabled.
  42324. */
  42325. set: function (value) {
  42326. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42332. /**
  42333. * Gets wether the color grading effect is enabled.
  42334. */
  42335. get: function () {
  42336. return this.imageProcessingConfiguration.colorGradingEnabled;
  42337. },
  42338. /**
  42339. * Gets wether the color grading effect is enabled.
  42340. */
  42341. set: function (value) {
  42342. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42343. },
  42344. enumerable: true,
  42345. configurable: true
  42346. });
  42347. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42348. /**
  42349. * Gets wether tonemapping is enabled or not.
  42350. */
  42351. get: function () {
  42352. return this._imageProcessingConfiguration.toneMappingEnabled;
  42353. },
  42354. /**
  42355. * Sets wether tonemapping is enabled or not
  42356. */
  42357. set: function (value) {
  42358. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. ;
  42364. ;
  42365. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42366. /**
  42367. * The camera exposure used on this material.
  42368. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42369. * This corresponds to a photographic exposure.
  42370. */
  42371. get: function () {
  42372. return this._imageProcessingConfiguration.exposure;
  42373. },
  42374. /**
  42375. * The camera exposure used on this material.
  42376. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42377. * This corresponds to a photographic exposure.
  42378. */
  42379. set: function (value) {
  42380. this._imageProcessingConfiguration.exposure = value;
  42381. },
  42382. enumerable: true,
  42383. configurable: true
  42384. });
  42385. ;
  42386. ;
  42387. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42388. /**
  42389. * Gets The camera contrast used on this material.
  42390. */
  42391. get: function () {
  42392. return this._imageProcessingConfiguration.contrast;
  42393. },
  42394. /**
  42395. * Sets The camera contrast used on this material.
  42396. */
  42397. set: function (value) {
  42398. this._imageProcessingConfiguration.contrast = value;
  42399. },
  42400. enumerable: true,
  42401. configurable: true
  42402. });
  42403. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42404. /**
  42405. * Gets the Color Grading 2D Lookup Texture.
  42406. */
  42407. get: function () {
  42408. return this._imageProcessingConfiguration.colorGradingTexture;
  42409. },
  42410. /**
  42411. * Sets the Color Grading 2D Lookup Texture.
  42412. */
  42413. set: function (value) {
  42414. this._imageProcessingConfiguration.colorGradingTexture = value;
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42420. /**
  42421. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42422. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42423. * 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;
  42424. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42425. */
  42426. get: function () {
  42427. return this._imageProcessingConfiguration.colorCurves;
  42428. },
  42429. /**
  42430. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42431. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42432. * 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;
  42433. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42434. */
  42435. set: function (value) {
  42436. this._imageProcessingConfiguration.colorCurves = value;
  42437. },
  42438. enumerable: true,
  42439. configurable: true
  42440. });
  42441. /**
  42442. * Returns the name of this material class.
  42443. */
  42444. PBRMaterial.prototype.getClassName = function () {
  42445. return "PBRMaterial";
  42446. };
  42447. /**
  42448. * Returns an array of the actively used textures.
  42449. * @returns - Array of BaseTextures
  42450. */
  42451. PBRMaterial.prototype.getActiveTextures = function () {
  42452. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42453. if (this._albedoTexture) {
  42454. activeTextures.push(this._albedoTexture);
  42455. }
  42456. if (this._ambientTexture) {
  42457. activeTextures.push(this._ambientTexture);
  42458. }
  42459. if (this._opacityTexture) {
  42460. activeTextures.push(this._opacityTexture);
  42461. }
  42462. if (this._reflectionTexture) {
  42463. activeTextures.push(this._reflectionTexture);
  42464. }
  42465. if (this._emissiveTexture) {
  42466. activeTextures.push(this._emissiveTexture);
  42467. }
  42468. if (this._reflectivityTexture) {
  42469. activeTextures.push(this._reflectivityTexture);
  42470. }
  42471. if (this._metallicTexture) {
  42472. activeTextures.push(this._metallicTexture);
  42473. }
  42474. if (this._microSurfaceTexture) {
  42475. activeTextures.push(this._microSurfaceTexture);
  42476. }
  42477. if (this._bumpTexture) {
  42478. activeTextures.push(this._bumpTexture);
  42479. }
  42480. if (this._lightmapTexture) {
  42481. activeTextures.push(this._lightmapTexture);
  42482. }
  42483. if (this._refractionTexture) {
  42484. activeTextures.push(this._refractionTexture);
  42485. }
  42486. return activeTextures;
  42487. };
  42488. /**
  42489. * Checks to see if a texture is used in the material.
  42490. * @param texture - Base texture to use.
  42491. * @returns - Boolean specifying if a texture is used in the material.
  42492. */
  42493. PBRMaterial.prototype.hasTexture = function (texture) {
  42494. if (_super.prototype.hasTexture.call(this, texture)) {
  42495. return true;
  42496. }
  42497. if (this._albedoTexture === texture) {
  42498. return true;
  42499. }
  42500. if (this._ambientTexture === texture) {
  42501. return true;
  42502. }
  42503. if (this._opacityTexture === texture) {
  42504. return true;
  42505. }
  42506. if (this._reflectionTexture === texture) {
  42507. return true;
  42508. }
  42509. if (this._reflectivityTexture === texture) {
  42510. return true;
  42511. }
  42512. if (this._metallicTexture === texture) {
  42513. return true;
  42514. }
  42515. if (this._microSurfaceTexture === texture) {
  42516. return true;
  42517. }
  42518. if (this._bumpTexture === texture) {
  42519. return true;
  42520. }
  42521. if (this._lightmapTexture === texture) {
  42522. return true;
  42523. }
  42524. if (this._refractionTexture === texture) {
  42525. return true;
  42526. }
  42527. return false;
  42528. };
  42529. /**
  42530. * Makes a duplicate of the current material.
  42531. * @param name - name to use for the new material.
  42532. */
  42533. PBRMaterial.prototype.clone = function (name) {
  42534. var _this = this;
  42535. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42536. clone.id = name;
  42537. clone.name = name;
  42538. return clone;
  42539. };
  42540. /**
  42541. * Serializes this PBR Material.
  42542. * @returns - An object with the serialized material.
  42543. */
  42544. PBRMaterial.prototype.serialize = function () {
  42545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42546. serializationObject.customType = "BABYLON.PBRMaterial";
  42547. return serializationObject;
  42548. };
  42549. // Statics
  42550. /**
  42551. * Parses a PBR Material from a serialized object.
  42552. * @param source - Serialized object.
  42553. * @param scene - BJS scene instance.
  42554. * @param rootUrl - url for the scene object
  42555. * @returns - PBRMaterial
  42556. */
  42557. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42558. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42559. };
  42560. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42561. /**
  42562. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42563. */
  42564. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42565. /**
  42566. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42567. */
  42568. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42569. /**
  42570. * 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.
  42571. * They are also discarded below the alpha cutoff threshold to improve performances.
  42572. */
  42573. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42574. __decorate([
  42575. BABYLON.serialize(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], PBRMaterial.prototype, "directIntensity", void 0);
  42578. __decorate([
  42579. BABYLON.serialize(),
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42581. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42582. __decorate([
  42583. BABYLON.serialize(),
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42585. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42586. __decorate([
  42587. BABYLON.serialize(),
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42590. __decorate([
  42591. BABYLON.serialize(),
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42593. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42594. __decorate([
  42595. BABYLON.serializeAsTexture(),
  42596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42597. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42598. __decorate([
  42599. BABYLON.serializeAsTexture(),
  42600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42601. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42602. __decorate([
  42603. BABYLON.serialize(),
  42604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42605. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42606. __decorate([
  42607. BABYLON.serializeAsTexture(),
  42608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42609. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42610. __decorate([
  42611. BABYLON.serializeAsTexture(),
  42612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42613. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42614. __decorate([
  42615. BABYLON.serializeAsTexture(),
  42616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42617. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42618. __decorate([
  42619. BABYLON.serializeAsTexture(),
  42620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42621. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42622. __decorate([
  42623. BABYLON.serializeAsTexture(),
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42625. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42626. __decorate([
  42627. BABYLON.serialize(),
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42629. ], PBRMaterial.prototype, "metallic", void 0);
  42630. __decorate([
  42631. BABYLON.serialize(),
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42633. ], PBRMaterial.prototype, "roughness", void 0);
  42634. __decorate([
  42635. BABYLON.serializeAsTexture(),
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42637. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42638. __decorate([
  42639. BABYLON.serializeAsTexture(),
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42641. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42642. __decorate([
  42643. BABYLON.serializeAsTexture(),
  42644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42645. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42646. __decorate([
  42647. BABYLON.serializeAsTexture(),
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42649. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42650. __decorate([
  42651. BABYLON.serializeAsColor3("ambient"),
  42652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42653. ], PBRMaterial.prototype, "ambientColor", void 0);
  42654. __decorate([
  42655. BABYLON.serializeAsColor3("albedo"),
  42656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42657. ], PBRMaterial.prototype, "albedoColor", void 0);
  42658. __decorate([
  42659. BABYLON.serializeAsColor3("reflectivity"),
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42662. __decorate([
  42663. BABYLON.serializeAsColor3("reflection"),
  42664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42665. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42666. __decorate([
  42667. BABYLON.serializeAsColor3("emissive"),
  42668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42669. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42670. __decorate([
  42671. BABYLON.serialize(),
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], PBRMaterial.prototype, "microSurface", void 0);
  42674. __decorate([
  42675. BABYLON.serialize(),
  42676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42677. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42678. __decorate([
  42679. BABYLON.serialize(),
  42680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42681. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42682. __decorate([
  42683. BABYLON.serialize(),
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42686. __decorate([
  42687. BABYLON.serialize(),
  42688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42689. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42690. __decorate([
  42691. BABYLON.serialize(),
  42692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42693. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42694. __decorate([
  42695. BABYLON.serialize(),
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42697. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42698. __decorate([
  42699. BABYLON.serialize(),
  42700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42701. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42702. __decorate([
  42703. BABYLON.serialize(),
  42704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42705. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42706. __decorate([
  42707. BABYLON.serialize(),
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42710. __decorate([
  42711. BABYLON.serialize(),
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42713. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42714. __decorate([
  42715. BABYLON.serialize(),
  42716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42717. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42718. __decorate([
  42719. BABYLON.serialize(),
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42722. __decorate([
  42723. BABYLON.serialize(),
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42726. __decorate([
  42727. BABYLON.serialize(),
  42728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42729. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42730. __decorate([
  42731. BABYLON.serialize(),
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42734. __decorate([
  42735. BABYLON.serialize(),
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42738. __decorate([
  42739. BABYLON.serialize(),
  42740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42741. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42742. __decorate([
  42743. BABYLON.serialize(),
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42746. __decorate([
  42747. BABYLON.serialize(),
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], PBRMaterial.prototype, "useParallax", void 0);
  42750. __decorate([
  42751. BABYLON.serialize(),
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42753. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42754. __decorate([
  42755. BABYLON.serialize(),
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42757. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42758. __decorate([
  42759. BABYLON.serialize(),
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42761. ], PBRMaterial.prototype, "disableLighting", void 0);
  42762. __decorate([
  42763. BABYLON.serialize(),
  42764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42765. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42766. __decorate([
  42767. BABYLON.serialize(),
  42768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42769. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42770. __decorate([
  42771. BABYLON.serialize(),
  42772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42773. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42774. __decorate([
  42775. BABYLON.serialize(),
  42776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42777. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42778. __decorate([
  42779. BABYLON.serialize(),
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42782. __decorate([
  42783. BABYLON.serialize(),
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42785. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42786. __decorate([
  42787. BABYLON.serialize(),
  42788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42789. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42790. __decorate([
  42791. BABYLON.serializeAsTexture(),
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42793. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42794. __decorate([
  42795. BABYLON.serialize(),
  42796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42797. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42798. __decorate([
  42799. BABYLON.serialize(),
  42800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42801. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42802. __decorate([
  42803. BABYLON.serialize(),
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42805. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42806. return PBRMaterial;
  42807. }(BABYLON.PBRBaseMaterial));
  42808. BABYLON.PBRMaterial = PBRMaterial;
  42809. })(BABYLON || (BABYLON = {}));
  42810. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42811. var BABYLON;
  42812. (function (BABYLON) {
  42813. /**
  42814. * The PBR material of BJS following the metal roughness convention.
  42815. *
  42816. * This fits to the PBR convention in the GLTF definition:
  42817. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42818. */
  42819. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42820. __extends(PBRMetallicRoughnessMaterial, _super);
  42821. /**
  42822. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42823. *
  42824. * @param name The material name
  42825. * @param scene The scene the material will be use in.
  42826. */
  42827. function PBRMetallicRoughnessMaterial(name, scene) {
  42828. var _this = _super.call(this, name, scene) || this;
  42829. _this._useRoughnessFromMetallicTextureAlpha = false;
  42830. _this._useRoughnessFromMetallicTextureGreen = true;
  42831. _this._useMetallnessFromMetallicTextureBlue = true;
  42832. _this.metallic = 1.0;
  42833. _this.roughness = 1.0;
  42834. return _this;
  42835. }
  42836. /**
  42837. * Return the currrent class name of the material.
  42838. */
  42839. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42840. return "PBRMetallicRoughnessMaterial";
  42841. };
  42842. /**
  42843. * Return the active textures of the material.
  42844. */
  42845. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42846. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42847. if (this.baseTexture) {
  42848. activeTextures.push(this.baseTexture);
  42849. }
  42850. if (this.metallicRoughnessTexture) {
  42851. activeTextures.push(this.metallicRoughnessTexture);
  42852. }
  42853. return activeTextures;
  42854. };
  42855. /**
  42856. * Checks to see if a texture is used in the material.
  42857. * @param texture - Base texture to use.
  42858. * @returns - Boolean specifying if a texture is used in the material.
  42859. */
  42860. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42861. if (_super.prototype.hasTexture.call(this, texture)) {
  42862. return true;
  42863. }
  42864. if (this.baseTexture === texture) {
  42865. return true;
  42866. }
  42867. if (this.metallicRoughnessTexture === texture) {
  42868. return true;
  42869. }
  42870. return false;
  42871. };
  42872. /**
  42873. * Makes a duplicate of the current material.
  42874. * @param name - name to use for the new material.
  42875. */
  42876. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42877. var _this = this;
  42878. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42879. clone.id = name;
  42880. clone.name = name;
  42881. return clone;
  42882. };
  42883. /**
  42884. * Serialize the material to a parsable JSON object.
  42885. */
  42886. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42887. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42888. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42889. return serializationObject;
  42890. };
  42891. /**
  42892. * Parses a JSON object correponding to the serialize function.
  42893. */
  42894. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42895. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42896. };
  42897. __decorate([
  42898. BABYLON.serializeAsColor3(),
  42899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42900. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42901. __decorate([
  42902. BABYLON.serializeAsTexture(),
  42903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42904. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42905. __decorate([
  42906. BABYLON.serialize(),
  42907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42908. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42909. __decorate([
  42910. BABYLON.serialize(),
  42911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42912. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42913. __decorate([
  42914. BABYLON.serializeAsTexture(),
  42915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42916. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42917. return PBRMetallicRoughnessMaterial;
  42918. }(BABYLON.PBRBaseSimpleMaterial));
  42919. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42920. })(BABYLON || (BABYLON = {}));
  42921. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42922. var BABYLON;
  42923. (function (BABYLON) {
  42924. /**
  42925. * The PBR material of BJS following the specular glossiness convention.
  42926. *
  42927. * This fits to the PBR convention in the GLTF definition:
  42928. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42929. */
  42930. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42931. __extends(PBRSpecularGlossinessMaterial, _super);
  42932. /**
  42933. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42934. *
  42935. * @param name The material name
  42936. * @param scene The scene the material will be use in.
  42937. */
  42938. function PBRSpecularGlossinessMaterial(name, scene) {
  42939. var _this = _super.call(this, name, scene) || this;
  42940. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42941. return _this;
  42942. }
  42943. /**
  42944. * Return the currrent class name of the material.
  42945. */
  42946. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42947. return "PBRSpecularGlossinessMaterial";
  42948. };
  42949. /**
  42950. * Return the active textures of the material.
  42951. */
  42952. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42953. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42954. if (this.diffuseTexture) {
  42955. activeTextures.push(this.diffuseTexture);
  42956. }
  42957. if (this.specularGlossinessTexture) {
  42958. activeTextures.push(this.specularGlossinessTexture);
  42959. }
  42960. return activeTextures;
  42961. };
  42962. /**
  42963. * Checks to see if a texture is used in the material.
  42964. * @param texture - Base texture to use.
  42965. * @returns - Boolean specifying if a texture is used in the material.
  42966. */
  42967. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42968. if (_super.prototype.hasTexture.call(this, texture)) {
  42969. return true;
  42970. }
  42971. if (this.diffuseTexture === texture) {
  42972. return true;
  42973. }
  42974. if (this.specularGlossinessTexture === texture) {
  42975. return true;
  42976. }
  42977. return false;
  42978. };
  42979. /**
  42980. * Makes a duplicate of the current material.
  42981. * @param name - name to use for the new material.
  42982. */
  42983. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42984. var _this = this;
  42985. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42986. clone.id = name;
  42987. clone.name = name;
  42988. return clone;
  42989. };
  42990. /**
  42991. * Serialize the material to a parsable JSON object.
  42992. */
  42993. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42994. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42995. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42996. return serializationObject;
  42997. };
  42998. /**
  42999. * Parses a JSON object correponding to the serialize function.
  43000. */
  43001. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43002. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43003. };
  43004. __decorate([
  43005. BABYLON.serializeAsColor3("diffuse"),
  43006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43007. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43008. __decorate([
  43009. BABYLON.serializeAsTexture(),
  43010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43011. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43012. __decorate([
  43013. BABYLON.serializeAsColor3("specular"),
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43015. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43016. __decorate([
  43017. BABYLON.serialize(),
  43018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43019. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43020. __decorate([
  43021. BABYLON.serializeAsTexture(),
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43023. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43024. return PBRSpecularGlossinessMaterial;
  43025. }(BABYLON.PBRBaseSimpleMaterial));
  43026. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43027. })(BABYLON || (BABYLON = {}));
  43028. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43029. var BABYLON;
  43030. (function (BABYLON) {
  43031. BABYLON.CameraInputTypes = {};
  43032. var CameraInputsManager = /** @class */ (function () {
  43033. function CameraInputsManager(camera) {
  43034. this.attached = {};
  43035. this.camera = camera;
  43036. this.checkInputs = function () { };
  43037. }
  43038. /**
  43039. * Add an input method to a camera.
  43040. * builtin inputs example: camera.inputs.addGamepad();
  43041. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43042. * @param input camera input method
  43043. */
  43044. CameraInputsManager.prototype.add = function (input) {
  43045. var type = input.getSimpleName();
  43046. if (this.attached[type]) {
  43047. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43048. return;
  43049. }
  43050. this.attached[type] = input;
  43051. input.camera = this.camera;
  43052. //for checkInputs, we are dynamically creating a function
  43053. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43054. if (input.checkInputs) {
  43055. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43056. }
  43057. if (this.attachedElement) {
  43058. input.attachControl(this.attachedElement);
  43059. }
  43060. };
  43061. /**
  43062. * Remove a specific input method from a camera
  43063. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43064. * @param inputToRemove camera input method
  43065. */
  43066. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43067. for (var cam in this.attached) {
  43068. var input = this.attached[cam];
  43069. if (input === inputToRemove) {
  43070. input.detachControl(this.attachedElement);
  43071. input.camera = null;
  43072. delete this.attached[cam];
  43073. this.rebuildInputCheck();
  43074. }
  43075. }
  43076. };
  43077. CameraInputsManager.prototype.removeByType = function (inputType) {
  43078. for (var cam in this.attached) {
  43079. var input = this.attached[cam];
  43080. if (input.getClassName() === inputType) {
  43081. input.detachControl(this.attachedElement);
  43082. input.camera = null;
  43083. delete this.attached[cam];
  43084. this.rebuildInputCheck();
  43085. }
  43086. }
  43087. };
  43088. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43089. var current = this.checkInputs;
  43090. return function () {
  43091. current();
  43092. fn();
  43093. };
  43094. };
  43095. CameraInputsManager.prototype.attachInput = function (input) {
  43096. if (this.attachedElement) {
  43097. input.attachControl(this.attachedElement, this.noPreventDefault);
  43098. }
  43099. };
  43100. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43101. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43102. if (this.attachedElement) {
  43103. return;
  43104. }
  43105. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43106. this.attachedElement = element;
  43107. this.noPreventDefault = noPreventDefault;
  43108. for (var cam in this.attached) {
  43109. this.attached[cam].attachControl(element, noPreventDefault);
  43110. }
  43111. };
  43112. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43113. if (disconnect === void 0) { disconnect = false; }
  43114. if (this.attachedElement !== element) {
  43115. return;
  43116. }
  43117. for (var cam in this.attached) {
  43118. this.attached[cam].detachControl(element);
  43119. if (disconnect) {
  43120. this.attached[cam].camera = null;
  43121. }
  43122. }
  43123. this.attachedElement = null;
  43124. };
  43125. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43126. this.checkInputs = function () { };
  43127. for (var cam in this.attached) {
  43128. var input = this.attached[cam];
  43129. if (input.checkInputs) {
  43130. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43131. }
  43132. }
  43133. };
  43134. /**
  43135. * Remove all attached input methods from a camera
  43136. */
  43137. CameraInputsManager.prototype.clear = function () {
  43138. if (this.attachedElement) {
  43139. this.detachElement(this.attachedElement, true);
  43140. }
  43141. this.attached = {};
  43142. this.attachedElement = null;
  43143. this.checkInputs = function () { };
  43144. };
  43145. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43146. var inputs = {};
  43147. for (var cam in this.attached) {
  43148. var input = this.attached[cam];
  43149. var res = BABYLON.SerializationHelper.Serialize(input);
  43150. inputs[input.getClassName()] = res;
  43151. }
  43152. serializedCamera.inputsmgr = inputs;
  43153. };
  43154. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43155. var parsedInputs = parsedCamera.inputsmgr;
  43156. if (parsedInputs) {
  43157. this.clear();
  43158. for (var n in parsedInputs) {
  43159. var construct = BABYLON.CameraInputTypes[n];
  43160. if (construct) {
  43161. var parsedinput = parsedInputs[n];
  43162. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43163. this.add(input);
  43164. }
  43165. }
  43166. }
  43167. else {
  43168. //2016-03-08 this part is for managing backward compatibility
  43169. for (var n in this.attached) {
  43170. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43171. if (construct) {
  43172. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43173. this.remove(this.attached[n]);
  43174. this.add(input);
  43175. }
  43176. }
  43177. }
  43178. };
  43179. return CameraInputsManager;
  43180. }());
  43181. BABYLON.CameraInputsManager = CameraInputsManager;
  43182. })(BABYLON || (BABYLON = {}));
  43183. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43184. var BABYLON;
  43185. (function (BABYLON) {
  43186. var TargetCamera = /** @class */ (function (_super) {
  43187. __extends(TargetCamera, _super);
  43188. function TargetCamera(name, position, scene) {
  43189. var _this = _super.call(this, name, position, scene) || this;
  43190. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43191. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43192. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43193. _this.speed = 2.0;
  43194. _this.noRotationConstraint = false;
  43195. _this.lockedTarget = null;
  43196. _this._currentTarget = BABYLON.Vector3.Zero();
  43197. _this._viewMatrix = BABYLON.Matrix.Zero();
  43198. _this._camMatrix = BABYLON.Matrix.Zero();
  43199. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43200. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43201. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43202. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43203. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43204. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43205. _this._tempMatrix = BABYLON.Matrix.Zero();
  43206. return _this;
  43207. }
  43208. TargetCamera.prototype.getFrontPosition = function (distance) {
  43209. this.getWorldMatrix();
  43210. var direction = this.getTarget().subtract(this.position);
  43211. direction.normalize();
  43212. direction.scaleInPlace(distance);
  43213. return this.globalPosition.add(direction);
  43214. };
  43215. TargetCamera.prototype._getLockedTargetPosition = function () {
  43216. if (!this.lockedTarget) {
  43217. return null;
  43218. }
  43219. if (this.lockedTarget.absolutePosition) {
  43220. this.lockedTarget.computeWorldMatrix();
  43221. }
  43222. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43223. };
  43224. TargetCamera.prototype.storeState = function () {
  43225. this._storedPosition = this.position.clone();
  43226. this._storedRotation = this.rotation.clone();
  43227. if (this.rotationQuaternion) {
  43228. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43229. }
  43230. return _super.prototype.storeState.call(this);
  43231. };
  43232. /**
  43233. * Restored camera state. You must call storeState() first
  43234. */
  43235. TargetCamera.prototype._restoreStateValues = function () {
  43236. if (!_super.prototype._restoreStateValues.call(this)) {
  43237. return false;
  43238. }
  43239. this.position = this._storedPosition.clone();
  43240. this.rotation = this._storedRotation.clone();
  43241. if (this.rotationQuaternion) {
  43242. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43243. }
  43244. this.cameraDirection.copyFromFloats(0, 0, 0);
  43245. this.cameraRotation.copyFromFloats(0, 0);
  43246. return true;
  43247. };
  43248. // Cache
  43249. TargetCamera.prototype._initCache = function () {
  43250. _super.prototype._initCache.call(this);
  43251. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43252. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43253. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43254. };
  43255. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43256. if (!ignoreParentClass) {
  43257. _super.prototype._updateCache.call(this);
  43258. }
  43259. var lockedTargetPosition = this._getLockedTargetPosition();
  43260. if (!lockedTargetPosition) {
  43261. this._cache.lockedTarget = null;
  43262. }
  43263. else {
  43264. if (!this._cache.lockedTarget) {
  43265. this._cache.lockedTarget = lockedTargetPosition.clone();
  43266. }
  43267. else {
  43268. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43269. }
  43270. }
  43271. this._cache.rotation.copyFrom(this.rotation);
  43272. if (this.rotationQuaternion)
  43273. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43274. };
  43275. // Synchronized
  43276. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43277. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43278. return false;
  43279. }
  43280. var lockedTargetPosition = this._getLockedTargetPosition();
  43281. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43282. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43283. };
  43284. // Methods
  43285. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43286. var engine = this.getEngine();
  43287. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43288. };
  43289. // Target
  43290. TargetCamera.prototype.setTarget = function (target) {
  43291. this.upVector.normalize();
  43292. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43293. this._camMatrix.invert();
  43294. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43295. var vDir = target.subtract(this.position);
  43296. if (vDir.x >= 0.0) {
  43297. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43298. }
  43299. else {
  43300. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43301. }
  43302. this.rotation.z = 0;
  43303. if (isNaN(this.rotation.x)) {
  43304. this.rotation.x = 0;
  43305. }
  43306. if (isNaN(this.rotation.y)) {
  43307. this.rotation.y = 0;
  43308. }
  43309. if (isNaN(this.rotation.z)) {
  43310. this.rotation.z = 0;
  43311. }
  43312. if (this.rotationQuaternion) {
  43313. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43314. }
  43315. };
  43316. /**
  43317. * Return the current target position of the camera. This value is expressed in local space.
  43318. */
  43319. TargetCamera.prototype.getTarget = function () {
  43320. return this._currentTarget;
  43321. };
  43322. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43323. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43324. };
  43325. TargetCamera.prototype._updatePosition = function () {
  43326. if (this.parent) {
  43327. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43328. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43329. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43330. return;
  43331. }
  43332. this.position.addInPlace(this.cameraDirection);
  43333. };
  43334. TargetCamera.prototype._checkInputs = function () {
  43335. var needToMove = this._decideIfNeedsToMove();
  43336. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43337. // Move
  43338. if (needToMove) {
  43339. this._updatePosition();
  43340. }
  43341. // Rotate
  43342. if (needToRotate) {
  43343. this.rotation.x += this.cameraRotation.x;
  43344. this.rotation.y += this.cameraRotation.y;
  43345. //rotate, if quaternion is set and rotation was used
  43346. if (this.rotationQuaternion) {
  43347. var len = this.rotation.lengthSquared();
  43348. if (len) {
  43349. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43350. }
  43351. }
  43352. if (!this.noRotationConstraint) {
  43353. var limit = (Math.PI / 2) * 0.95;
  43354. if (this.rotation.x > limit)
  43355. this.rotation.x = limit;
  43356. if (this.rotation.x < -limit)
  43357. this.rotation.x = -limit;
  43358. }
  43359. }
  43360. // Inertia
  43361. if (needToMove) {
  43362. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43363. this.cameraDirection.x = 0;
  43364. }
  43365. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43366. this.cameraDirection.y = 0;
  43367. }
  43368. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43369. this.cameraDirection.z = 0;
  43370. }
  43371. this.cameraDirection.scaleInPlace(this.inertia);
  43372. }
  43373. if (needToRotate) {
  43374. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43375. this.cameraRotation.x = 0;
  43376. }
  43377. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43378. this.cameraRotation.y = 0;
  43379. }
  43380. this.cameraRotation.scaleInPlace(this.inertia);
  43381. }
  43382. _super.prototype._checkInputs.call(this);
  43383. };
  43384. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43385. if (this.rotationQuaternion) {
  43386. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43387. }
  43388. else {
  43389. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43390. }
  43391. //update the up vector!
  43392. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43393. };
  43394. TargetCamera.prototype._getViewMatrix = function () {
  43395. if (this.lockedTarget) {
  43396. this.setTarget(this._getLockedTargetPosition());
  43397. }
  43398. // Compute
  43399. this._updateCameraRotationMatrix();
  43400. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43401. // Computing target and final matrix
  43402. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43403. if (this.getScene().useRightHandedSystem) {
  43404. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43405. }
  43406. else {
  43407. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43408. }
  43409. return this._viewMatrix;
  43410. };
  43411. /**
  43412. * @override
  43413. * Override Camera.createRigCamera
  43414. */
  43415. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43416. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43417. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43418. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43419. if (!this.rotationQuaternion) {
  43420. this.rotationQuaternion = new BABYLON.Quaternion();
  43421. }
  43422. rigCamera._cameraRigParams = {};
  43423. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43424. }
  43425. return rigCamera;
  43426. }
  43427. return null;
  43428. };
  43429. /**
  43430. * @override
  43431. * Override Camera._updateRigCameras
  43432. */
  43433. TargetCamera.prototype._updateRigCameras = function () {
  43434. var camLeft = this._rigCameras[0];
  43435. var camRight = this._rigCameras[1];
  43436. switch (this.cameraRigMode) {
  43437. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43438. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43439. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43440. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43441. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43442. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43443. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43444. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43445. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43446. camLeft.setTarget(this.getTarget());
  43447. camRight.setTarget(this.getTarget());
  43448. break;
  43449. case BABYLON.Camera.RIG_MODE_VR:
  43450. if (camLeft.rotationQuaternion) {
  43451. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43452. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43453. }
  43454. else {
  43455. camLeft.rotation.copyFrom(this.rotation);
  43456. camRight.rotation.copyFrom(this.rotation);
  43457. }
  43458. camLeft.position.copyFrom(this.position);
  43459. camRight.position.copyFrom(this.position);
  43460. break;
  43461. }
  43462. _super.prototype._updateRigCameras.call(this);
  43463. };
  43464. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43465. if (!this._rigCamTransformMatrix) {
  43466. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43467. }
  43468. var target = this.getTarget();
  43469. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43470. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43471. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43472. };
  43473. TargetCamera.prototype.getClassName = function () {
  43474. return "TargetCamera";
  43475. };
  43476. __decorate([
  43477. BABYLON.serializeAsVector3()
  43478. ], TargetCamera.prototype, "rotation", void 0);
  43479. __decorate([
  43480. BABYLON.serialize()
  43481. ], TargetCamera.prototype, "speed", void 0);
  43482. __decorate([
  43483. BABYLON.serializeAsMeshReference("lockedTargetId")
  43484. ], TargetCamera.prototype, "lockedTarget", void 0);
  43485. return TargetCamera;
  43486. }(BABYLON.Camera));
  43487. BABYLON.TargetCamera = TargetCamera;
  43488. })(BABYLON || (BABYLON = {}));
  43489. //# sourceMappingURL=babylon.targetCamera.js.map
  43490. var BABYLON;
  43491. (function (BABYLON) {
  43492. var FreeCameraMouseInput = /** @class */ (function () {
  43493. function FreeCameraMouseInput(touchEnabled) {
  43494. if (touchEnabled === void 0) { touchEnabled = true; }
  43495. this.touchEnabled = touchEnabled;
  43496. this.buttons = [0, 1, 2];
  43497. this.angularSensibility = 2000.0;
  43498. this.previousPosition = null;
  43499. }
  43500. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43501. var _this = this;
  43502. var engine = this.camera.getEngine();
  43503. if (!this._pointerInput) {
  43504. this._pointerInput = function (p, s) {
  43505. var evt = p.event;
  43506. if (engine.isInVRExclusivePointerMode) {
  43507. return;
  43508. }
  43509. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43510. return;
  43511. }
  43512. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43513. return;
  43514. }
  43515. var srcElement = (evt.srcElement || evt.target);
  43516. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43517. try {
  43518. srcElement.setPointerCapture(evt.pointerId);
  43519. }
  43520. catch (e) {
  43521. //Nothing to do with the error. Execution will continue.
  43522. }
  43523. _this.previousPosition = {
  43524. x: evt.clientX,
  43525. y: evt.clientY
  43526. };
  43527. if (!noPreventDefault) {
  43528. evt.preventDefault();
  43529. element.focus();
  43530. }
  43531. }
  43532. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43533. try {
  43534. srcElement.releasePointerCapture(evt.pointerId);
  43535. }
  43536. catch (e) {
  43537. //Nothing to do with the error.
  43538. }
  43539. _this.previousPosition = null;
  43540. if (!noPreventDefault) {
  43541. evt.preventDefault();
  43542. }
  43543. }
  43544. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43545. if (!_this.previousPosition || engine.isPointerLock) {
  43546. return;
  43547. }
  43548. var offsetX = evt.clientX - _this.previousPosition.x;
  43549. var offsetY = evt.clientY - _this.previousPosition.y;
  43550. if (_this.camera.getScene().useRightHandedSystem) {
  43551. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43552. }
  43553. else {
  43554. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43555. }
  43556. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43557. _this.previousPosition = {
  43558. x: evt.clientX,
  43559. y: evt.clientY
  43560. };
  43561. if (!noPreventDefault) {
  43562. evt.preventDefault();
  43563. }
  43564. }
  43565. };
  43566. }
  43567. this._onMouseMove = function (evt) {
  43568. if (!engine.isPointerLock) {
  43569. return;
  43570. }
  43571. if (engine.isInVRExclusivePointerMode) {
  43572. return;
  43573. }
  43574. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43575. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43576. if (_this.camera.getScene().useRightHandedSystem) {
  43577. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43578. }
  43579. else {
  43580. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43581. }
  43582. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43583. _this.previousPosition = null;
  43584. if (!noPreventDefault) {
  43585. evt.preventDefault();
  43586. }
  43587. };
  43588. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43589. element.addEventListener("mousemove", this._onMouseMove, false);
  43590. };
  43591. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43592. if (this._observer && element) {
  43593. this.camera.getScene().onPointerObservable.remove(this._observer);
  43594. if (this._onMouseMove) {
  43595. element.removeEventListener("mousemove", this._onMouseMove);
  43596. }
  43597. this._observer = null;
  43598. this._onMouseMove = null;
  43599. this.previousPosition = null;
  43600. }
  43601. };
  43602. FreeCameraMouseInput.prototype.getClassName = function () {
  43603. return "FreeCameraMouseInput";
  43604. };
  43605. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43606. return "mouse";
  43607. };
  43608. __decorate([
  43609. BABYLON.serialize()
  43610. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43611. __decorate([
  43612. BABYLON.serialize()
  43613. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43614. return FreeCameraMouseInput;
  43615. }());
  43616. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43617. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43618. })(BABYLON || (BABYLON = {}));
  43619. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43620. var BABYLON;
  43621. (function (BABYLON) {
  43622. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43623. function FreeCameraKeyboardMoveInput() {
  43624. this._keys = new Array();
  43625. this.keysUp = [38];
  43626. this.keysDown = [40];
  43627. this.keysLeft = [37];
  43628. this.keysRight = [39];
  43629. }
  43630. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43631. var _this = this;
  43632. if (this._onCanvasBlurObserver) {
  43633. return;
  43634. }
  43635. this._scene = this.camera.getScene();
  43636. this._engine = this._scene.getEngine();
  43637. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43638. _this._keys = [];
  43639. });
  43640. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43641. var evt = info.event;
  43642. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43643. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43644. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43645. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43646. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43647. var index = _this._keys.indexOf(evt.keyCode);
  43648. if (index === -1) {
  43649. _this._keys.push(evt.keyCode);
  43650. }
  43651. if (!noPreventDefault) {
  43652. evt.preventDefault();
  43653. }
  43654. }
  43655. }
  43656. else {
  43657. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43658. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43659. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43660. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43661. var index = _this._keys.indexOf(evt.keyCode);
  43662. if (index >= 0) {
  43663. _this._keys.splice(index, 1);
  43664. }
  43665. if (!noPreventDefault) {
  43666. evt.preventDefault();
  43667. }
  43668. }
  43669. }
  43670. });
  43671. };
  43672. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43673. if (this._scene) {
  43674. if (this._onKeyboardObserver) {
  43675. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43676. }
  43677. if (this._onCanvasBlurObserver) {
  43678. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43679. }
  43680. this._onKeyboardObserver = null;
  43681. this._onCanvasBlurObserver = null;
  43682. }
  43683. this._keys = [];
  43684. };
  43685. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43686. if (this._onKeyboardObserver) {
  43687. var camera = this.camera;
  43688. // Keyboard
  43689. for (var index = 0; index < this._keys.length; index++) {
  43690. var keyCode = this._keys[index];
  43691. var speed = camera._computeLocalCameraSpeed();
  43692. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43693. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43694. }
  43695. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43696. camera._localDirection.copyFromFloats(0, 0, speed);
  43697. }
  43698. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43699. camera._localDirection.copyFromFloats(speed, 0, 0);
  43700. }
  43701. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43702. camera._localDirection.copyFromFloats(0, 0, -speed);
  43703. }
  43704. if (camera.getScene().useRightHandedSystem) {
  43705. camera._localDirection.z *= -1;
  43706. }
  43707. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43708. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43709. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43710. }
  43711. }
  43712. };
  43713. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43714. return "FreeCameraKeyboardMoveInput";
  43715. };
  43716. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43717. this._keys = [];
  43718. };
  43719. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43720. return "keyboard";
  43721. };
  43722. __decorate([
  43723. BABYLON.serialize()
  43724. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43725. __decorate([
  43726. BABYLON.serialize()
  43727. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43728. __decorate([
  43729. BABYLON.serialize()
  43730. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43731. __decorate([
  43732. BABYLON.serialize()
  43733. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43734. return FreeCameraKeyboardMoveInput;
  43735. }());
  43736. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43737. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43738. })(BABYLON || (BABYLON = {}));
  43739. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43740. var BABYLON;
  43741. (function (BABYLON) {
  43742. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43743. __extends(FreeCameraInputsManager, _super);
  43744. function FreeCameraInputsManager(camera) {
  43745. return _super.call(this, camera) || this;
  43746. }
  43747. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43748. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43749. return this;
  43750. };
  43751. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43752. if (touchEnabled === void 0) { touchEnabled = true; }
  43753. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43754. return this;
  43755. };
  43756. FreeCameraInputsManager.prototype.addGamepad = function () {
  43757. this.add(new BABYLON.FreeCameraGamepadInput());
  43758. return this;
  43759. };
  43760. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43761. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43762. return this;
  43763. };
  43764. FreeCameraInputsManager.prototype.addTouch = function () {
  43765. this.add(new BABYLON.FreeCameraTouchInput());
  43766. return this;
  43767. };
  43768. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43769. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43770. return this;
  43771. };
  43772. return FreeCameraInputsManager;
  43773. }(BABYLON.CameraInputsManager));
  43774. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43775. })(BABYLON || (BABYLON = {}));
  43776. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43777. var BABYLON;
  43778. (function (BABYLON) {
  43779. var FreeCamera = /** @class */ (function (_super) {
  43780. __extends(FreeCamera, _super);
  43781. function FreeCamera(name, position, scene) {
  43782. var _this = _super.call(this, name, position, scene) || this;
  43783. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43784. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43785. _this.checkCollisions = false;
  43786. _this.applyGravity = false;
  43787. _this._needMoveForGravity = false;
  43788. _this._oldPosition = BABYLON.Vector3.Zero();
  43789. _this._diffPosition = BABYLON.Vector3.Zero();
  43790. _this._newPosition = BABYLON.Vector3.Zero();
  43791. // Collisions
  43792. _this._collisionMask = -1;
  43793. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43794. if (collidedMesh === void 0) { collidedMesh = null; }
  43795. //TODO move this to the collision coordinator!
  43796. if (_this.getScene().workerCollisions)
  43797. newPosition.multiplyInPlace(_this._collider._radius);
  43798. var updatePosition = function (newPos) {
  43799. _this._newPosition.copyFrom(newPos);
  43800. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43801. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43802. _this.position.addInPlace(_this._diffPosition);
  43803. if (_this.onCollide && collidedMesh) {
  43804. _this.onCollide(collidedMesh);
  43805. }
  43806. }
  43807. };
  43808. updatePosition(newPosition);
  43809. };
  43810. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43811. _this.inputs.addKeyboard().addMouse();
  43812. return _this;
  43813. }
  43814. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43815. //-- begin properties for backward compatibility for inputs
  43816. /**
  43817. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43818. * Higher values reduce sensitivity.
  43819. */
  43820. get: function () {
  43821. var mouse = this.inputs.attached["mouse"];
  43822. if (mouse)
  43823. return mouse.angularSensibility;
  43824. return 0;
  43825. },
  43826. /**
  43827. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43828. * Higher values reduce sensitivity.
  43829. */
  43830. set: function (value) {
  43831. var mouse = this.inputs.attached["mouse"];
  43832. if (mouse)
  43833. mouse.angularSensibility = value;
  43834. },
  43835. enumerable: true,
  43836. configurable: true
  43837. });
  43838. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43839. get: function () {
  43840. var keyboard = this.inputs.attached["keyboard"];
  43841. if (keyboard)
  43842. return keyboard.keysUp;
  43843. return [];
  43844. },
  43845. set: function (value) {
  43846. var keyboard = this.inputs.attached["keyboard"];
  43847. if (keyboard)
  43848. keyboard.keysUp = value;
  43849. },
  43850. enumerable: true,
  43851. configurable: true
  43852. });
  43853. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43854. get: function () {
  43855. var keyboard = this.inputs.attached["keyboard"];
  43856. if (keyboard)
  43857. return keyboard.keysDown;
  43858. return [];
  43859. },
  43860. set: function (value) {
  43861. var keyboard = this.inputs.attached["keyboard"];
  43862. if (keyboard)
  43863. keyboard.keysDown = value;
  43864. },
  43865. enumerable: true,
  43866. configurable: true
  43867. });
  43868. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43869. get: function () {
  43870. var keyboard = this.inputs.attached["keyboard"];
  43871. if (keyboard)
  43872. return keyboard.keysLeft;
  43873. return [];
  43874. },
  43875. set: function (value) {
  43876. var keyboard = this.inputs.attached["keyboard"];
  43877. if (keyboard)
  43878. keyboard.keysLeft = value;
  43879. },
  43880. enumerable: true,
  43881. configurable: true
  43882. });
  43883. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43884. get: function () {
  43885. var keyboard = this.inputs.attached["keyboard"];
  43886. if (keyboard)
  43887. return keyboard.keysRight;
  43888. return [];
  43889. },
  43890. set: function (value) {
  43891. var keyboard = this.inputs.attached["keyboard"];
  43892. if (keyboard)
  43893. keyboard.keysRight = value;
  43894. },
  43895. enumerable: true,
  43896. configurable: true
  43897. });
  43898. // Controls
  43899. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43900. this.inputs.attachElement(element, noPreventDefault);
  43901. };
  43902. FreeCamera.prototype.detachControl = function (element) {
  43903. this.inputs.detachElement(element);
  43904. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43905. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43906. };
  43907. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43908. get: function () {
  43909. return this._collisionMask;
  43910. },
  43911. set: function (mask) {
  43912. this._collisionMask = !isNaN(mask) ? mask : -1;
  43913. },
  43914. enumerable: true,
  43915. configurable: true
  43916. });
  43917. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43918. var globalPosition;
  43919. if (this.parent) {
  43920. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43921. }
  43922. else {
  43923. globalPosition = this.position;
  43924. }
  43925. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43926. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43927. if (!this._collider) {
  43928. this._collider = new BABYLON.Collider();
  43929. }
  43930. this._collider._radius = this.ellipsoid;
  43931. this._collider.collisionMask = this._collisionMask;
  43932. //no need for clone, as long as gravity is not on.
  43933. var actualDisplacement = displacement;
  43934. //add gravity to the direction to prevent the dual-collision checking
  43935. if (this.applyGravity) {
  43936. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43937. actualDisplacement = displacement.add(this.getScene().gravity);
  43938. }
  43939. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43940. };
  43941. FreeCamera.prototype._checkInputs = function () {
  43942. if (!this._localDirection) {
  43943. this._localDirection = BABYLON.Vector3.Zero();
  43944. this._transformedDirection = BABYLON.Vector3.Zero();
  43945. }
  43946. this.inputs.checkInputs();
  43947. _super.prototype._checkInputs.call(this);
  43948. };
  43949. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43950. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43951. };
  43952. FreeCamera.prototype._updatePosition = function () {
  43953. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43954. this._collideWithWorld(this.cameraDirection);
  43955. }
  43956. else {
  43957. _super.prototype._updatePosition.call(this);
  43958. }
  43959. };
  43960. FreeCamera.prototype.dispose = function () {
  43961. this.inputs.clear();
  43962. _super.prototype.dispose.call(this);
  43963. };
  43964. FreeCamera.prototype.getClassName = function () {
  43965. return "FreeCamera";
  43966. };
  43967. __decorate([
  43968. BABYLON.serializeAsVector3()
  43969. ], FreeCamera.prototype, "ellipsoid", void 0);
  43970. __decorate([
  43971. BABYLON.serializeAsVector3()
  43972. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43973. __decorate([
  43974. BABYLON.serialize()
  43975. ], FreeCamera.prototype, "checkCollisions", void 0);
  43976. __decorate([
  43977. BABYLON.serialize()
  43978. ], FreeCamera.prototype, "applyGravity", void 0);
  43979. return FreeCamera;
  43980. }(BABYLON.TargetCamera));
  43981. BABYLON.FreeCamera = FreeCamera;
  43982. })(BABYLON || (BABYLON = {}));
  43983. //# sourceMappingURL=babylon.freeCamera.js.map
  43984. var BABYLON;
  43985. (function (BABYLON) {
  43986. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43987. function ArcRotateCameraKeyboardMoveInput() {
  43988. this._keys = new Array();
  43989. this.keysUp = [38];
  43990. this.keysDown = [40];
  43991. this.keysLeft = [37];
  43992. this.keysRight = [39];
  43993. this.keysReset = [220];
  43994. this.panningSensibility = 50.0;
  43995. this.zoomingSensibility = 25.0;
  43996. this.useAltToZoom = true;
  43997. }
  43998. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43999. var _this = this;
  44000. if (this._onCanvasBlurObserver) {
  44001. return;
  44002. }
  44003. this._scene = this.camera.getScene();
  44004. this._engine = this._scene.getEngine();
  44005. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44006. _this._keys = [];
  44007. });
  44008. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44009. var evt = info.event;
  44010. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44011. _this._ctrlPressed = evt.ctrlKey;
  44012. _this._altPressed = evt.altKey;
  44013. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44014. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44015. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44016. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44017. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44018. var index = _this._keys.indexOf(evt.keyCode);
  44019. if (index === -1) {
  44020. _this._keys.push(evt.keyCode);
  44021. }
  44022. if (evt.preventDefault) {
  44023. if (!noPreventDefault) {
  44024. evt.preventDefault();
  44025. }
  44026. }
  44027. }
  44028. }
  44029. else {
  44030. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44031. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44032. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44033. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44034. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44035. var index = _this._keys.indexOf(evt.keyCode);
  44036. if (index >= 0) {
  44037. _this._keys.splice(index, 1);
  44038. }
  44039. if (evt.preventDefault) {
  44040. if (!noPreventDefault) {
  44041. evt.preventDefault();
  44042. }
  44043. }
  44044. }
  44045. }
  44046. });
  44047. };
  44048. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44049. if (this._scene) {
  44050. if (this._onKeyboardObserver) {
  44051. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44052. }
  44053. if (this._onCanvasBlurObserver) {
  44054. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44055. }
  44056. this._onKeyboardObserver = null;
  44057. this._onCanvasBlurObserver = null;
  44058. }
  44059. this._keys = [];
  44060. };
  44061. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44062. if (this._onKeyboardObserver) {
  44063. var camera = this.camera;
  44064. for (var index = 0; index < this._keys.length; index++) {
  44065. var keyCode = this._keys[index];
  44066. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44067. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44068. camera.inertialPanningX -= 1 / this.panningSensibility;
  44069. }
  44070. else {
  44071. camera.inertialAlphaOffset -= 0.01;
  44072. }
  44073. }
  44074. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44075. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44076. camera.inertialPanningY += 1 / this.panningSensibility;
  44077. }
  44078. else if (this._altPressed && this.useAltToZoom) {
  44079. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44080. }
  44081. else {
  44082. camera.inertialBetaOffset -= 0.01;
  44083. }
  44084. }
  44085. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44086. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44087. camera.inertialPanningX += 1 / this.panningSensibility;
  44088. }
  44089. else {
  44090. camera.inertialAlphaOffset += 0.01;
  44091. }
  44092. }
  44093. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44094. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44095. camera.inertialPanningY -= 1 / this.panningSensibility;
  44096. }
  44097. else if (this._altPressed && this.useAltToZoom) {
  44098. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44099. }
  44100. else {
  44101. camera.inertialBetaOffset += 0.01;
  44102. }
  44103. }
  44104. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44105. camera.restoreState();
  44106. }
  44107. }
  44108. }
  44109. };
  44110. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44111. return "ArcRotateCameraKeyboardMoveInput";
  44112. };
  44113. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44114. return "keyboard";
  44115. };
  44116. __decorate([
  44117. BABYLON.serialize()
  44118. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44119. __decorate([
  44120. BABYLON.serialize()
  44121. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44122. __decorate([
  44123. BABYLON.serialize()
  44124. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44125. __decorate([
  44126. BABYLON.serialize()
  44127. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44128. __decorate([
  44129. BABYLON.serialize()
  44130. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44131. __decorate([
  44132. BABYLON.serialize()
  44133. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44134. __decorate([
  44135. BABYLON.serialize()
  44136. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44137. __decorate([
  44138. BABYLON.serialize()
  44139. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44140. return ArcRotateCameraKeyboardMoveInput;
  44141. }());
  44142. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44143. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44144. })(BABYLON || (BABYLON = {}));
  44145. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44146. var BABYLON;
  44147. (function (BABYLON) {
  44148. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44149. function ArcRotateCameraMouseWheelInput() {
  44150. this.wheelPrecision = 3.0;
  44151. /**
  44152. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44153. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44154. */
  44155. this.wheelDeltaPercentage = 0;
  44156. }
  44157. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44158. var _this = this;
  44159. this._wheel = function (p, s) {
  44160. //sanity check - this should be a PointerWheel event.
  44161. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44162. return;
  44163. var event = p.event;
  44164. var delta = 0;
  44165. if (event.wheelDelta) {
  44166. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44167. }
  44168. else if (event.detail) {
  44169. delta = -event.detail / _this.wheelPrecision;
  44170. }
  44171. if (delta)
  44172. _this.camera.inertialRadiusOffset += delta;
  44173. if (event.preventDefault) {
  44174. if (!noPreventDefault) {
  44175. event.preventDefault();
  44176. }
  44177. }
  44178. };
  44179. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44180. };
  44181. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44182. if (this._observer && element) {
  44183. this.camera.getScene().onPointerObservable.remove(this._observer);
  44184. this._observer = null;
  44185. this._wheel = null;
  44186. }
  44187. };
  44188. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44189. return "ArcRotateCameraMouseWheelInput";
  44190. };
  44191. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44192. return "mousewheel";
  44193. };
  44194. __decorate([
  44195. BABYLON.serialize()
  44196. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44197. __decorate([
  44198. BABYLON.serialize()
  44199. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44200. return ArcRotateCameraMouseWheelInput;
  44201. }());
  44202. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44203. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44204. })(BABYLON || (BABYLON = {}));
  44205. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44206. var BABYLON;
  44207. (function (BABYLON) {
  44208. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44209. function ArcRotateCameraPointersInput() {
  44210. this.buttons = [0, 1, 2];
  44211. this.angularSensibilityX = 1000.0;
  44212. this.angularSensibilityY = 1000.0;
  44213. this.pinchPrecision = 12.0;
  44214. /**
  44215. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44216. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44217. */
  44218. this.pinchDeltaPercentage = 0;
  44219. this.panningSensibility = 1000.0;
  44220. this.multiTouchPanning = true;
  44221. this.multiTouchPanAndZoom = true;
  44222. this._isPanClick = false;
  44223. this.pinchInwards = true;
  44224. }
  44225. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44226. var _this = this;
  44227. var engine = this.camera.getEngine();
  44228. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44229. var pointA = null;
  44230. var pointB = null;
  44231. var previousPinchSquaredDistance = 0;
  44232. var initialDistance = 0;
  44233. var twoFingerActivityCount = 0;
  44234. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44235. this._pointerInput = function (p, s) {
  44236. var evt = p.event;
  44237. var isTouch = p.event.pointerType === "touch";
  44238. if (engine.isInVRExclusivePointerMode) {
  44239. return;
  44240. }
  44241. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44242. return;
  44243. }
  44244. var srcElement = (evt.srcElement || evt.target);
  44245. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44246. try {
  44247. srcElement.setPointerCapture(evt.pointerId);
  44248. }
  44249. catch (e) {
  44250. //Nothing to do with the error. Execution will continue.
  44251. }
  44252. // Manage panning with pan button click
  44253. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44254. // manage pointers
  44255. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44256. if (pointA === null) {
  44257. pointA = cacheSoloPointer;
  44258. }
  44259. else if (pointB === null) {
  44260. pointB = cacheSoloPointer;
  44261. }
  44262. if (!noPreventDefault) {
  44263. evt.preventDefault();
  44264. element.focus();
  44265. }
  44266. }
  44267. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44268. _this.camera.restoreState();
  44269. }
  44270. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44271. try {
  44272. srcElement.releasePointerCapture(evt.pointerId);
  44273. }
  44274. catch (e) {
  44275. //Nothing to do with the error.
  44276. }
  44277. cacheSoloPointer = null;
  44278. previousPinchSquaredDistance = 0;
  44279. previousMultiTouchPanPosition.isPaning = false;
  44280. previousMultiTouchPanPosition.isPinching = false;
  44281. twoFingerActivityCount = 0;
  44282. initialDistance = 0;
  44283. if (!isTouch) {
  44284. pointB = null; // Mouse and pen are mono pointer
  44285. }
  44286. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44287. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44288. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44289. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44290. if (engine.badOS) {
  44291. pointA = pointB = null;
  44292. }
  44293. else {
  44294. //only remove the impacted pointer in case of multitouch allowing on most
  44295. //platforms switching from rotate to zoom and pan seamlessly.
  44296. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44297. pointA = pointB;
  44298. pointB = null;
  44299. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44300. }
  44301. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44302. pointB = null;
  44303. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44304. }
  44305. else {
  44306. pointA = pointB = null;
  44307. }
  44308. }
  44309. if (!noPreventDefault) {
  44310. evt.preventDefault();
  44311. }
  44312. }
  44313. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44314. if (!noPreventDefault) {
  44315. evt.preventDefault();
  44316. }
  44317. // One button down
  44318. if (pointA && pointB === null && cacheSoloPointer) {
  44319. if (_this.panningSensibility !== 0 &&
  44320. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44321. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44322. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44323. }
  44324. else {
  44325. var offsetX = evt.clientX - cacheSoloPointer.x;
  44326. var offsetY = evt.clientY - cacheSoloPointer.y;
  44327. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44328. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44329. }
  44330. cacheSoloPointer.x = evt.clientX;
  44331. cacheSoloPointer.y = evt.clientY;
  44332. }
  44333. else if (pointA && pointB) {
  44334. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44335. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44336. ed.x = evt.clientX;
  44337. ed.y = evt.clientY;
  44338. var direction = _this.pinchInwards ? 1 : -1;
  44339. var distX = pointA.x - pointB.x;
  44340. var distY = pointA.y - pointB.y;
  44341. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44342. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44343. if (previousPinchSquaredDistance === 0) {
  44344. initialDistance = pinchDistance;
  44345. previousPinchSquaredDistance = pinchSquaredDistance;
  44346. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44347. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44348. return;
  44349. }
  44350. if (_this.multiTouchPanAndZoom) {
  44351. if (_this.pinchDeltaPercentage) {
  44352. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44353. }
  44354. else {
  44355. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44356. (_this.pinchPrecision *
  44357. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44358. direction);
  44359. }
  44360. if (_this.panningSensibility !== 0) {
  44361. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44362. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44363. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44364. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44365. previousMultiTouchPanPosition.x = pointersCenterX;
  44366. previousMultiTouchPanPosition.y = pointersCenterY;
  44367. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44368. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44369. }
  44370. }
  44371. else {
  44372. twoFingerActivityCount++;
  44373. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44374. if (_this.pinchDeltaPercentage) {
  44375. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44376. }
  44377. else {
  44378. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44379. (_this.pinchPrecision *
  44380. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44381. direction);
  44382. }
  44383. previousMultiTouchPanPosition.isPaning = false;
  44384. previousMultiTouchPanPosition.isPinching = true;
  44385. }
  44386. else {
  44387. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44388. if (!previousMultiTouchPanPosition.isPaning) {
  44389. previousMultiTouchPanPosition.isPaning = true;
  44390. previousMultiTouchPanPosition.isPinching = false;
  44391. previousMultiTouchPanPosition.x = ed.x;
  44392. previousMultiTouchPanPosition.y = ed.y;
  44393. return;
  44394. }
  44395. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44396. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44397. }
  44398. }
  44399. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44400. previousMultiTouchPanPosition.x = ed.x;
  44401. previousMultiTouchPanPosition.y = ed.y;
  44402. }
  44403. }
  44404. previousPinchSquaredDistance = pinchSquaredDistance;
  44405. }
  44406. }
  44407. };
  44408. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44409. this._onContextMenu = function (evt) {
  44410. evt.preventDefault();
  44411. };
  44412. if (!this.camera._useCtrlForPanning) {
  44413. element.addEventListener("contextmenu", this._onContextMenu, false);
  44414. }
  44415. this._onLostFocus = function () {
  44416. //this._keys = [];
  44417. pointA = pointB = null;
  44418. previousPinchSquaredDistance = 0;
  44419. previousMultiTouchPanPosition.isPaning = false;
  44420. previousMultiTouchPanPosition.isPinching = false;
  44421. twoFingerActivityCount = 0;
  44422. cacheSoloPointer = null;
  44423. initialDistance = 0;
  44424. };
  44425. this._onMouseMove = function (evt) {
  44426. if (!engine.isPointerLock) {
  44427. return;
  44428. }
  44429. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44430. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44431. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44432. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44433. if (!noPreventDefault) {
  44434. evt.preventDefault();
  44435. }
  44436. };
  44437. this._onGestureStart = function (e) {
  44438. if (window.MSGesture === undefined) {
  44439. return;
  44440. }
  44441. if (!_this._MSGestureHandler) {
  44442. _this._MSGestureHandler = new MSGesture();
  44443. _this._MSGestureHandler.target = element;
  44444. }
  44445. _this._MSGestureHandler.addPointer(e.pointerId);
  44446. };
  44447. this._onGesture = function (e) {
  44448. _this.camera.radius *= e.scale;
  44449. if (e.preventDefault) {
  44450. if (!noPreventDefault) {
  44451. e.stopPropagation();
  44452. e.preventDefault();
  44453. }
  44454. }
  44455. };
  44456. element.addEventListener("mousemove", this._onMouseMove, false);
  44457. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44458. element.addEventListener("MSGestureChange", this._onGesture, false);
  44459. BABYLON.Tools.RegisterTopRootEvents([
  44460. { name: "blur", handler: this._onLostFocus }
  44461. ]);
  44462. };
  44463. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44464. if (this._onLostFocus) {
  44465. BABYLON.Tools.UnregisterTopRootEvents([
  44466. { name: "blur", handler: this._onLostFocus }
  44467. ]);
  44468. }
  44469. if (element && this._observer) {
  44470. this.camera.getScene().onPointerObservable.remove(this._observer);
  44471. this._observer = null;
  44472. if (this._onContextMenu) {
  44473. element.removeEventListener("contextmenu", this._onContextMenu);
  44474. }
  44475. if (this._onMouseMove) {
  44476. element.removeEventListener("mousemove", this._onMouseMove);
  44477. }
  44478. if (this._onGestureStart) {
  44479. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44480. }
  44481. if (this._onGesture) {
  44482. element.removeEventListener("MSGestureChange", this._onGesture);
  44483. }
  44484. this._isPanClick = false;
  44485. this.pinchInwards = true;
  44486. this._onMouseMove = null;
  44487. this._onGestureStart = null;
  44488. this._onGesture = null;
  44489. this._MSGestureHandler = null;
  44490. this._onLostFocus = null;
  44491. this._onContextMenu = null;
  44492. }
  44493. };
  44494. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44495. return "ArcRotateCameraPointersInput";
  44496. };
  44497. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44498. return "pointers";
  44499. };
  44500. __decorate([
  44501. BABYLON.serialize()
  44502. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44503. __decorate([
  44504. BABYLON.serialize()
  44505. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44506. __decorate([
  44507. BABYLON.serialize()
  44508. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44509. __decorate([
  44510. BABYLON.serialize()
  44511. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44512. __decorate([
  44513. BABYLON.serialize()
  44514. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44515. __decorate([
  44516. BABYLON.serialize()
  44517. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44518. __decorate([
  44519. BABYLON.serialize()
  44520. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44521. __decorate([
  44522. BABYLON.serialize()
  44523. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44524. return ArcRotateCameraPointersInput;
  44525. }());
  44526. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44527. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44528. })(BABYLON || (BABYLON = {}));
  44529. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44530. var BABYLON;
  44531. (function (BABYLON) {
  44532. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44533. __extends(ArcRotateCameraInputsManager, _super);
  44534. function ArcRotateCameraInputsManager(camera) {
  44535. return _super.call(this, camera) || this;
  44536. }
  44537. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44538. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44539. return this;
  44540. };
  44541. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44542. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44543. return this;
  44544. };
  44545. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44546. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44547. return this;
  44548. };
  44549. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44550. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44551. return this;
  44552. };
  44553. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44554. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44555. return this;
  44556. };
  44557. return ArcRotateCameraInputsManager;
  44558. }(BABYLON.CameraInputsManager));
  44559. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44560. })(BABYLON || (BABYLON = {}));
  44561. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44562. var BABYLON;
  44563. (function (BABYLON) {
  44564. var ArcRotateCamera = /** @class */ (function (_super) {
  44565. __extends(ArcRotateCamera, _super);
  44566. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44567. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44568. _this.inertialAlphaOffset = 0;
  44569. _this.inertialBetaOffset = 0;
  44570. _this.inertialRadiusOffset = 0;
  44571. _this.lowerAlphaLimit = null;
  44572. _this.upperAlphaLimit = null;
  44573. _this.lowerBetaLimit = 0.01;
  44574. _this.upperBetaLimit = Math.PI;
  44575. _this.lowerRadiusLimit = null;
  44576. _this.upperRadiusLimit = null;
  44577. _this.inertialPanningX = 0;
  44578. _this.inertialPanningY = 0;
  44579. _this.pinchToPanMaxDistance = 20;
  44580. _this.panningDistanceLimit = null;
  44581. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44582. _this.panningInertia = 0.9;
  44583. //-- end properties for backward compatibility for inputs
  44584. _this.zoomOnFactor = 1;
  44585. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44586. _this.allowUpsideDown = true;
  44587. _this._viewMatrix = new BABYLON.Matrix();
  44588. // Panning
  44589. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44590. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44591. _this.checkCollisions = false;
  44592. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44593. _this._previousPosition = BABYLON.Vector3.Zero();
  44594. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44595. _this._newPosition = BABYLON.Vector3.Zero();
  44596. _this._computationVector = BABYLON.Vector3.Zero();
  44597. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44598. if (collidedMesh === void 0) { collidedMesh = null; }
  44599. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44600. newPosition.multiplyInPlace(_this._collider._radius);
  44601. }
  44602. if (!collidedMesh) {
  44603. _this._previousPosition.copyFrom(_this.position);
  44604. }
  44605. else {
  44606. _this.setPosition(newPosition);
  44607. if (_this.onCollide) {
  44608. _this.onCollide(collidedMesh);
  44609. }
  44610. }
  44611. // Recompute because of constraints
  44612. var cosa = Math.cos(_this.alpha);
  44613. var sina = Math.sin(_this.alpha);
  44614. var cosb = Math.cos(_this.beta);
  44615. var sinb = Math.sin(_this.beta);
  44616. if (sinb === 0) {
  44617. sinb = 0.0001;
  44618. }
  44619. var target = _this._getTargetPosition();
  44620. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44621. target.addToRef(_this._computationVector, _this._newPosition);
  44622. _this.position.copyFrom(_this._newPosition);
  44623. var up = _this.upVector;
  44624. if (_this.allowUpsideDown && _this.beta < 0) {
  44625. up = up.clone();
  44626. up = up.negate();
  44627. }
  44628. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44629. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44630. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44631. _this._collisionTriggered = false;
  44632. };
  44633. _this._target = BABYLON.Vector3.Zero();
  44634. if (target) {
  44635. _this.setTarget(target);
  44636. }
  44637. _this.alpha = alpha;
  44638. _this.beta = beta;
  44639. _this.radius = radius;
  44640. _this.getViewMatrix();
  44641. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44642. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44643. return _this;
  44644. }
  44645. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44646. get: function () {
  44647. return this._target;
  44648. },
  44649. set: function (value) {
  44650. this.setTarget(value);
  44651. },
  44652. enumerable: true,
  44653. configurable: true
  44654. });
  44655. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44656. //-- begin properties for backward compatibility for inputs
  44657. get: function () {
  44658. var pointers = this.inputs.attached["pointers"];
  44659. if (pointers)
  44660. return pointers.angularSensibilityX;
  44661. return 0;
  44662. },
  44663. set: function (value) {
  44664. var pointers = this.inputs.attached["pointers"];
  44665. if (pointers) {
  44666. pointers.angularSensibilityX = value;
  44667. }
  44668. },
  44669. enumerable: true,
  44670. configurable: true
  44671. });
  44672. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44673. get: function () {
  44674. var pointers = this.inputs.attached["pointers"];
  44675. if (pointers)
  44676. return pointers.angularSensibilityY;
  44677. return 0;
  44678. },
  44679. set: function (value) {
  44680. var pointers = this.inputs.attached["pointers"];
  44681. if (pointers) {
  44682. pointers.angularSensibilityY = value;
  44683. }
  44684. },
  44685. enumerable: true,
  44686. configurable: true
  44687. });
  44688. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44689. get: function () {
  44690. var pointers = this.inputs.attached["pointers"];
  44691. if (pointers)
  44692. return pointers.pinchPrecision;
  44693. return 0;
  44694. },
  44695. set: function (value) {
  44696. var pointers = this.inputs.attached["pointers"];
  44697. if (pointers) {
  44698. pointers.pinchPrecision = value;
  44699. }
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44705. get: function () {
  44706. var pointers = this.inputs.attached["pointers"];
  44707. if (pointers)
  44708. return pointers.pinchDeltaPercentage;
  44709. return 0;
  44710. },
  44711. set: function (value) {
  44712. var pointers = this.inputs.attached["pointers"];
  44713. if (pointers) {
  44714. pointers.pinchDeltaPercentage = value;
  44715. }
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44721. get: function () {
  44722. var pointers = this.inputs.attached["pointers"];
  44723. if (pointers)
  44724. return pointers.panningSensibility;
  44725. return 0;
  44726. },
  44727. set: function (value) {
  44728. var pointers = this.inputs.attached["pointers"];
  44729. if (pointers) {
  44730. pointers.panningSensibility = value;
  44731. }
  44732. },
  44733. enumerable: true,
  44734. configurable: true
  44735. });
  44736. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44737. get: function () {
  44738. var keyboard = this.inputs.attached["keyboard"];
  44739. if (keyboard)
  44740. return keyboard.keysUp;
  44741. return [];
  44742. },
  44743. set: function (value) {
  44744. var keyboard = this.inputs.attached["keyboard"];
  44745. if (keyboard)
  44746. keyboard.keysUp = value;
  44747. },
  44748. enumerable: true,
  44749. configurable: true
  44750. });
  44751. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44752. get: function () {
  44753. var keyboard = this.inputs.attached["keyboard"];
  44754. if (keyboard)
  44755. return keyboard.keysDown;
  44756. return [];
  44757. },
  44758. set: function (value) {
  44759. var keyboard = this.inputs.attached["keyboard"];
  44760. if (keyboard)
  44761. keyboard.keysDown = value;
  44762. },
  44763. enumerable: true,
  44764. configurable: true
  44765. });
  44766. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44767. get: function () {
  44768. var keyboard = this.inputs.attached["keyboard"];
  44769. if (keyboard)
  44770. return keyboard.keysLeft;
  44771. return [];
  44772. },
  44773. set: function (value) {
  44774. var keyboard = this.inputs.attached["keyboard"];
  44775. if (keyboard)
  44776. keyboard.keysLeft = value;
  44777. },
  44778. enumerable: true,
  44779. configurable: true
  44780. });
  44781. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44782. get: function () {
  44783. var keyboard = this.inputs.attached["keyboard"];
  44784. if (keyboard)
  44785. return keyboard.keysRight;
  44786. return [];
  44787. },
  44788. set: function (value) {
  44789. var keyboard = this.inputs.attached["keyboard"];
  44790. if (keyboard)
  44791. keyboard.keysRight = value;
  44792. },
  44793. enumerable: true,
  44794. configurable: true
  44795. });
  44796. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44797. get: function () {
  44798. var mousewheel = this.inputs.attached["mousewheel"];
  44799. if (mousewheel)
  44800. return mousewheel.wheelPrecision;
  44801. return 0;
  44802. },
  44803. set: function (value) {
  44804. var mousewheel = this.inputs.attached["mousewheel"];
  44805. if (mousewheel)
  44806. mousewheel.wheelPrecision = value;
  44807. },
  44808. enumerable: true,
  44809. configurable: true
  44810. });
  44811. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44812. get: function () {
  44813. var mousewheel = this.inputs.attached["mousewheel"];
  44814. if (mousewheel)
  44815. return mousewheel.wheelDeltaPercentage;
  44816. return 0;
  44817. },
  44818. set: function (value) {
  44819. var mousewheel = this.inputs.attached["mousewheel"];
  44820. if (mousewheel)
  44821. mousewheel.wheelDeltaPercentage = value;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44827. get: function () {
  44828. return this._bouncingBehavior;
  44829. },
  44830. enumerable: true,
  44831. configurable: true
  44832. });
  44833. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44834. get: function () {
  44835. return this._bouncingBehavior != null;
  44836. },
  44837. set: function (value) {
  44838. if (value === this.useBouncingBehavior) {
  44839. return;
  44840. }
  44841. if (value) {
  44842. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44843. this.addBehavior(this._bouncingBehavior);
  44844. }
  44845. else if (this._bouncingBehavior) {
  44846. this.removeBehavior(this._bouncingBehavior);
  44847. this._bouncingBehavior = null;
  44848. }
  44849. },
  44850. enumerable: true,
  44851. configurable: true
  44852. });
  44853. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44854. get: function () {
  44855. return this._framingBehavior;
  44856. },
  44857. enumerable: true,
  44858. configurable: true
  44859. });
  44860. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44861. get: function () {
  44862. return this._framingBehavior != null;
  44863. },
  44864. set: function (value) {
  44865. if (value === this.useFramingBehavior) {
  44866. return;
  44867. }
  44868. if (value) {
  44869. this._framingBehavior = new BABYLON.FramingBehavior();
  44870. this.addBehavior(this._framingBehavior);
  44871. }
  44872. else if (this._framingBehavior) {
  44873. this.removeBehavior(this._framingBehavior);
  44874. this._framingBehavior = null;
  44875. }
  44876. },
  44877. enumerable: true,
  44878. configurable: true
  44879. });
  44880. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44881. get: function () {
  44882. return this._autoRotationBehavior;
  44883. },
  44884. enumerable: true,
  44885. configurable: true
  44886. });
  44887. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44888. get: function () {
  44889. return this._autoRotationBehavior != null;
  44890. },
  44891. set: function (value) {
  44892. if (value === this.useAutoRotationBehavior) {
  44893. return;
  44894. }
  44895. if (value) {
  44896. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44897. this.addBehavior(this._autoRotationBehavior);
  44898. }
  44899. else if (this._autoRotationBehavior) {
  44900. this.removeBehavior(this._autoRotationBehavior);
  44901. this._autoRotationBehavior = null;
  44902. }
  44903. },
  44904. enumerable: true,
  44905. configurable: true
  44906. });
  44907. // Cache
  44908. ArcRotateCamera.prototype._initCache = function () {
  44909. _super.prototype._initCache.call(this);
  44910. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44911. this._cache.alpha = undefined;
  44912. this._cache.beta = undefined;
  44913. this._cache.radius = undefined;
  44914. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44915. };
  44916. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44917. if (!ignoreParentClass) {
  44918. _super.prototype._updateCache.call(this);
  44919. }
  44920. this._cache._target.copyFrom(this._getTargetPosition());
  44921. this._cache.alpha = this.alpha;
  44922. this._cache.beta = this.beta;
  44923. this._cache.radius = this.radius;
  44924. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44925. };
  44926. ArcRotateCamera.prototype._getTargetPosition = function () {
  44927. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44928. var pos = this._targetHost.getAbsolutePosition();
  44929. if (this._targetBoundingCenter) {
  44930. pos.addToRef(this._targetBoundingCenter, this._target);
  44931. }
  44932. else {
  44933. this._target.copyFrom(pos);
  44934. }
  44935. }
  44936. var lockedTargetPosition = this._getLockedTargetPosition();
  44937. if (lockedTargetPosition) {
  44938. return lockedTargetPosition;
  44939. }
  44940. return this._target;
  44941. };
  44942. ArcRotateCamera.prototype.storeState = function () {
  44943. this._storedAlpha = this.alpha;
  44944. this._storedBeta = this.beta;
  44945. this._storedRadius = this.radius;
  44946. this._storedTarget = this._getTargetPosition().clone();
  44947. return _super.prototype.storeState.call(this);
  44948. };
  44949. /**
  44950. * Restored camera state. You must call storeState() first
  44951. */
  44952. ArcRotateCamera.prototype._restoreStateValues = function () {
  44953. if (!_super.prototype._restoreStateValues.call(this)) {
  44954. return false;
  44955. }
  44956. this.alpha = this._storedAlpha;
  44957. this.beta = this._storedBeta;
  44958. this.radius = this._storedRadius;
  44959. this.setTarget(this._storedTarget.clone());
  44960. this.inertialAlphaOffset = 0;
  44961. this.inertialBetaOffset = 0;
  44962. this.inertialRadiusOffset = 0;
  44963. this.inertialPanningX = 0;
  44964. this.inertialPanningY = 0;
  44965. return true;
  44966. };
  44967. // Synchronized
  44968. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44969. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44970. return false;
  44971. return this._cache._target.equals(this._getTargetPosition())
  44972. && this._cache.alpha === this.alpha
  44973. && this._cache.beta === this.beta
  44974. && this._cache.radius === this.radius
  44975. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44976. };
  44977. // Methods
  44978. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44979. var _this = this;
  44980. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44981. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44982. this._useCtrlForPanning = useCtrlForPanning;
  44983. this._panningMouseButton = panningMouseButton;
  44984. this.inputs.attachElement(element, noPreventDefault);
  44985. this._reset = function () {
  44986. _this.inertialAlphaOffset = 0;
  44987. _this.inertialBetaOffset = 0;
  44988. _this.inertialRadiusOffset = 0;
  44989. _this.inertialPanningX = 0;
  44990. _this.inertialPanningY = 0;
  44991. };
  44992. };
  44993. ArcRotateCamera.prototype.detachControl = function (element) {
  44994. this.inputs.detachElement(element);
  44995. if (this._reset) {
  44996. this._reset();
  44997. }
  44998. };
  44999. ArcRotateCamera.prototype._checkInputs = function () {
  45000. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45001. if (this._collisionTriggered) {
  45002. return;
  45003. }
  45004. this.inputs.checkInputs();
  45005. // Inertia
  45006. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45007. if (this.getScene().useRightHandedSystem) {
  45008. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45009. }
  45010. else {
  45011. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45012. }
  45013. this.beta += this.inertialBetaOffset;
  45014. this.radius -= this.inertialRadiusOffset;
  45015. this.inertialAlphaOffset *= this.inertia;
  45016. this.inertialBetaOffset *= this.inertia;
  45017. this.inertialRadiusOffset *= this.inertia;
  45018. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45019. this.inertialAlphaOffset = 0;
  45020. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45021. this.inertialBetaOffset = 0;
  45022. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45023. this.inertialRadiusOffset = 0;
  45024. }
  45025. // Panning inertia
  45026. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45027. if (!this._localDirection) {
  45028. this._localDirection = BABYLON.Vector3.Zero();
  45029. this._transformedDirection = BABYLON.Vector3.Zero();
  45030. }
  45031. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45032. this._localDirection.multiplyInPlace(this.panningAxis);
  45033. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45034. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45035. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45036. if (!this.panningAxis.y) {
  45037. this._transformedDirection.y = 0;
  45038. }
  45039. if (!this._targetHost) {
  45040. if (this.panningDistanceLimit) {
  45041. this._transformedDirection.addInPlace(this._target);
  45042. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45043. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45044. this._target.copyFrom(this._transformedDirection);
  45045. }
  45046. }
  45047. else {
  45048. this._target.addInPlace(this._transformedDirection);
  45049. }
  45050. }
  45051. this.inertialPanningX *= this.panningInertia;
  45052. this.inertialPanningY *= this.panningInertia;
  45053. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45054. this.inertialPanningX = 0;
  45055. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45056. this.inertialPanningY = 0;
  45057. }
  45058. // Limits
  45059. this._checkLimits();
  45060. _super.prototype._checkInputs.call(this);
  45061. };
  45062. ArcRotateCamera.prototype._checkLimits = function () {
  45063. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45064. if (this.allowUpsideDown && this.beta > Math.PI) {
  45065. this.beta = this.beta - (2 * Math.PI);
  45066. }
  45067. }
  45068. else {
  45069. if (this.beta < this.lowerBetaLimit) {
  45070. this.beta = this.lowerBetaLimit;
  45071. }
  45072. }
  45073. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45074. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45075. this.beta = this.beta + (2 * Math.PI);
  45076. }
  45077. }
  45078. else {
  45079. if (this.beta > this.upperBetaLimit) {
  45080. this.beta = this.upperBetaLimit;
  45081. }
  45082. }
  45083. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45084. this.alpha = this.lowerAlphaLimit;
  45085. }
  45086. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45087. this.alpha = this.upperAlphaLimit;
  45088. }
  45089. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45090. this.radius = this.lowerRadiusLimit;
  45091. }
  45092. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45093. this.radius = this.upperRadiusLimit;
  45094. }
  45095. };
  45096. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45097. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45098. this.radius = this._computationVector.length();
  45099. if (this.radius === 0) {
  45100. this.radius = 0.0001; // Just to avoid division by zero
  45101. }
  45102. // Alpha
  45103. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45104. if (this._computationVector.z < 0) {
  45105. this.alpha = 2 * Math.PI - this.alpha;
  45106. }
  45107. // Beta
  45108. this.beta = Math.acos(this._computationVector.y / this.radius);
  45109. this._checkLimits();
  45110. };
  45111. ArcRotateCamera.prototype.setPosition = function (position) {
  45112. if (this.position.equals(position)) {
  45113. return;
  45114. }
  45115. this.position.copyFrom(position);
  45116. this.rebuildAnglesAndRadius();
  45117. };
  45118. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45119. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45120. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45121. if (target.getBoundingInfo) {
  45122. if (toBoundingCenter) {
  45123. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45124. }
  45125. else {
  45126. this._targetBoundingCenter = null;
  45127. }
  45128. this._targetHost = target;
  45129. this._target = this._getTargetPosition();
  45130. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45131. }
  45132. else {
  45133. var newTarget = target;
  45134. var currentTarget = this._getTargetPosition();
  45135. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45136. return;
  45137. }
  45138. this._targetHost = null;
  45139. this._target = newTarget;
  45140. this._targetBoundingCenter = null;
  45141. this.onMeshTargetChangedObservable.notifyObservers(null);
  45142. }
  45143. this.rebuildAnglesAndRadius();
  45144. };
  45145. ArcRotateCamera.prototype._getViewMatrix = function () {
  45146. // Compute
  45147. var cosa = Math.cos(this.alpha);
  45148. var sina = Math.sin(this.alpha);
  45149. var cosb = Math.cos(this.beta);
  45150. var sinb = Math.sin(this.beta);
  45151. if (sinb === 0) {
  45152. sinb = 0.0001;
  45153. }
  45154. var target = this._getTargetPosition();
  45155. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45156. target.addToRef(this._computationVector, this._newPosition);
  45157. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45158. if (!this._collider) {
  45159. this._collider = new BABYLON.Collider();
  45160. }
  45161. this._collider._radius = this.collisionRadius;
  45162. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45163. this._collisionTriggered = true;
  45164. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45165. }
  45166. else {
  45167. this.position.copyFrom(this._newPosition);
  45168. var up = this.upVector;
  45169. if (this.allowUpsideDown && sinb < 0) {
  45170. up = up.clone();
  45171. up = up.negate();
  45172. }
  45173. if (this.getScene().useRightHandedSystem) {
  45174. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45175. }
  45176. else {
  45177. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45178. }
  45179. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45180. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45181. }
  45182. this._currentTarget = target;
  45183. return this._viewMatrix;
  45184. };
  45185. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45186. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45187. meshes = meshes || this.getScene().meshes;
  45188. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45189. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45190. this.radius = distance * this.zoomOnFactor;
  45191. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45192. };
  45193. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45194. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45195. var meshesOrMinMaxVector;
  45196. var distance;
  45197. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45198. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45199. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45200. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45201. }
  45202. else {
  45203. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45204. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45205. distance = minMaxVectorAndDistance.distance;
  45206. }
  45207. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45208. if (!doNotUpdateMaxZ) {
  45209. this.maxZ = distance * 2;
  45210. }
  45211. };
  45212. /**
  45213. * @override
  45214. * Override Camera.createRigCamera
  45215. */
  45216. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45217. var alphaShift = 0;
  45218. switch (this.cameraRigMode) {
  45219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45220. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45222. case BABYLON.Camera.RIG_MODE_VR:
  45223. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45224. break;
  45225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45226. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45227. break;
  45228. }
  45229. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45230. rigCam._cameraRigParams = {};
  45231. return rigCam;
  45232. };
  45233. /**
  45234. * @override
  45235. * Override Camera._updateRigCameras
  45236. */
  45237. ArcRotateCamera.prototype._updateRigCameras = function () {
  45238. var camLeft = this._rigCameras[0];
  45239. var camRight = this._rigCameras[1];
  45240. camLeft.beta = camRight.beta = this.beta;
  45241. camLeft.radius = camRight.radius = this.radius;
  45242. switch (this.cameraRigMode) {
  45243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45246. case BABYLON.Camera.RIG_MODE_VR:
  45247. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45248. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45249. break;
  45250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45251. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45252. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45253. break;
  45254. }
  45255. _super.prototype._updateRigCameras.call(this);
  45256. };
  45257. ArcRotateCamera.prototype.dispose = function () {
  45258. this.inputs.clear();
  45259. _super.prototype.dispose.call(this);
  45260. };
  45261. ArcRotateCamera.prototype.getClassName = function () {
  45262. return "ArcRotateCamera";
  45263. };
  45264. __decorate([
  45265. BABYLON.serialize()
  45266. ], ArcRotateCamera.prototype, "alpha", void 0);
  45267. __decorate([
  45268. BABYLON.serialize()
  45269. ], ArcRotateCamera.prototype, "beta", void 0);
  45270. __decorate([
  45271. BABYLON.serialize()
  45272. ], ArcRotateCamera.prototype, "radius", void 0);
  45273. __decorate([
  45274. BABYLON.serializeAsVector3("target")
  45275. ], ArcRotateCamera.prototype, "_target", void 0);
  45276. __decorate([
  45277. BABYLON.serialize()
  45278. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45279. __decorate([
  45280. BABYLON.serialize()
  45281. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45282. __decorate([
  45283. BABYLON.serialize()
  45284. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45285. __decorate([
  45286. BABYLON.serialize()
  45287. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45288. __decorate([
  45289. BABYLON.serialize()
  45290. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45291. __decorate([
  45292. BABYLON.serialize()
  45293. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45294. __decorate([
  45295. BABYLON.serialize()
  45296. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45297. __decorate([
  45298. BABYLON.serialize()
  45299. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45300. __decorate([
  45301. BABYLON.serialize()
  45302. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45303. __decorate([
  45304. BABYLON.serialize()
  45305. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45306. __decorate([
  45307. BABYLON.serialize()
  45308. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45309. __decorate([
  45310. BABYLON.serialize()
  45311. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45312. __decorate([
  45313. BABYLON.serialize()
  45314. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45315. __decorate([
  45316. BABYLON.serializeAsVector3()
  45317. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45318. __decorate([
  45319. BABYLON.serialize()
  45320. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45321. __decorate([
  45322. BABYLON.serialize()
  45323. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45324. __decorate([
  45325. BABYLON.serialize()
  45326. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45327. return ArcRotateCamera;
  45328. }(BABYLON.TargetCamera));
  45329. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45330. })(BABYLON || (BABYLON = {}));
  45331. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45332. var BABYLON;
  45333. (function (BABYLON) {
  45334. /**
  45335. * The HemisphericLight simulates the ambient environment light,
  45336. * so the passed direction is the light reflection direction, not the incoming direction.
  45337. */
  45338. var HemisphericLight = /** @class */ (function (_super) {
  45339. __extends(HemisphericLight, _super);
  45340. /**
  45341. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45342. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45343. * The HemisphericLight can't cast shadows.
  45344. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45345. * @param name The friendly name of the light
  45346. * @param direction The direction of the light reflection
  45347. * @param scene The scene the light belongs to
  45348. */
  45349. function HemisphericLight(name, direction, scene) {
  45350. var _this = _super.call(this, name, scene) || this;
  45351. /**
  45352. * The groundColor is the light in the opposite direction to the one specified during creation.
  45353. * 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.
  45354. */
  45355. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45356. _this.direction = direction || BABYLON.Vector3.Up();
  45357. return _this;
  45358. }
  45359. HemisphericLight.prototype._buildUniformLayout = function () {
  45360. this._uniformBuffer.addUniform("vLightData", 4);
  45361. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45362. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45363. this._uniformBuffer.addUniform("vLightGround", 3);
  45364. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45365. this._uniformBuffer.addUniform("depthValues", 2);
  45366. this._uniformBuffer.create();
  45367. };
  45368. /**
  45369. * Returns the string "HemisphericLight".
  45370. * @return The class name
  45371. */
  45372. HemisphericLight.prototype.getClassName = function () {
  45373. return "HemisphericLight";
  45374. };
  45375. /**
  45376. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45377. * Returns the updated direction.
  45378. * @param target The target the direction should point to
  45379. * @return The computed direction
  45380. */
  45381. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45382. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45383. return this.direction;
  45384. };
  45385. /**
  45386. * Returns the shadow generator associated to the light.
  45387. * @returns Always null for hemispheric lights because it does not support shadows.
  45388. */
  45389. HemisphericLight.prototype.getShadowGenerator = function () {
  45390. return null;
  45391. };
  45392. /**
  45393. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45394. * @param effect The effect to update
  45395. * @param lightIndex The index of the light in the effect to update
  45396. * @returns The hemispheric light
  45397. */
  45398. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45399. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45400. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45401. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45402. return this;
  45403. };
  45404. /**
  45405. * @ignore internal use only.
  45406. */
  45407. HemisphericLight.prototype._getWorldMatrix = function () {
  45408. if (!this._worldMatrix) {
  45409. this._worldMatrix = BABYLON.Matrix.Identity();
  45410. }
  45411. return this._worldMatrix;
  45412. };
  45413. /**
  45414. * Returns the integer 3.
  45415. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45416. */
  45417. HemisphericLight.prototype.getTypeID = function () {
  45418. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45419. };
  45420. __decorate([
  45421. BABYLON.serializeAsColor3()
  45422. ], HemisphericLight.prototype, "groundColor", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsVector3()
  45425. ], HemisphericLight.prototype, "direction", void 0);
  45426. return HemisphericLight;
  45427. }(BABYLON.Light));
  45428. BABYLON.HemisphericLight = HemisphericLight;
  45429. })(BABYLON || (BABYLON = {}));
  45430. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45431. var BABYLON;
  45432. (function (BABYLON) {
  45433. /**
  45434. * Base implementation of @see IShadowLight
  45435. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45436. */
  45437. var ShadowLight = /** @class */ (function (_super) {
  45438. __extends(ShadowLight, _super);
  45439. function ShadowLight() {
  45440. var _this = _super !== null && _super.apply(this, arguments) || this;
  45441. _this._needProjectionMatrixCompute = true;
  45442. return _this;
  45443. }
  45444. ShadowLight.prototype._setPosition = function (value) {
  45445. this._position = value;
  45446. };
  45447. Object.defineProperty(ShadowLight.prototype, "position", {
  45448. /**
  45449. * Sets the position the shadow will be casted from. Also use as the light position for both
  45450. * point and spot lights.
  45451. */
  45452. get: function () {
  45453. return this._position;
  45454. },
  45455. /**
  45456. * Sets the position the shadow will be casted from. Also use as the light position for both
  45457. * point and spot lights.
  45458. */
  45459. set: function (value) {
  45460. this._setPosition(value);
  45461. },
  45462. enumerable: true,
  45463. configurable: true
  45464. });
  45465. ShadowLight.prototype._setDirection = function (value) {
  45466. this._direction = value;
  45467. };
  45468. Object.defineProperty(ShadowLight.prototype, "direction", {
  45469. /**
  45470. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45471. * Also use as the light direction on spot and directional lights.
  45472. */
  45473. get: function () {
  45474. return this._direction;
  45475. },
  45476. /**
  45477. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45478. * Also use as the light direction on spot and directional lights.
  45479. */
  45480. set: function (value) {
  45481. this._setDirection(value);
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45487. /**
  45488. * Gets the shadow projection clipping minimum z value.
  45489. */
  45490. get: function () {
  45491. return this._shadowMinZ;
  45492. },
  45493. /**
  45494. * Sets the shadow projection clipping minimum z value.
  45495. */
  45496. set: function (value) {
  45497. this._shadowMinZ = value;
  45498. this.forceProjectionMatrixCompute();
  45499. },
  45500. enumerable: true,
  45501. configurable: true
  45502. });
  45503. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45504. /**
  45505. * Sets the shadow projection clipping maximum z value.
  45506. */
  45507. get: function () {
  45508. return this._shadowMaxZ;
  45509. },
  45510. /**
  45511. * Gets the shadow projection clipping maximum z value.
  45512. */
  45513. set: function (value) {
  45514. this._shadowMaxZ = value;
  45515. this.forceProjectionMatrixCompute();
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. /**
  45521. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45522. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45523. */
  45524. ShadowLight.prototype.computeTransformedInformation = function () {
  45525. if (this.parent && this.parent.getWorldMatrix) {
  45526. if (!this.transformedPosition) {
  45527. this.transformedPosition = BABYLON.Vector3.Zero();
  45528. }
  45529. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45530. // In case the direction is present.
  45531. if (this.direction) {
  45532. if (!this.transformedDirection) {
  45533. this.transformedDirection = BABYLON.Vector3.Zero();
  45534. }
  45535. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45536. }
  45537. return true;
  45538. }
  45539. return false;
  45540. };
  45541. /**
  45542. * Return the depth scale used for the shadow map.
  45543. * @returns the depth scale.
  45544. */
  45545. ShadowLight.prototype.getDepthScale = function () {
  45546. return 50.0;
  45547. };
  45548. /**
  45549. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45550. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45551. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45552. */
  45553. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45554. return this.transformedDirection ? this.transformedDirection : this.direction;
  45555. };
  45556. /**
  45557. * Returns the ShadowLight absolute position in the World.
  45558. * @returns the position vector in world space
  45559. */
  45560. ShadowLight.prototype.getAbsolutePosition = function () {
  45561. return this.transformedPosition ? this.transformedPosition : this.position;
  45562. };
  45563. /**
  45564. * Sets the ShadowLight direction toward the passed target.
  45565. * @param target The point tot target in local space
  45566. * @returns the updated ShadowLight direction
  45567. */
  45568. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45569. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45570. return this.direction;
  45571. };
  45572. /**
  45573. * Returns the light rotation in euler definition.
  45574. * @returns the x y z rotation in local space.
  45575. */
  45576. ShadowLight.prototype.getRotation = function () {
  45577. this.direction.normalize();
  45578. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45579. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45580. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45581. };
  45582. /**
  45583. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45584. * @returns true if a cube texture needs to be use
  45585. */
  45586. ShadowLight.prototype.needCube = function () {
  45587. return false;
  45588. };
  45589. /**
  45590. * Detects if the projection matrix requires to be recomputed this frame.
  45591. * @returns true if it requires to be recomputed otherwise, false.
  45592. */
  45593. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45594. return this._needProjectionMatrixCompute;
  45595. };
  45596. /**
  45597. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45598. */
  45599. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45600. this._needProjectionMatrixCompute = true;
  45601. };
  45602. /**
  45603. * Get the world matrix of the sahdow lights.
  45604. * @ignore Internal Use Only
  45605. */
  45606. ShadowLight.prototype._getWorldMatrix = function () {
  45607. if (!this._worldMatrix) {
  45608. this._worldMatrix = BABYLON.Matrix.Identity();
  45609. }
  45610. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45611. return this._worldMatrix;
  45612. };
  45613. /**
  45614. * Gets the minZ used for shadow according to both the scene and the light.
  45615. * @param activeCamera The camera we are returning the min for
  45616. * @returns the depth min z
  45617. */
  45618. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45619. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45620. };
  45621. /**
  45622. * Gets the maxZ used for shadow according to both the scene and the light.
  45623. * @param activeCamera The camera we are returning the max for
  45624. * @returns the depth max z
  45625. */
  45626. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45627. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45628. };
  45629. /**
  45630. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45631. * @param matrix The materix to updated with the projection information
  45632. * @param viewMatrix The transform matrix of the light
  45633. * @param renderList The list of mesh to render in the map
  45634. * @returns The current light
  45635. */
  45636. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45637. if (this.customProjectionMatrixBuilder) {
  45638. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45639. }
  45640. else {
  45641. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45642. }
  45643. return this;
  45644. };
  45645. __decorate([
  45646. BABYLON.serializeAsVector3()
  45647. ], ShadowLight.prototype, "position", null);
  45648. __decorate([
  45649. BABYLON.serializeAsVector3()
  45650. ], ShadowLight.prototype, "direction", null);
  45651. __decorate([
  45652. BABYLON.serialize()
  45653. ], ShadowLight.prototype, "shadowMinZ", null);
  45654. __decorate([
  45655. BABYLON.serialize()
  45656. ], ShadowLight.prototype, "shadowMaxZ", null);
  45657. return ShadowLight;
  45658. }(BABYLON.Light));
  45659. BABYLON.ShadowLight = ShadowLight;
  45660. })(BABYLON || (BABYLON = {}));
  45661. //# sourceMappingURL=babylon.shadowLight.js.map
  45662. var BABYLON;
  45663. (function (BABYLON) {
  45664. /**
  45665. * A point light is a light defined by an unique point in world space.
  45666. * The light is emitted in every direction from this point.
  45667. * A good example of a point light is a standard light bulb.
  45668. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45669. */
  45670. var PointLight = /** @class */ (function (_super) {
  45671. __extends(PointLight, _super);
  45672. /**
  45673. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45674. * A PointLight emits the light in every direction.
  45675. * It can cast shadows.
  45676. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45677. * ```javascript
  45678. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45679. * ```
  45680. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45681. * @param name The light friendly name
  45682. * @param position The position of the point light in the scene
  45683. * @param scene The scene the lights belongs to
  45684. */
  45685. function PointLight(name, position, scene) {
  45686. var _this = _super.call(this, name, scene) || this;
  45687. _this._shadowAngle = Math.PI / 2;
  45688. _this.position = position;
  45689. return _this;
  45690. }
  45691. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45692. /**
  45693. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45694. * This specifies what angle the shadow will use to be created.
  45695. *
  45696. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45697. */
  45698. get: function () {
  45699. return this._shadowAngle;
  45700. },
  45701. /**
  45702. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45703. * This specifies what angle the shadow will use to be created.
  45704. *
  45705. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45706. */
  45707. set: function (value) {
  45708. this._shadowAngle = value;
  45709. this.forceProjectionMatrixCompute();
  45710. },
  45711. enumerable: true,
  45712. configurable: true
  45713. });
  45714. Object.defineProperty(PointLight.prototype, "direction", {
  45715. /**
  45716. * Gets the direction if it has been set.
  45717. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45718. */
  45719. get: function () {
  45720. return this._direction;
  45721. },
  45722. /**
  45723. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45724. */
  45725. set: function (value) {
  45726. var previousNeedCube = this.needCube();
  45727. this._direction = value;
  45728. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45729. this._shadowGenerator.recreateShadowMap();
  45730. }
  45731. },
  45732. enumerable: true,
  45733. configurable: true
  45734. });
  45735. /**
  45736. * Returns the string "PointLight"
  45737. * @returns the class name
  45738. */
  45739. PointLight.prototype.getClassName = function () {
  45740. return "PointLight";
  45741. };
  45742. /**
  45743. * Returns the integer 0.
  45744. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45745. */
  45746. PointLight.prototype.getTypeID = function () {
  45747. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45748. };
  45749. /**
  45750. * Specifies wether or not the shadowmap should be a cube texture.
  45751. * @returns true if the shadowmap needs to be a cube texture.
  45752. */
  45753. PointLight.prototype.needCube = function () {
  45754. return !this.direction;
  45755. };
  45756. /**
  45757. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45758. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45759. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45760. */
  45761. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45762. if (this.direction) {
  45763. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45764. }
  45765. else {
  45766. switch (faceIndex) {
  45767. case 0:
  45768. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45769. case 1:
  45770. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45771. case 2:
  45772. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45773. case 3:
  45774. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45775. case 4:
  45776. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45777. case 5:
  45778. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45779. }
  45780. }
  45781. return BABYLON.Vector3.Zero();
  45782. };
  45783. /**
  45784. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45785. * - fov = PI / 2
  45786. * - aspect ratio : 1.0
  45787. * - z-near and far equal to the active camera minZ and maxZ.
  45788. * Returns the PointLight.
  45789. */
  45790. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45791. var activeCamera = this.getScene().activeCamera;
  45792. if (!activeCamera) {
  45793. return;
  45794. }
  45795. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45796. };
  45797. PointLight.prototype._buildUniformLayout = function () {
  45798. this._uniformBuffer.addUniform("vLightData", 4);
  45799. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45800. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45801. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45802. this._uniformBuffer.addUniform("depthValues", 2);
  45803. this._uniformBuffer.create();
  45804. };
  45805. /**
  45806. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45807. * @param effect The effect to update
  45808. * @param lightIndex The index of the light in the effect to update
  45809. * @returns The point light
  45810. */
  45811. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45812. if (this.computeTransformedInformation()) {
  45813. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45814. return this;
  45815. }
  45816. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45817. return this;
  45818. };
  45819. __decorate([
  45820. BABYLON.serialize()
  45821. ], PointLight.prototype, "shadowAngle", null);
  45822. return PointLight;
  45823. }(BABYLON.ShadowLight));
  45824. BABYLON.PointLight = PointLight;
  45825. })(BABYLON || (BABYLON = {}));
  45826. //# sourceMappingURL=babylon.pointLight.js.map
  45827. var BABYLON;
  45828. (function (BABYLON) {
  45829. /**
  45830. * A directional light is defined by a direction (what a surprise!).
  45831. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45832. * 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.
  45833. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45834. */
  45835. var DirectionalLight = /** @class */ (function (_super) {
  45836. __extends(DirectionalLight, _super);
  45837. /**
  45838. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45839. * The directional light is emitted from everywhere in the given direction.
  45840. * It can cast shawdows.
  45841. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45842. * @param name The friendly name of the light
  45843. * @param direction The direction of the light
  45844. * @param scene The scene the light belongs to
  45845. */
  45846. function DirectionalLight(name, direction, scene) {
  45847. var _this = _super.call(this, name, scene) || this;
  45848. _this._shadowFrustumSize = 0;
  45849. _this._shadowOrthoScale = 0.5;
  45850. /**
  45851. * Automatically compute the projection matrix to best fit (including all the casters)
  45852. * on each frame.
  45853. */
  45854. _this.autoUpdateExtends = true;
  45855. // Cache
  45856. _this._orthoLeft = Number.MAX_VALUE;
  45857. _this._orthoRight = Number.MIN_VALUE;
  45858. _this._orthoTop = Number.MIN_VALUE;
  45859. _this._orthoBottom = Number.MAX_VALUE;
  45860. _this.position = direction.scale(-1.0);
  45861. _this.direction = direction;
  45862. return _this;
  45863. }
  45864. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45865. /**
  45866. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45867. */
  45868. get: function () {
  45869. return this._shadowFrustumSize;
  45870. },
  45871. /**
  45872. * Specifies a fix frustum size for the shadow generation.
  45873. */
  45874. set: function (value) {
  45875. this._shadowFrustumSize = value;
  45876. this.forceProjectionMatrixCompute();
  45877. },
  45878. enumerable: true,
  45879. configurable: true
  45880. });
  45881. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45882. /**
  45883. * Gets the shadow projection scale against the optimal computed one.
  45884. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45885. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45886. */
  45887. get: function () {
  45888. return this._shadowOrthoScale;
  45889. },
  45890. /**
  45891. * Sets the shadow projection scale against the optimal computed one.
  45892. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45893. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45894. */
  45895. set: function (value) {
  45896. this._shadowOrthoScale = value;
  45897. this.forceProjectionMatrixCompute();
  45898. },
  45899. enumerable: true,
  45900. configurable: true
  45901. });
  45902. /**
  45903. * Returns the string "DirectionalLight".
  45904. * @return The class name
  45905. */
  45906. DirectionalLight.prototype.getClassName = function () {
  45907. return "DirectionalLight";
  45908. };
  45909. /**
  45910. * Returns the integer 1.
  45911. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45912. */
  45913. DirectionalLight.prototype.getTypeID = function () {
  45914. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45915. };
  45916. /**
  45917. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45918. * Returns the DirectionalLight Shadow projection matrix.
  45919. */
  45920. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45921. if (this.shadowFrustumSize > 0) {
  45922. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45923. }
  45924. else {
  45925. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45926. }
  45927. };
  45928. /**
  45929. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45930. * Returns the DirectionalLight Shadow projection matrix.
  45931. */
  45932. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45933. var activeCamera = this.getScene().activeCamera;
  45934. if (!activeCamera) {
  45935. return;
  45936. }
  45937. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45938. };
  45939. /**
  45940. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45941. * Returns the DirectionalLight Shadow projection matrix.
  45942. */
  45943. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45944. var activeCamera = this.getScene().activeCamera;
  45945. if (!activeCamera) {
  45946. return;
  45947. }
  45948. // Check extends
  45949. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45950. var tempVector3 = BABYLON.Vector3.Zero();
  45951. this._orthoLeft = Number.MAX_VALUE;
  45952. this._orthoRight = Number.MIN_VALUE;
  45953. this._orthoTop = Number.MIN_VALUE;
  45954. this._orthoBottom = Number.MAX_VALUE;
  45955. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45956. var mesh = renderList[meshIndex];
  45957. if (!mesh) {
  45958. continue;
  45959. }
  45960. var boundingInfo = mesh.getBoundingInfo();
  45961. var boundingBox = boundingInfo.boundingBox;
  45962. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45963. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45964. if (tempVector3.x < this._orthoLeft)
  45965. this._orthoLeft = tempVector3.x;
  45966. if (tempVector3.y < this._orthoBottom)
  45967. this._orthoBottom = tempVector3.y;
  45968. if (tempVector3.x > this._orthoRight)
  45969. this._orthoRight = tempVector3.x;
  45970. if (tempVector3.y > this._orthoTop)
  45971. this._orthoTop = tempVector3.y;
  45972. }
  45973. }
  45974. }
  45975. var xOffset = this._orthoRight - this._orthoLeft;
  45976. var yOffset = this._orthoTop - this._orthoBottom;
  45977. 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);
  45978. };
  45979. DirectionalLight.prototype._buildUniformLayout = function () {
  45980. this._uniformBuffer.addUniform("vLightData", 4);
  45981. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45982. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45983. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45984. this._uniformBuffer.addUniform("depthValues", 2);
  45985. this._uniformBuffer.create();
  45986. };
  45987. /**
  45988. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45989. * @param effect The effect to update
  45990. * @param lightIndex The index of the light in the effect to update
  45991. * @returns The directional light
  45992. */
  45993. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45994. if (this.computeTransformedInformation()) {
  45995. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45996. return this;
  45997. }
  45998. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45999. return this;
  46000. };
  46001. /**
  46002. * Gets the minZ used for shadow according to both the scene and the light.
  46003. *
  46004. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46005. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46006. * @param activeCamera The camera we are returning the min for
  46007. * @returns the depth min z
  46008. */
  46009. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46010. return 1;
  46011. };
  46012. /**
  46013. * Gets the maxZ used for shadow according to both the scene and the light.
  46014. *
  46015. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46016. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46017. * @param activeCamera The camera we are returning the max for
  46018. * @returns the depth max z
  46019. */
  46020. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46021. return 1;
  46022. };
  46023. __decorate([
  46024. BABYLON.serialize()
  46025. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46026. __decorate([
  46027. BABYLON.serialize()
  46028. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46029. __decorate([
  46030. BABYLON.serialize()
  46031. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46032. return DirectionalLight;
  46033. }(BABYLON.ShadowLight));
  46034. BABYLON.DirectionalLight = DirectionalLight;
  46035. })(BABYLON || (BABYLON = {}));
  46036. //# sourceMappingURL=babylon.directionalLight.js.map
  46037. var BABYLON;
  46038. (function (BABYLON) {
  46039. /**
  46040. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46041. * These values define a cone of light starting from the position, emitting toward the direction.
  46042. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46043. * and the exponent defines the speed of the decay of the light with distance (reach).
  46044. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46045. */
  46046. var SpotLight = /** @class */ (function (_super) {
  46047. __extends(SpotLight, _super);
  46048. /**
  46049. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46050. * It can cast shadows.
  46051. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46052. * @param name The light friendly name
  46053. * @param position The position of the spot light in the scene
  46054. * @param direction The direction of the light in the scene
  46055. * @param angle The cone angle of the light in Radians
  46056. * @param exponent The light decay speed with the distance from the emission spot
  46057. * @param scene The scene the lights belongs to
  46058. */
  46059. function SpotLight(name, position, direction, angle, exponent, scene) {
  46060. var _this = _super.call(this, name, scene) || this;
  46061. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46062. _this._projectionTextureLightNear = 1e-6;
  46063. _this._projectionTextureLightFar = 1000.0;
  46064. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46065. _this._projectionTextureViewLightDirty = true;
  46066. _this._projectionTextureProjectionLightDirty = true;
  46067. _this._projectionTextureDirty = true;
  46068. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46069. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46070. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46071. _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);
  46072. _this.position = position;
  46073. _this.direction = direction;
  46074. _this.angle = angle;
  46075. _this.exponent = exponent;
  46076. return _this;
  46077. }
  46078. Object.defineProperty(SpotLight.prototype, "angle", {
  46079. /**
  46080. * Gets the cone angle of the spot light in Radians.
  46081. */
  46082. get: function () {
  46083. return this._angle;
  46084. },
  46085. /**
  46086. * Sets the cone angle of the spot light in Radians.
  46087. */
  46088. set: function (value) {
  46089. this._angle = value;
  46090. this._projectionTextureProjectionLightDirty = true;
  46091. this.forceProjectionMatrixCompute();
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46097. /**
  46098. * Allows scaling the angle of the light for shadow generation only.
  46099. */
  46100. get: function () {
  46101. return this._shadowAngleScale;
  46102. },
  46103. /**
  46104. * Allows scaling the angle of the light for shadow generation only.
  46105. */
  46106. set: function (value) {
  46107. this._shadowAngleScale = value;
  46108. this.forceProjectionMatrixCompute();
  46109. },
  46110. enumerable: true,
  46111. configurable: true
  46112. });
  46113. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46114. /**
  46115. * Allows reading the projecton texture
  46116. */
  46117. get: function () {
  46118. return this._projectionTextureMatrix;
  46119. },
  46120. enumerable: true,
  46121. configurable: true
  46122. });
  46123. ;
  46124. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46125. /**
  46126. * Gets the near clip of the Spotlight for texture projection.
  46127. */
  46128. get: function () {
  46129. return this._projectionTextureLightNear;
  46130. },
  46131. /**
  46132. * Sets the near clip of the Spotlight for texture projection.
  46133. */
  46134. set: function (value) {
  46135. this._projectionTextureLightNear = value;
  46136. this._projectionTextureProjectionLightDirty = true;
  46137. },
  46138. enumerable: true,
  46139. configurable: true
  46140. });
  46141. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46142. /**
  46143. * Gets the far clip of the Spotlight for texture projection.
  46144. */
  46145. get: function () {
  46146. return this._projectionTextureLightFar;
  46147. },
  46148. /**
  46149. * Sets the far clip of the Spotlight for texture projection.
  46150. */
  46151. set: function (value) {
  46152. this._projectionTextureLightFar = value;
  46153. this._projectionTextureProjectionLightDirty = true;
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46159. /**
  46160. * Gets the Up vector of the Spotlight for texture projection.
  46161. */
  46162. get: function () {
  46163. return this._projectionTextureUpDirection;
  46164. },
  46165. /**
  46166. * Sets the Up vector of the Spotlight for texture projection.
  46167. */
  46168. set: function (value) {
  46169. this._projectionTextureUpDirection = value;
  46170. this._projectionTextureProjectionLightDirty = true;
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. ;
  46176. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46177. /**
  46178. * Gets the projection texture of the light.
  46179. */
  46180. get: function () {
  46181. return this._projectionTexture;
  46182. },
  46183. /**
  46184. * Sets the projection texture of the light.
  46185. */
  46186. set: function (value) {
  46187. this._projectionTexture = value;
  46188. this._projectionTextureDirty = true;
  46189. },
  46190. enumerable: true,
  46191. configurable: true
  46192. });
  46193. /**
  46194. * Returns the string "SpotLight".
  46195. * @returns the class name
  46196. */
  46197. SpotLight.prototype.getClassName = function () {
  46198. return "SpotLight";
  46199. };
  46200. /**
  46201. * Returns the integer 2.
  46202. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46203. */
  46204. SpotLight.prototype.getTypeID = function () {
  46205. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46206. };
  46207. /**
  46208. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46209. */
  46210. SpotLight.prototype._setDirection = function (value) {
  46211. _super.prototype._setDirection.call(this, value);
  46212. this._projectionTextureViewLightDirty = true;
  46213. };
  46214. /**
  46215. * Overrides the position setter to recompute the projection texture view light Matrix.
  46216. */
  46217. SpotLight.prototype._setPosition = function (value) {
  46218. _super.prototype._setPosition.call(this, value);
  46219. this._projectionTextureViewLightDirty = true;
  46220. };
  46221. /**
  46222. * 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.
  46223. * Returns the SpotLight.
  46224. */
  46225. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46226. var activeCamera = this.getScene().activeCamera;
  46227. if (!activeCamera) {
  46228. return;
  46229. }
  46230. this._shadowAngleScale = this._shadowAngleScale || 1;
  46231. var angle = this._shadowAngleScale * this._angle;
  46232. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46233. };
  46234. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46235. this._projectionTextureViewLightDirty = false;
  46236. this._projectionTextureDirty = true;
  46237. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46238. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46239. };
  46240. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46241. this._projectionTextureProjectionLightDirty = false;
  46242. this._projectionTextureDirty = true;
  46243. var light_far = this.projectionTextureLightFar;
  46244. var light_near = this.projectionTextureLightNear;
  46245. var P = light_far / (light_far - light_near);
  46246. var Q = -P * light_near;
  46247. var S = 1.0 / Math.tan(this._angle / 2.0);
  46248. var A = 1.0;
  46249. 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);
  46250. };
  46251. /**
  46252. * Main function for light texture projection matrix computing.
  46253. */
  46254. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46255. this._projectionTextureDirty = false;
  46256. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46257. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46258. };
  46259. SpotLight.prototype._buildUniformLayout = function () {
  46260. this._uniformBuffer.addUniform("vLightData", 4);
  46261. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46262. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46263. this._uniformBuffer.addUniform("vLightDirection", 3);
  46264. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46265. this._uniformBuffer.addUniform("depthValues", 2);
  46266. this._uniformBuffer.create();
  46267. };
  46268. /**
  46269. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46270. * @param effect The effect to update
  46271. * @param lightIndex The index of the light in the effect to update
  46272. * @returns The spot light
  46273. */
  46274. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46275. var normalizeDirection;
  46276. if (this.computeTransformedInformation()) {
  46277. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46278. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46279. }
  46280. else {
  46281. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46282. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46283. }
  46284. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46285. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46286. if (this._projectionTextureViewLightDirty) {
  46287. this._computeProjectionTextureViewLightMatrix();
  46288. }
  46289. if (this._projectionTextureProjectionLightDirty) {
  46290. this._computeProjectionTextureProjectionLightMatrix();
  46291. }
  46292. if (this._projectionTextureDirty) {
  46293. this._computeProjectionTextureMatrix();
  46294. }
  46295. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46296. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46297. }
  46298. return this;
  46299. };
  46300. /**
  46301. * Disposes the light and the associated resources.
  46302. */
  46303. SpotLight.prototype.dispose = function () {
  46304. _super.prototype.dispose.call(this);
  46305. if (this._projectionTexture) {
  46306. this._projectionTexture.dispose();
  46307. }
  46308. };
  46309. __decorate([
  46310. BABYLON.serialize()
  46311. ], SpotLight.prototype, "angle", null);
  46312. __decorate([
  46313. BABYLON.serialize()
  46314. ], SpotLight.prototype, "shadowAngleScale", null);
  46315. __decorate([
  46316. BABYLON.serialize()
  46317. ], SpotLight.prototype, "exponent", void 0);
  46318. __decorate([
  46319. BABYLON.serialize()
  46320. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46321. __decorate([
  46322. BABYLON.serialize()
  46323. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46324. __decorate([
  46325. BABYLON.serialize()
  46326. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46327. __decorate([
  46328. BABYLON.serializeAsTexture("projectedLightTexture")
  46329. ], SpotLight.prototype, "_projectionTexture", void 0);
  46330. return SpotLight;
  46331. }(BABYLON.ShadowLight));
  46332. BABYLON.SpotLight = SpotLight;
  46333. })(BABYLON || (BABYLON = {}));
  46334. //# sourceMappingURL=babylon.spotLight.js.map
  46335. var BABYLON;
  46336. (function (BABYLON) {
  46337. /**
  46338. * Class used to override all child animations of a given target
  46339. */
  46340. var AnimationPropertiesOverride = /** @class */ (function () {
  46341. function AnimationPropertiesOverride() {
  46342. /**
  46343. * Gets or sets a value indicating if animation blending must be used
  46344. */
  46345. this.enableBlending = false;
  46346. /**
  46347. * Gets or sets the blending speed to use when enableBlending is true
  46348. */
  46349. this.blendingSpeed = 0.01;
  46350. /**
  46351. * Gets or sets the default loop mode to use
  46352. */
  46353. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46354. }
  46355. return AnimationPropertiesOverride;
  46356. }());
  46357. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46358. })(BABYLON || (BABYLON = {}));
  46359. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46360. var BABYLON;
  46361. (function (BABYLON) {
  46362. var AnimationRange = /** @class */ (function () {
  46363. function AnimationRange(name, from, to) {
  46364. this.name = name;
  46365. this.from = from;
  46366. this.to = to;
  46367. }
  46368. AnimationRange.prototype.clone = function () {
  46369. return new AnimationRange(this.name, this.from, this.to);
  46370. };
  46371. return AnimationRange;
  46372. }());
  46373. BABYLON.AnimationRange = AnimationRange;
  46374. /**
  46375. * Composed of a frame, and an action function
  46376. */
  46377. var AnimationEvent = /** @class */ (function () {
  46378. function AnimationEvent(frame, action, onlyOnce) {
  46379. this.frame = frame;
  46380. this.action = action;
  46381. this.onlyOnce = onlyOnce;
  46382. this.isDone = false;
  46383. }
  46384. return AnimationEvent;
  46385. }());
  46386. BABYLON.AnimationEvent = AnimationEvent;
  46387. var PathCursor = /** @class */ (function () {
  46388. function PathCursor(path) {
  46389. this.path = path;
  46390. this._onchange = new Array();
  46391. this.value = 0;
  46392. this.animations = new Array();
  46393. }
  46394. PathCursor.prototype.getPoint = function () {
  46395. var point = this.path.getPointAtLengthPosition(this.value);
  46396. return new BABYLON.Vector3(point.x, 0, point.y);
  46397. };
  46398. PathCursor.prototype.moveAhead = function (step) {
  46399. if (step === void 0) { step = 0.002; }
  46400. this.move(step);
  46401. return this;
  46402. };
  46403. PathCursor.prototype.moveBack = function (step) {
  46404. if (step === void 0) { step = 0.002; }
  46405. this.move(-step);
  46406. return this;
  46407. };
  46408. PathCursor.prototype.move = function (step) {
  46409. if (Math.abs(step) > 1) {
  46410. throw "step size should be less than 1.";
  46411. }
  46412. this.value += step;
  46413. this.ensureLimits();
  46414. this.raiseOnChange();
  46415. return this;
  46416. };
  46417. PathCursor.prototype.ensureLimits = function () {
  46418. while (this.value > 1) {
  46419. this.value -= 1;
  46420. }
  46421. while (this.value < 0) {
  46422. this.value += 1;
  46423. }
  46424. return this;
  46425. };
  46426. // used by animation engine
  46427. PathCursor.prototype.raiseOnChange = function () {
  46428. var _this = this;
  46429. this._onchange.forEach(function (f) { return f(_this); });
  46430. return this;
  46431. };
  46432. PathCursor.prototype.onchange = function (f) {
  46433. this._onchange.push(f);
  46434. return this;
  46435. };
  46436. return PathCursor;
  46437. }());
  46438. BABYLON.PathCursor = PathCursor;
  46439. var AnimationKeyInterpolation;
  46440. (function (AnimationKeyInterpolation) {
  46441. /**
  46442. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46443. */
  46444. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46445. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46446. var Animation = /** @class */ (function () {
  46447. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46448. this.name = name;
  46449. this.targetProperty = targetProperty;
  46450. this.framePerSecond = framePerSecond;
  46451. this.dataType = dataType;
  46452. this.loopMode = loopMode;
  46453. this.enableBlending = enableBlending;
  46454. this._runtimeAnimations = new Array();
  46455. // The set of event that will be linked to this animation
  46456. this._events = new Array();
  46457. this.blendingSpeed = 0.01;
  46458. this._ranges = {};
  46459. this.targetPropertyPath = targetProperty.split(".");
  46460. this.dataType = dataType;
  46461. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46462. }
  46463. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46464. var dataType = undefined;
  46465. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46466. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46467. }
  46468. else if (from instanceof BABYLON.Quaternion) {
  46469. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46470. }
  46471. else if (from instanceof BABYLON.Vector3) {
  46472. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46473. }
  46474. else if (from instanceof BABYLON.Vector2) {
  46475. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46476. }
  46477. else if (from instanceof BABYLON.Color3) {
  46478. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46479. }
  46480. else if (from instanceof BABYLON.Size) {
  46481. dataType = Animation.ANIMATIONTYPE_SIZE;
  46482. }
  46483. if (dataType == undefined) {
  46484. return null;
  46485. }
  46486. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46487. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46488. animation.setKeys(keys);
  46489. if (easingFunction !== undefined) {
  46490. animation.setEasingFunction(easingFunction);
  46491. }
  46492. return animation;
  46493. };
  46494. /**
  46495. * Sets up an animation.
  46496. * @param property the property to animate
  46497. * @param animationType the animation type to apply
  46498. * @param easingFunction the easing function used in the animation
  46499. * @returns The created animation
  46500. */
  46501. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46502. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46503. animation.setEasingFunction(easingFunction);
  46504. return animation;
  46505. };
  46506. /**
  46507. * Create and start an animation on a node
  46508. * @param {string} name defines the name of the global animation that will be run on all nodes
  46509. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46510. * @param {string} targetProperty defines property to animate
  46511. * @param {number} framePerSecond defines the number of frame per second yo use
  46512. * @param {number} totalFrame defines the number of frames in total
  46513. * @param {any} from defines the initial value
  46514. * @param {any} to defines the final value
  46515. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46516. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46517. * @param onAnimationEnd defines the callback to call when animation end
  46518. * @returns the animatable created for this animation
  46519. */
  46520. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46521. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46522. if (!animation) {
  46523. return null;
  46524. }
  46525. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46526. };
  46527. /**
  46528. * Create and start an animation on a node and its descendants
  46529. * @param {string} name defines the name of the global animation that will be run on all nodes
  46530. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46531. * @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.
  46532. * @param {string} targetProperty defines property to animate
  46533. * @param {number} framePerSecond defines the number of frame per second yo use
  46534. * @param {number} totalFrame defines the number of frames in total
  46535. * @param {any} from defines the initial value
  46536. * @param {any} to defines the final value
  46537. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46538. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46539. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46540. * @returns the list of animatables created for all nodes
  46541. * @example https://www.babylonjs-playground.com/#MH0VLI
  46542. */
  46543. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46544. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46545. if (!animation) {
  46546. return null;
  46547. }
  46548. var scene = node.getScene();
  46549. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46550. };
  46551. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46552. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46553. if (!animation) {
  46554. return null;
  46555. }
  46556. node.animations.push(animation);
  46557. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46558. };
  46559. /**
  46560. * Transition property of the Camera to the target Value.
  46561. * @param property The property to transition
  46562. * @param targetValue The target Value of the property
  46563. * @param host The object where the property to animate belongs
  46564. * @param scene Scene used to run the animation
  46565. * @param frameRate Framerate (in frame/s) to use
  46566. * @param transition The transition type we want to use
  46567. * @param duration The duration of the animation, in milliseconds
  46568. * @param onAnimationEnd Call back trigger at the end of the animation.
  46569. */
  46570. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46571. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46572. if (duration <= 0) {
  46573. host[property] = targetValue;
  46574. if (onAnimationEnd) {
  46575. onAnimationEnd();
  46576. }
  46577. return null;
  46578. }
  46579. var endFrame = frameRate * (duration / 1000);
  46580. transition.setKeys([{
  46581. frame: 0,
  46582. value: host[property].clone ? host[property].clone() : host[property]
  46583. },
  46584. {
  46585. frame: endFrame,
  46586. value: targetValue
  46587. }]);
  46588. if (!host.animations) {
  46589. host.animations = [];
  46590. }
  46591. host.animations.push(transition);
  46592. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46593. animation.onAnimationEnd = onAnimationEnd;
  46594. return animation;
  46595. };
  46596. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46597. /**
  46598. * Return the array of runtime animations currently using this animation
  46599. */
  46600. get: function () {
  46601. return this._runtimeAnimations;
  46602. },
  46603. enumerable: true,
  46604. configurable: true
  46605. });
  46606. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46607. get: function () {
  46608. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46609. var runtimeAnimation = _a[_i];
  46610. if (!runtimeAnimation.isStopped) {
  46611. return true;
  46612. }
  46613. }
  46614. return false;
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. // Methods
  46620. /**
  46621. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46622. */
  46623. Animation.prototype.toString = function (fullDetails) {
  46624. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46625. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46626. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46627. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46628. if (fullDetails) {
  46629. ret += ", Ranges: {";
  46630. var first = true;
  46631. for (var name in this._ranges) {
  46632. if (first) {
  46633. ret += ", ";
  46634. first = false;
  46635. }
  46636. ret += name;
  46637. }
  46638. ret += "}";
  46639. }
  46640. return ret;
  46641. };
  46642. /**
  46643. * Add an event to this animation.
  46644. */
  46645. Animation.prototype.addEvent = function (event) {
  46646. this._events.push(event);
  46647. };
  46648. /**
  46649. * Remove all events found at the given frame
  46650. * @param frame
  46651. */
  46652. Animation.prototype.removeEvents = function (frame) {
  46653. for (var index = 0; index < this._events.length; index++) {
  46654. if (this._events[index].frame === frame) {
  46655. this._events.splice(index, 1);
  46656. index--;
  46657. }
  46658. }
  46659. };
  46660. Animation.prototype.getEvents = function () {
  46661. return this._events;
  46662. };
  46663. Animation.prototype.createRange = function (name, from, to) {
  46664. // check name not already in use; could happen for bones after serialized
  46665. if (!this._ranges[name]) {
  46666. this._ranges[name] = new AnimationRange(name, from, to);
  46667. }
  46668. };
  46669. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46670. if (deleteFrames === void 0) { deleteFrames = true; }
  46671. var range = this._ranges[name];
  46672. if (!range) {
  46673. return;
  46674. }
  46675. if (deleteFrames) {
  46676. var from = range.from;
  46677. var to = range.to;
  46678. // this loop MUST go high to low for multiple splices to work
  46679. for (var key = this._keys.length - 1; key >= 0; key--) {
  46680. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46681. this._keys.splice(key, 1);
  46682. }
  46683. }
  46684. }
  46685. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46686. };
  46687. Animation.prototype.getRange = function (name) {
  46688. return this._ranges[name];
  46689. };
  46690. Animation.prototype.getKeys = function () {
  46691. return this._keys;
  46692. };
  46693. Animation.prototype.getHighestFrame = function () {
  46694. var ret = 0;
  46695. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46696. if (ret < this._keys[key].frame) {
  46697. ret = this._keys[key].frame;
  46698. }
  46699. }
  46700. return ret;
  46701. };
  46702. Animation.prototype.getEasingFunction = function () {
  46703. return this._easingFunction;
  46704. };
  46705. Animation.prototype.setEasingFunction = function (easingFunction) {
  46706. this._easingFunction = easingFunction;
  46707. };
  46708. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46709. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46710. };
  46711. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46712. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46713. };
  46714. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46715. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46716. };
  46717. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46718. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46719. };
  46720. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46721. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46722. };
  46723. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46724. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46725. };
  46726. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46727. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46728. };
  46729. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46730. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46731. };
  46732. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46733. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46734. };
  46735. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46736. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46737. };
  46738. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46739. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46740. };
  46741. Animation.prototype.clone = function () {
  46742. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46743. clone.enableBlending = this.enableBlending;
  46744. clone.blendingSpeed = this.blendingSpeed;
  46745. if (this._keys) {
  46746. clone.setKeys(this._keys);
  46747. }
  46748. if (this._ranges) {
  46749. clone._ranges = {};
  46750. for (var name in this._ranges) {
  46751. var range = this._ranges[name];
  46752. if (!range) {
  46753. continue;
  46754. }
  46755. clone._ranges[name] = range.clone();
  46756. }
  46757. }
  46758. return clone;
  46759. };
  46760. Animation.prototype.setKeys = function (values) {
  46761. this._keys = values.slice(0);
  46762. };
  46763. Animation.prototype.serialize = function () {
  46764. var serializationObject = {};
  46765. serializationObject.name = this.name;
  46766. serializationObject.property = this.targetProperty;
  46767. serializationObject.framePerSecond = this.framePerSecond;
  46768. serializationObject.dataType = this.dataType;
  46769. serializationObject.loopBehavior = this.loopMode;
  46770. serializationObject.enableBlending = this.enableBlending;
  46771. serializationObject.blendingSpeed = this.blendingSpeed;
  46772. var dataType = this.dataType;
  46773. serializationObject.keys = [];
  46774. var keys = this.getKeys();
  46775. for (var index = 0; index < keys.length; index++) {
  46776. var animationKey = keys[index];
  46777. var key = {};
  46778. key.frame = animationKey.frame;
  46779. switch (dataType) {
  46780. case Animation.ANIMATIONTYPE_FLOAT:
  46781. key.values = [animationKey.value];
  46782. break;
  46783. case Animation.ANIMATIONTYPE_QUATERNION:
  46784. case Animation.ANIMATIONTYPE_MATRIX:
  46785. case Animation.ANIMATIONTYPE_VECTOR3:
  46786. case Animation.ANIMATIONTYPE_COLOR3:
  46787. key.values = animationKey.value.asArray();
  46788. break;
  46789. }
  46790. serializationObject.keys.push(key);
  46791. }
  46792. serializationObject.ranges = [];
  46793. for (var name in this._ranges) {
  46794. var source = this._ranges[name];
  46795. if (!source) {
  46796. continue;
  46797. }
  46798. var range = {};
  46799. range.name = name;
  46800. range.from = source.from;
  46801. range.to = source.to;
  46802. serializationObject.ranges.push(range);
  46803. }
  46804. return serializationObject;
  46805. };
  46806. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46807. get: function () {
  46808. return Animation._ANIMATIONTYPE_FLOAT;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46814. get: function () {
  46815. return Animation._ANIMATIONTYPE_VECTOR3;
  46816. },
  46817. enumerable: true,
  46818. configurable: true
  46819. });
  46820. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46821. get: function () {
  46822. return Animation._ANIMATIONTYPE_VECTOR2;
  46823. },
  46824. enumerable: true,
  46825. configurable: true
  46826. });
  46827. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46828. get: function () {
  46829. return Animation._ANIMATIONTYPE_SIZE;
  46830. },
  46831. enumerable: true,
  46832. configurable: true
  46833. });
  46834. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46835. get: function () {
  46836. return Animation._ANIMATIONTYPE_QUATERNION;
  46837. },
  46838. enumerable: true,
  46839. configurable: true
  46840. });
  46841. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46842. get: function () {
  46843. return Animation._ANIMATIONTYPE_MATRIX;
  46844. },
  46845. enumerable: true,
  46846. configurable: true
  46847. });
  46848. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46849. get: function () {
  46850. return Animation._ANIMATIONTYPE_COLOR3;
  46851. },
  46852. enumerable: true,
  46853. configurable: true
  46854. });
  46855. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46856. get: function () {
  46857. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46863. get: function () {
  46864. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46865. },
  46866. enumerable: true,
  46867. configurable: true
  46868. });
  46869. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46870. get: function () {
  46871. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46872. },
  46873. enumerable: true,
  46874. configurable: true
  46875. });
  46876. Animation.Parse = function (parsedAnimation) {
  46877. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46878. var dataType = parsedAnimation.dataType;
  46879. var keys = [];
  46880. var data;
  46881. var index;
  46882. if (parsedAnimation.enableBlending) {
  46883. animation.enableBlending = parsedAnimation.enableBlending;
  46884. }
  46885. if (parsedAnimation.blendingSpeed) {
  46886. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46887. }
  46888. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46889. var key = parsedAnimation.keys[index];
  46890. var inTangent;
  46891. var outTangent;
  46892. switch (dataType) {
  46893. case Animation.ANIMATIONTYPE_FLOAT:
  46894. data = key.values[0];
  46895. if (key.values.length >= 1) {
  46896. inTangent = key.values[1];
  46897. }
  46898. if (key.values.length >= 2) {
  46899. outTangent = key.values[2];
  46900. }
  46901. break;
  46902. case Animation.ANIMATIONTYPE_QUATERNION:
  46903. data = BABYLON.Quaternion.FromArray(key.values);
  46904. if (key.values.length >= 8) {
  46905. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46906. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46907. inTangent = _inTangent;
  46908. }
  46909. }
  46910. if (key.values.length >= 12) {
  46911. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46912. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46913. outTangent = _outTangent;
  46914. }
  46915. }
  46916. break;
  46917. case Animation.ANIMATIONTYPE_MATRIX:
  46918. data = BABYLON.Matrix.FromArray(key.values);
  46919. break;
  46920. case Animation.ANIMATIONTYPE_COLOR3:
  46921. data = BABYLON.Color3.FromArray(key.values);
  46922. break;
  46923. case Animation.ANIMATIONTYPE_VECTOR3:
  46924. default:
  46925. data = BABYLON.Vector3.FromArray(key.values);
  46926. break;
  46927. }
  46928. var keyData = {};
  46929. keyData.frame = key.frame;
  46930. keyData.value = data;
  46931. if (inTangent != undefined) {
  46932. keyData.inTangent = inTangent;
  46933. }
  46934. if (outTangent != undefined) {
  46935. keyData.outTangent = outTangent;
  46936. }
  46937. keys.push(keyData);
  46938. }
  46939. animation.setKeys(keys);
  46940. if (parsedAnimation.ranges) {
  46941. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46942. data = parsedAnimation.ranges[index];
  46943. animation.createRange(data.name, data.from, data.to);
  46944. }
  46945. }
  46946. return animation;
  46947. };
  46948. Animation.AppendSerializedAnimations = function (source, destination) {
  46949. if (source.animations) {
  46950. destination.animations = [];
  46951. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46952. var animation = source.animations[animationIndex];
  46953. destination.animations.push(animation.serialize());
  46954. }
  46955. }
  46956. };
  46957. Animation.AllowMatricesInterpolation = false;
  46958. // Statics
  46959. Animation._ANIMATIONTYPE_FLOAT = 0;
  46960. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46961. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46962. Animation._ANIMATIONTYPE_MATRIX = 3;
  46963. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46964. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46965. Animation._ANIMATIONTYPE_SIZE = 6;
  46966. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46967. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46968. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46969. return Animation;
  46970. }());
  46971. BABYLON.Animation = Animation;
  46972. })(BABYLON || (BABYLON = {}));
  46973. //# sourceMappingURL=babylon.animation.js.map
  46974. var BABYLON;
  46975. (function (BABYLON) {
  46976. /**
  46977. * This class defines the direct association between an animation and a target
  46978. */
  46979. var TargetedAnimation = /** @class */ (function () {
  46980. function TargetedAnimation() {
  46981. }
  46982. return TargetedAnimation;
  46983. }());
  46984. BABYLON.TargetedAnimation = TargetedAnimation;
  46985. /**
  46986. * Use this class to create coordinated animations on multiple targets
  46987. */
  46988. var AnimationGroup = /** @class */ (function () {
  46989. function AnimationGroup(name, scene) {
  46990. if (scene === void 0) { scene = null; }
  46991. this.name = name;
  46992. this._targetedAnimations = new Array();
  46993. this._animatables = new Array();
  46994. this._from = Number.MAX_VALUE;
  46995. this._to = -Number.MAX_VALUE;
  46996. this._speedRatio = 1;
  46997. this.onAnimationEndObservable = new BABYLON.Observable();
  46998. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46999. this._scene.animationGroups.push(this);
  47000. }
  47001. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47002. /**
  47003. * Define if the animations are started
  47004. */
  47005. get: function () {
  47006. return this._isStarted;
  47007. },
  47008. enumerable: true,
  47009. configurable: true
  47010. });
  47011. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47012. /**
  47013. * Gets or sets the speed ratio to use for all animations
  47014. */
  47015. get: function () {
  47016. return this._speedRatio;
  47017. },
  47018. /**
  47019. * Gets or sets the speed ratio to use for all animations
  47020. */
  47021. set: function (value) {
  47022. if (this._speedRatio === value) {
  47023. return;
  47024. }
  47025. this._speedRatio = value;
  47026. for (var index = 0; index < this._animatables.length; index++) {
  47027. var animatable = this._animatables[index];
  47028. animatable.speedRatio = this._speedRatio;
  47029. }
  47030. },
  47031. enumerable: true,
  47032. configurable: true
  47033. });
  47034. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47035. /**
  47036. * Gets the targeted animations for this animation group
  47037. */
  47038. get: function () {
  47039. return this._targetedAnimations;
  47040. },
  47041. enumerable: true,
  47042. configurable: true
  47043. });
  47044. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47045. /**
  47046. * returning the list of animatables controlled by this animation group.
  47047. */
  47048. get: function () {
  47049. return this._animatables;
  47050. },
  47051. enumerable: true,
  47052. configurable: true
  47053. });
  47054. /**
  47055. * Add an animation (with its target) in the group
  47056. * @param animation defines the animation we want to add
  47057. * @param target defines the target of the animation
  47058. * @returns the {BABYLON.TargetedAnimation} object
  47059. */
  47060. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47061. var targetedAnimation = {
  47062. animation: animation,
  47063. target: target
  47064. };
  47065. var keys = animation.getKeys();
  47066. if (this._from > keys[0].frame) {
  47067. this._from = keys[0].frame;
  47068. }
  47069. if (this._to < keys[keys.length - 1].frame) {
  47070. this._to = keys[keys.length - 1].frame;
  47071. }
  47072. this._targetedAnimations.push(targetedAnimation);
  47073. return targetedAnimation;
  47074. };
  47075. /**
  47076. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47077. * It can add constant keys at begin or end
  47078. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47079. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47080. */
  47081. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47082. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47083. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47084. beginFrame = Math.max(beginFrame, this._from);
  47085. endFrame = Math.min(endFrame, this._to);
  47086. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47087. var targetedAnimation = this._targetedAnimations[index];
  47088. var keys = targetedAnimation.animation.getKeys();
  47089. var startKey = keys[0];
  47090. var endKey = keys[keys.length - 1];
  47091. if (startKey.frame > beginFrame) {
  47092. var newKey = {
  47093. frame: beginFrame,
  47094. value: startKey.value,
  47095. inTangent: startKey.inTangent,
  47096. outTangent: startKey.outTangent,
  47097. interpolation: startKey.interpolation
  47098. };
  47099. keys.splice(0, 0, newKey);
  47100. }
  47101. if (endKey.frame < endFrame) {
  47102. var newKey = {
  47103. frame: endFrame,
  47104. value: endKey.value,
  47105. inTangent: endKey.outTangent,
  47106. outTangent: endKey.outTangent,
  47107. interpolation: endKey.interpolation
  47108. };
  47109. keys.push(newKey);
  47110. }
  47111. }
  47112. return this;
  47113. };
  47114. /**
  47115. * Start all animations on given targets
  47116. * @param loop defines if animations must loop
  47117. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47118. */
  47119. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47120. var _this = this;
  47121. if (loop === void 0) { loop = false; }
  47122. if (speedRatio === void 0) { speedRatio = 1; }
  47123. if (this._isStarted || this._targetedAnimations.length === 0) {
  47124. return this;
  47125. }
  47126. var _loop_1 = function () {
  47127. var targetedAnimation = this_1._targetedAnimations[index];
  47128. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47129. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47130. }));
  47131. };
  47132. var this_1 = this;
  47133. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47134. _loop_1();
  47135. }
  47136. this._speedRatio = speedRatio;
  47137. this._isStarted = true;
  47138. return this;
  47139. };
  47140. /**
  47141. * Pause all animations
  47142. */
  47143. AnimationGroup.prototype.pause = function () {
  47144. if (!this._isStarted) {
  47145. return this;
  47146. }
  47147. for (var index = 0; index < this._animatables.length; index++) {
  47148. var animatable = this._animatables[index];
  47149. animatable.pause();
  47150. }
  47151. return this;
  47152. };
  47153. /**
  47154. * Play all animations to initial state
  47155. * This function will start() the animations if they were not started or will restart() them if they were paused
  47156. * @param loop defines if animations must loop
  47157. */
  47158. AnimationGroup.prototype.play = function (loop) {
  47159. if (this.isStarted) {
  47160. if (loop !== undefined) {
  47161. for (var index = 0; index < this._animatables.length; index++) {
  47162. var animatable = this._animatables[index];
  47163. animatable.loopAnimation = loop;
  47164. }
  47165. }
  47166. this.restart();
  47167. }
  47168. else {
  47169. this.start(loop, this._speedRatio);
  47170. }
  47171. return this;
  47172. };
  47173. /**
  47174. * Reset all animations to initial state
  47175. */
  47176. AnimationGroup.prototype.reset = function () {
  47177. if (!this._isStarted) {
  47178. return this;
  47179. }
  47180. for (var index = 0; index < this._animatables.length; index++) {
  47181. var animatable = this._animatables[index];
  47182. animatable.reset();
  47183. }
  47184. return this;
  47185. };
  47186. /**
  47187. * Restart animations from key 0
  47188. */
  47189. AnimationGroup.prototype.restart = function () {
  47190. if (!this._isStarted) {
  47191. return this;
  47192. }
  47193. for (var index = 0; index < this._animatables.length; index++) {
  47194. var animatable = this._animatables[index];
  47195. animatable.restart();
  47196. }
  47197. return this;
  47198. };
  47199. /**
  47200. * Stop all animations
  47201. */
  47202. AnimationGroup.prototype.stop = function () {
  47203. if (!this._isStarted) {
  47204. return this;
  47205. }
  47206. for (var index = 0; index < this._animatables.length; index++) {
  47207. var animatable = this._animatables[index];
  47208. animatable.stop();
  47209. }
  47210. this._isStarted = false;
  47211. return this;
  47212. };
  47213. /**
  47214. * Goes to a specific frame in this animation group
  47215. *
  47216. * @param frame the frame number to go to
  47217. * @return the animationGroup
  47218. */
  47219. AnimationGroup.prototype.goToFrame = function (frame) {
  47220. if (!this._isStarted) {
  47221. return this;
  47222. }
  47223. for (var index = 0; index < this._animatables.length; index++) {
  47224. var animatable = this._animatables[index];
  47225. animatable.goToFrame(frame);
  47226. }
  47227. return this;
  47228. };
  47229. /**
  47230. * Dispose all associated resources
  47231. */
  47232. AnimationGroup.prototype.dispose = function () {
  47233. this._targetedAnimations = [];
  47234. this._animatables = [];
  47235. var index = this._scene.animationGroups.indexOf(this);
  47236. if (index > -1) {
  47237. this._scene.animationGroups.splice(index, 1);
  47238. }
  47239. };
  47240. return AnimationGroup;
  47241. }());
  47242. BABYLON.AnimationGroup = AnimationGroup;
  47243. })(BABYLON || (BABYLON = {}));
  47244. //# sourceMappingURL=babylon.animationGroup.js.map
  47245. var BABYLON;
  47246. (function (BABYLON) {
  47247. var RuntimeAnimation = /** @class */ (function () {
  47248. function RuntimeAnimation(target, animation) {
  47249. this._offsetsCache = {};
  47250. this._highLimitsCache = {};
  47251. this._stopped = false;
  47252. this._blendingFactor = 0;
  47253. this._ratioOffset = 0;
  47254. this._animation = animation;
  47255. this._target = target;
  47256. animation._runtimeAnimations.push(this);
  47257. }
  47258. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47259. get: function () {
  47260. return this._animation;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. RuntimeAnimation.prototype.reset = function () {
  47266. this._offsetsCache = {};
  47267. this._highLimitsCache = {};
  47268. this.currentFrame = 0;
  47269. this._blendingFactor = 0;
  47270. this._originalBlendValue = null;
  47271. };
  47272. RuntimeAnimation.prototype.isStopped = function () {
  47273. return this._stopped;
  47274. };
  47275. RuntimeAnimation.prototype.dispose = function () {
  47276. var index = this._animation.runtimeAnimations.indexOf(this);
  47277. if (index > -1) {
  47278. this._animation.runtimeAnimations.splice(index, 1);
  47279. }
  47280. };
  47281. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47282. if (typeof value === "function") {
  47283. return value();
  47284. }
  47285. return value;
  47286. };
  47287. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47288. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47289. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47290. }
  47291. this.currentFrame = currentFrame;
  47292. var keys = this._animation.getKeys();
  47293. // Try to get a hash to find the right key
  47294. 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));
  47295. if (keys[startKeyIndex].frame >= currentFrame) {
  47296. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47297. startKeyIndex--;
  47298. }
  47299. }
  47300. for (var key = startKeyIndex; key < keys.length; key++) {
  47301. var endKey = keys[key + 1];
  47302. if (endKey.frame >= currentFrame) {
  47303. var startKey = keys[key];
  47304. var startValue = this._getKeyValue(startKey.value);
  47305. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47306. return startValue;
  47307. }
  47308. var endValue = this._getKeyValue(endKey.value);
  47309. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47310. var frameDelta = endKey.frame - startKey.frame;
  47311. // gradient : percent of currentFrame between the frame inf and the frame sup
  47312. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47313. // check for easingFunction and correction of gradient
  47314. var easingFunction = this._animation.getEasingFunction();
  47315. if (easingFunction != null) {
  47316. gradient = easingFunction.ease(gradient);
  47317. }
  47318. switch (this._animation.dataType) {
  47319. // Float
  47320. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47321. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47322. switch (loopMode) {
  47323. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47324. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47325. return floatValue;
  47326. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47327. return offsetValue * repeatCount + floatValue;
  47328. }
  47329. break;
  47330. // Quaternion
  47331. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47332. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47333. switch (loopMode) {
  47334. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47335. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47336. return quatValue;
  47337. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47338. return quatValue.add(offsetValue.scale(repeatCount));
  47339. }
  47340. return quatValue;
  47341. // Vector3
  47342. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47343. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47344. switch (loopMode) {
  47345. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47346. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47347. return vec3Value;
  47348. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47349. return vec3Value.add(offsetValue.scale(repeatCount));
  47350. }
  47351. // Vector2
  47352. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47353. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47354. switch (loopMode) {
  47355. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47356. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47357. return vec2Value;
  47358. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47359. return vec2Value.add(offsetValue.scale(repeatCount));
  47360. }
  47361. // Size
  47362. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47363. switch (loopMode) {
  47364. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47365. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47366. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47367. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47368. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47369. }
  47370. // Color3
  47371. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47372. switch (loopMode) {
  47373. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47374. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47375. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47376. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47377. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47378. }
  47379. // Matrix
  47380. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47381. switch (loopMode) {
  47382. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47383. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47384. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47385. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47386. }
  47387. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47388. return startValue;
  47389. }
  47390. default:
  47391. break;
  47392. }
  47393. break;
  47394. }
  47395. }
  47396. return this._getKeyValue(keys[keys.length - 1].value);
  47397. };
  47398. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47399. if (blend === void 0) { blend = false; }
  47400. // Set value
  47401. var path;
  47402. var destination;
  47403. var targetPropertyPath = this._animation.targetPropertyPath;
  47404. if (targetPropertyPath.length > 1) {
  47405. var property = this._target[targetPropertyPath[0]];
  47406. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47407. property = property[targetPropertyPath[index]];
  47408. }
  47409. path = targetPropertyPath[targetPropertyPath.length - 1];
  47410. destination = property;
  47411. }
  47412. else {
  47413. path = targetPropertyPath[0];
  47414. destination = this._target;
  47415. }
  47416. // Blending
  47417. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47418. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47419. if (enableBlending && this._blendingFactor <= 1.0) {
  47420. if (!this._originalBlendValue) {
  47421. if (destination[path].clone) {
  47422. this._originalBlendValue = destination[path].clone();
  47423. }
  47424. else {
  47425. this._originalBlendValue = destination[path];
  47426. }
  47427. }
  47428. if (this._originalBlendValue.prototype) {
  47429. if (this._originalBlendValue.prototype.Lerp) {
  47430. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47431. }
  47432. else {
  47433. destination[path] = currentValue;
  47434. }
  47435. }
  47436. else if (this._originalBlendValue.m) {
  47437. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47438. }
  47439. else {
  47440. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47441. }
  47442. this._blendingFactor += blendingSpeed;
  47443. }
  47444. else {
  47445. destination[path] = currentValue;
  47446. }
  47447. if (this._target.markAsDirty) {
  47448. this._target.markAsDirty(this._animation.targetProperty);
  47449. }
  47450. };
  47451. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47452. if (this._target && this._target.animationPropertiesOverride) {
  47453. return this._target.animationPropertiesOverride.loopMode;
  47454. }
  47455. return this._animation.loopMode;
  47456. };
  47457. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47458. var keys = this._animation.getKeys();
  47459. if (frame < keys[0].frame) {
  47460. frame = keys[0].frame;
  47461. }
  47462. else if (frame > keys[keys.length - 1].frame) {
  47463. frame = keys[keys.length - 1].frame;
  47464. }
  47465. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47466. this.setValue(currentValue);
  47467. };
  47468. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47469. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47470. this._ratioOffset = this._previousRatio - newRatio;
  47471. };
  47472. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47473. if (blend === void 0) { blend = false; }
  47474. var targetPropertyPath = this._animation.targetPropertyPath;
  47475. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47476. this._stopped = true;
  47477. return false;
  47478. }
  47479. var returnValue = true;
  47480. var keys = this._animation.getKeys();
  47481. // Adding a start key at frame 0 if missing
  47482. if (keys[0].frame !== 0) {
  47483. var newKey = { frame: 0, value: keys[0].value };
  47484. keys.splice(0, 0, newKey);
  47485. }
  47486. // Check limits
  47487. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47488. from = keys[0].frame;
  47489. }
  47490. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47491. to = keys[keys.length - 1].frame;
  47492. }
  47493. //to and from cannot be the same key
  47494. if (from === to) {
  47495. if (from > keys[0].frame) {
  47496. from--;
  47497. }
  47498. else if (to < keys[keys.length - 1].frame) {
  47499. to++;
  47500. }
  47501. }
  47502. // Compute ratio
  47503. var range = to - from;
  47504. var offsetValue;
  47505. // ratio represents the frame delta between from and to
  47506. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47507. var highLimitValue = 0;
  47508. this._previousDelay = delay;
  47509. this._previousRatio = ratio;
  47510. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47511. returnValue = false;
  47512. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47513. }
  47514. else {
  47515. // Get max value if required
  47516. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47517. var keyOffset = to.toString() + from.toString();
  47518. if (!this._offsetsCache[keyOffset]) {
  47519. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47520. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47521. switch (this._animation.dataType) {
  47522. // Float
  47523. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47524. this._offsetsCache[keyOffset] = toValue - fromValue;
  47525. break;
  47526. // Quaternion
  47527. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47528. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47529. break;
  47530. // Vector3
  47531. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47532. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47533. // Vector2
  47534. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47535. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47536. // Size
  47537. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47538. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47539. // Color3
  47540. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47541. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47542. default:
  47543. break;
  47544. }
  47545. this._highLimitsCache[keyOffset] = toValue;
  47546. }
  47547. highLimitValue = this._highLimitsCache[keyOffset];
  47548. offsetValue = this._offsetsCache[keyOffset];
  47549. }
  47550. }
  47551. if (offsetValue === undefined) {
  47552. switch (this._animation.dataType) {
  47553. // Float
  47554. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47555. offsetValue = 0;
  47556. break;
  47557. // Quaternion
  47558. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47559. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47560. break;
  47561. // Vector3
  47562. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47563. offsetValue = BABYLON.Vector3.Zero();
  47564. break;
  47565. // Vector2
  47566. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47567. offsetValue = BABYLON.Vector2.Zero();
  47568. break;
  47569. // Size
  47570. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47571. offsetValue = BABYLON.Size.Zero();
  47572. break;
  47573. // Color3
  47574. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47575. offsetValue = BABYLON.Color3.Black();
  47576. }
  47577. }
  47578. // Compute value
  47579. var repeatCount = (ratio / range) >> 0;
  47580. var currentFrame = returnValue ? from + ratio % range : to;
  47581. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47582. // Set value
  47583. this.setValue(currentValue);
  47584. // Check events
  47585. var events = this._animation.getEvents();
  47586. for (var index = 0; index < events.length; index++) {
  47587. // Make sure current frame has passed event frame and that event frame is within the current range
  47588. // Also, handle both forward and reverse animations
  47589. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47590. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47591. var event = events[index];
  47592. if (!event.isDone) {
  47593. // If event should be done only once, remove it.
  47594. if (event.onlyOnce) {
  47595. events.splice(index, 1);
  47596. index--;
  47597. }
  47598. event.isDone = true;
  47599. event.action();
  47600. } // Don't do anything if the event has already be done.
  47601. }
  47602. else if (events[index].isDone && !events[index].onlyOnce) {
  47603. // reset event, the animation is looping
  47604. events[index].isDone = false;
  47605. }
  47606. }
  47607. if (!returnValue) {
  47608. this._stopped = true;
  47609. }
  47610. return returnValue;
  47611. };
  47612. return RuntimeAnimation;
  47613. }());
  47614. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47615. })(BABYLON || (BABYLON = {}));
  47616. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47617. var BABYLON;
  47618. (function (BABYLON) {
  47619. var Animatable = /** @class */ (function () {
  47620. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47621. if (fromFrame === void 0) { fromFrame = 0; }
  47622. if (toFrame === void 0) { toFrame = 100; }
  47623. if (loopAnimation === void 0) { loopAnimation = false; }
  47624. if (speedRatio === void 0) { speedRatio = 1.0; }
  47625. this.target = target;
  47626. this.fromFrame = fromFrame;
  47627. this.toFrame = toFrame;
  47628. this.loopAnimation = loopAnimation;
  47629. this.onAnimationEnd = onAnimationEnd;
  47630. this._localDelayOffset = null;
  47631. this._pausedDelay = null;
  47632. this._runtimeAnimations = new Array();
  47633. this._paused = false;
  47634. this._speedRatio = 1;
  47635. this.animationStarted = false;
  47636. if (animations) {
  47637. this.appendAnimations(target, animations);
  47638. }
  47639. this._speedRatio = speedRatio;
  47640. this._scene = scene;
  47641. scene._activeAnimatables.push(this);
  47642. }
  47643. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47644. get: function () {
  47645. return this._speedRatio;
  47646. },
  47647. set: function (value) {
  47648. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47649. var animation = this._runtimeAnimations[index];
  47650. animation._prepareForSpeedRatioChange(value);
  47651. }
  47652. this._speedRatio = value;
  47653. },
  47654. enumerable: true,
  47655. configurable: true
  47656. });
  47657. // Methods
  47658. Animatable.prototype.getAnimations = function () {
  47659. return this._runtimeAnimations;
  47660. };
  47661. Animatable.prototype.appendAnimations = function (target, animations) {
  47662. for (var index = 0; index < animations.length; index++) {
  47663. var animation = animations[index];
  47664. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47665. }
  47666. };
  47667. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47668. var runtimeAnimations = this._runtimeAnimations;
  47669. for (var index = 0; index < runtimeAnimations.length; index++) {
  47670. if (runtimeAnimations[index].animation.targetProperty === property) {
  47671. return runtimeAnimations[index].animation;
  47672. }
  47673. }
  47674. return null;
  47675. };
  47676. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47677. var runtimeAnimations = this._runtimeAnimations;
  47678. for (var index = 0; index < runtimeAnimations.length; index++) {
  47679. if (runtimeAnimations[index].animation.targetProperty === property) {
  47680. return runtimeAnimations[index];
  47681. }
  47682. }
  47683. return null;
  47684. };
  47685. Animatable.prototype.reset = function () {
  47686. var runtimeAnimations = this._runtimeAnimations;
  47687. for (var index = 0; index < runtimeAnimations.length; index++) {
  47688. runtimeAnimations[index].reset();
  47689. }
  47690. // Reset to original value
  47691. for (index = 0; index < runtimeAnimations.length; index++) {
  47692. var animation = runtimeAnimations[index];
  47693. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47694. }
  47695. this._localDelayOffset = null;
  47696. this._pausedDelay = null;
  47697. };
  47698. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47699. var runtimeAnimations = this._runtimeAnimations;
  47700. for (var index = 0; index < runtimeAnimations.length; index++) {
  47701. runtimeAnimations[index].animation.enableBlending = true;
  47702. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47703. }
  47704. };
  47705. Animatable.prototype.disableBlending = function () {
  47706. var runtimeAnimations = this._runtimeAnimations;
  47707. for (var index = 0; index < runtimeAnimations.length; index++) {
  47708. runtimeAnimations[index].animation.enableBlending = false;
  47709. }
  47710. };
  47711. Animatable.prototype.goToFrame = function (frame) {
  47712. var runtimeAnimations = this._runtimeAnimations;
  47713. if (runtimeAnimations[0]) {
  47714. var fps = runtimeAnimations[0].animation.framePerSecond;
  47715. var currentFrame = runtimeAnimations[0].currentFrame;
  47716. var adjustTime = frame - currentFrame;
  47717. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47718. if (this._localDelayOffset === null) {
  47719. this._localDelayOffset = 0;
  47720. }
  47721. this._localDelayOffset -= delay;
  47722. }
  47723. for (var index = 0; index < runtimeAnimations.length; index++) {
  47724. runtimeAnimations[index].goToFrame(frame);
  47725. }
  47726. };
  47727. Animatable.prototype.pause = function () {
  47728. if (this._paused) {
  47729. return;
  47730. }
  47731. this._paused = true;
  47732. };
  47733. Animatable.prototype.restart = function () {
  47734. this._paused = false;
  47735. };
  47736. Animatable.prototype.stop = function (animationName) {
  47737. if (animationName) {
  47738. var idx = this._scene._activeAnimatables.indexOf(this);
  47739. if (idx > -1) {
  47740. var runtimeAnimations = this._runtimeAnimations;
  47741. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47742. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47743. continue;
  47744. }
  47745. runtimeAnimations[index].dispose();
  47746. runtimeAnimations.splice(index, 1);
  47747. }
  47748. if (runtimeAnimations.length == 0) {
  47749. this._scene._activeAnimatables.splice(idx, 1);
  47750. if (this.onAnimationEnd) {
  47751. this.onAnimationEnd();
  47752. }
  47753. }
  47754. }
  47755. }
  47756. else {
  47757. var index = this._scene._activeAnimatables.indexOf(this);
  47758. if (index > -1) {
  47759. this._scene._activeAnimatables.splice(index, 1);
  47760. var runtimeAnimations = this._runtimeAnimations;
  47761. for (var index = 0; index < runtimeAnimations.length; index++) {
  47762. runtimeAnimations[index].dispose();
  47763. }
  47764. if (this.onAnimationEnd) {
  47765. this.onAnimationEnd();
  47766. }
  47767. }
  47768. }
  47769. };
  47770. Animatable.prototype._animate = function (delay) {
  47771. if (this._paused) {
  47772. this.animationStarted = false;
  47773. if (this._pausedDelay === null) {
  47774. this._pausedDelay = delay;
  47775. }
  47776. return true;
  47777. }
  47778. if (this._localDelayOffset === null) {
  47779. this._localDelayOffset = delay;
  47780. this._pausedDelay = null;
  47781. }
  47782. else if (this._pausedDelay !== null) {
  47783. this._localDelayOffset += delay - this._pausedDelay;
  47784. this._pausedDelay = null;
  47785. }
  47786. // Animating
  47787. var running = false;
  47788. var runtimeAnimations = this._runtimeAnimations;
  47789. var index;
  47790. for (index = 0; index < runtimeAnimations.length; index++) {
  47791. var animation = runtimeAnimations[index];
  47792. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47793. running = running || isRunning;
  47794. }
  47795. this.animationStarted = running;
  47796. if (!running) {
  47797. // Remove from active animatables
  47798. index = this._scene._activeAnimatables.indexOf(this);
  47799. this._scene._activeAnimatables.splice(index, 1);
  47800. // Dispose all runtime animations
  47801. for (index = 0; index < runtimeAnimations.length; index++) {
  47802. runtimeAnimations[index].dispose();
  47803. }
  47804. }
  47805. if (!running && this.onAnimationEnd) {
  47806. this.onAnimationEnd();
  47807. this.onAnimationEnd = null;
  47808. }
  47809. return running;
  47810. };
  47811. return Animatable;
  47812. }());
  47813. BABYLON.Animatable = Animatable;
  47814. })(BABYLON || (BABYLON = {}));
  47815. //# sourceMappingURL=babylon.animatable.js.map
  47816. var BABYLON;
  47817. (function (BABYLON) {
  47818. var EasingFunction = /** @class */ (function () {
  47819. function EasingFunction() {
  47820. // Properties
  47821. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47822. }
  47823. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47824. get: function () {
  47825. return EasingFunction._EASINGMODE_EASEIN;
  47826. },
  47827. enumerable: true,
  47828. configurable: true
  47829. });
  47830. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47831. get: function () {
  47832. return EasingFunction._EASINGMODE_EASEOUT;
  47833. },
  47834. enumerable: true,
  47835. configurable: true
  47836. });
  47837. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47838. get: function () {
  47839. return EasingFunction._EASINGMODE_EASEINOUT;
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47845. var n = Math.min(Math.max(easingMode, 0), 2);
  47846. this._easingMode = n;
  47847. };
  47848. EasingFunction.prototype.getEasingMode = function () {
  47849. return this._easingMode;
  47850. };
  47851. EasingFunction.prototype.easeInCore = function (gradient) {
  47852. throw new Error('You must implement this method');
  47853. };
  47854. EasingFunction.prototype.ease = function (gradient) {
  47855. switch (this._easingMode) {
  47856. case EasingFunction.EASINGMODE_EASEIN:
  47857. return this.easeInCore(gradient);
  47858. case EasingFunction.EASINGMODE_EASEOUT:
  47859. return (1 - this.easeInCore(1 - gradient));
  47860. }
  47861. if (gradient >= 0.5) {
  47862. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47863. }
  47864. return (this.easeInCore(gradient * 2) * 0.5);
  47865. };
  47866. //Statics
  47867. EasingFunction._EASINGMODE_EASEIN = 0;
  47868. EasingFunction._EASINGMODE_EASEOUT = 1;
  47869. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47870. return EasingFunction;
  47871. }());
  47872. BABYLON.EasingFunction = EasingFunction;
  47873. var CircleEase = /** @class */ (function (_super) {
  47874. __extends(CircleEase, _super);
  47875. function CircleEase() {
  47876. return _super !== null && _super.apply(this, arguments) || this;
  47877. }
  47878. CircleEase.prototype.easeInCore = function (gradient) {
  47879. gradient = Math.max(0, Math.min(1, gradient));
  47880. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47881. };
  47882. return CircleEase;
  47883. }(EasingFunction));
  47884. BABYLON.CircleEase = CircleEase;
  47885. var BackEase = /** @class */ (function (_super) {
  47886. __extends(BackEase, _super);
  47887. function BackEase(amplitude) {
  47888. if (amplitude === void 0) { amplitude = 1; }
  47889. var _this = _super.call(this) || this;
  47890. _this.amplitude = amplitude;
  47891. return _this;
  47892. }
  47893. BackEase.prototype.easeInCore = function (gradient) {
  47894. var num = Math.max(0, this.amplitude);
  47895. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47896. };
  47897. return BackEase;
  47898. }(EasingFunction));
  47899. BABYLON.BackEase = BackEase;
  47900. var BounceEase = /** @class */ (function (_super) {
  47901. __extends(BounceEase, _super);
  47902. function BounceEase(bounces, bounciness) {
  47903. if (bounces === void 0) { bounces = 3; }
  47904. if (bounciness === void 0) { bounciness = 2; }
  47905. var _this = _super.call(this) || this;
  47906. _this.bounces = bounces;
  47907. _this.bounciness = bounciness;
  47908. return _this;
  47909. }
  47910. BounceEase.prototype.easeInCore = function (gradient) {
  47911. var y = Math.max(0.0, this.bounces);
  47912. var bounciness = this.bounciness;
  47913. if (bounciness <= 1.0) {
  47914. bounciness = 1.001;
  47915. }
  47916. var num9 = Math.pow(bounciness, y);
  47917. var num5 = 1.0 - bounciness;
  47918. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47919. var num15 = gradient * num4;
  47920. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47921. var num3 = Math.floor(num65);
  47922. var num13 = num3 + 1.0;
  47923. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47924. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47925. var num7 = (num8 + num12) * 0.5;
  47926. var num6 = gradient - num7;
  47927. var num2 = num7 - num8;
  47928. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47929. };
  47930. return BounceEase;
  47931. }(EasingFunction));
  47932. BABYLON.BounceEase = BounceEase;
  47933. var CubicEase = /** @class */ (function (_super) {
  47934. __extends(CubicEase, _super);
  47935. function CubicEase() {
  47936. return _super !== null && _super.apply(this, arguments) || this;
  47937. }
  47938. CubicEase.prototype.easeInCore = function (gradient) {
  47939. return (gradient * gradient * gradient);
  47940. };
  47941. return CubicEase;
  47942. }(EasingFunction));
  47943. BABYLON.CubicEase = CubicEase;
  47944. var ElasticEase = /** @class */ (function (_super) {
  47945. __extends(ElasticEase, _super);
  47946. function ElasticEase(oscillations, springiness) {
  47947. if (oscillations === void 0) { oscillations = 3; }
  47948. if (springiness === void 0) { springiness = 3; }
  47949. var _this = _super.call(this) || this;
  47950. _this.oscillations = oscillations;
  47951. _this.springiness = springiness;
  47952. return _this;
  47953. }
  47954. ElasticEase.prototype.easeInCore = function (gradient) {
  47955. var num2;
  47956. var num3 = Math.max(0.0, this.oscillations);
  47957. var num = Math.max(0.0, this.springiness);
  47958. if (num == 0) {
  47959. num2 = gradient;
  47960. }
  47961. else {
  47962. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47963. }
  47964. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47965. };
  47966. return ElasticEase;
  47967. }(EasingFunction));
  47968. BABYLON.ElasticEase = ElasticEase;
  47969. var ExponentialEase = /** @class */ (function (_super) {
  47970. __extends(ExponentialEase, _super);
  47971. function ExponentialEase(exponent) {
  47972. if (exponent === void 0) { exponent = 2; }
  47973. var _this = _super.call(this) || this;
  47974. _this.exponent = exponent;
  47975. return _this;
  47976. }
  47977. ExponentialEase.prototype.easeInCore = function (gradient) {
  47978. if (this.exponent <= 0) {
  47979. return gradient;
  47980. }
  47981. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47982. };
  47983. return ExponentialEase;
  47984. }(EasingFunction));
  47985. BABYLON.ExponentialEase = ExponentialEase;
  47986. var PowerEase = /** @class */ (function (_super) {
  47987. __extends(PowerEase, _super);
  47988. function PowerEase(power) {
  47989. if (power === void 0) { power = 2; }
  47990. var _this = _super.call(this) || this;
  47991. _this.power = power;
  47992. return _this;
  47993. }
  47994. PowerEase.prototype.easeInCore = function (gradient) {
  47995. var y = Math.max(0.0, this.power);
  47996. return Math.pow(gradient, y);
  47997. };
  47998. return PowerEase;
  47999. }(EasingFunction));
  48000. BABYLON.PowerEase = PowerEase;
  48001. var QuadraticEase = /** @class */ (function (_super) {
  48002. __extends(QuadraticEase, _super);
  48003. function QuadraticEase() {
  48004. return _super !== null && _super.apply(this, arguments) || this;
  48005. }
  48006. QuadraticEase.prototype.easeInCore = function (gradient) {
  48007. return (gradient * gradient);
  48008. };
  48009. return QuadraticEase;
  48010. }(EasingFunction));
  48011. BABYLON.QuadraticEase = QuadraticEase;
  48012. var QuarticEase = /** @class */ (function (_super) {
  48013. __extends(QuarticEase, _super);
  48014. function QuarticEase() {
  48015. return _super !== null && _super.apply(this, arguments) || this;
  48016. }
  48017. QuarticEase.prototype.easeInCore = function (gradient) {
  48018. return (gradient * gradient * gradient * gradient);
  48019. };
  48020. return QuarticEase;
  48021. }(EasingFunction));
  48022. BABYLON.QuarticEase = QuarticEase;
  48023. var QuinticEase = /** @class */ (function (_super) {
  48024. __extends(QuinticEase, _super);
  48025. function QuinticEase() {
  48026. return _super !== null && _super.apply(this, arguments) || this;
  48027. }
  48028. QuinticEase.prototype.easeInCore = function (gradient) {
  48029. return (gradient * gradient * gradient * gradient * gradient);
  48030. };
  48031. return QuinticEase;
  48032. }(EasingFunction));
  48033. BABYLON.QuinticEase = QuinticEase;
  48034. var SineEase = /** @class */ (function (_super) {
  48035. __extends(SineEase, _super);
  48036. function SineEase() {
  48037. return _super !== null && _super.apply(this, arguments) || this;
  48038. }
  48039. SineEase.prototype.easeInCore = function (gradient) {
  48040. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48041. };
  48042. return SineEase;
  48043. }(EasingFunction));
  48044. BABYLON.SineEase = SineEase;
  48045. var BezierCurveEase = /** @class */ (function (_super) {
  48046. __extends(BezierCurveEase, _super);
  48047. function BezierCurveEase(x1, y1, x2, y2) {
  48048. if (x1 === void 0) { x1 = 0; }
  48049. if (y1 === void 0) { y1 = 0; }
  48050. if (x2 === void 0) { x2 = 1; }
  48051. if (y2 === void 0) { y2 = 1; }
  48052. var _this = _super.call(this) || this;
  48053. _this.x1 = x1;
  48054. _this.y1 = y1;
  48055. _this.x2 = x2;
  48056. _this.y2 = y2;
  48057. return _this;
  48058. }
  48059. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48060. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48061. };
  48062. return BezierCurveEase;
  48063. }(EasingFunction));
  48064. BABYLON.BezierCurveEase = BezierCurveEase;
  48065. })(BABYLON || (BABYLON = {}));
  48066. //# sourceMappingURL=babylon.easing.js.map
  48067. var BABYLON;
  48068. (function (BABYLON) {
  48069. var Condition = /** @class */ (function () {
  48070. function Condition(actionManager) {
  48071. this._actionManager = actionManager;
  48072. }
  48073. Condition.prototype.isValid = function () {
  48074. return true;
  48075. };
  48076. Condition.prototype._getProperty = function (propertyPath) {
  48077. return this._actionManager._getProperty(propertyPath);
  48078. };
  48079. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48080. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48081. };
  48082. Condition.prototype.serialize = function () {
  48083. };
  48084. Condition.prototype._serialize = function (serializedCondition) {
  48085. return {
  48086. type: 2,
  48087. children: [],
  48088. name: serializedCondition.name,
  48089. properties: serializedCondition.properties
  48090. };
  48091. };
  48092. return Condition;
  48093. }());
  48094. BABYLON.Condition = Condition;
  48095. var ValueCondition = /** @class */ (function (_super) {
  48096. __extends(ValueCondition, _super);
  48097. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48098. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48099. var _this = _super.call(this, actionManager) || this;
  48100. _this.propertyPath = propertyPath;
  48101. _this.value = value;
  48102. _this.operator = operator;
  48103. _this._target = target;
  48104. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48105. _this._property = _this._getProperty(_this.propertyPath);
  48106. return _this;
  48107. }
  48108. Object.defineProperty(ValueCondition, "IsEqual", {
  48109. get: function () {
  48110. return ValueCondition._IsEqual;
  48111. },
  48112. enumerable: true,
  48113. configurable: true
  48114. });
  48115. Object.defineProperty(ValueCondition, "IsDifferent", {
  48116. get: function () {
  48117. return ValueCondition._IsDifferent;
  48118. },
  48119. enumerable: true,
  48120. configurable: true
  48121. });
  48122. Object.defineProperty(ValueCondition, "IsGreater", {
  48123. get: function () {
  48124. return ValueCondition._IsGreater;
  48125. },
  48126. enumerable: true,
  48127. configurable: true
  48128. });
  48129. Object.defineProperty(ValueCondition, "IsLesser", {
  48130. get: function () {
  48131. return ValueCondition._IsLesser;
  48132. },
  48133. enumerable: true,
  48134. configurable: true
  48135. });
  48136. // Methods
  48137. ValueCondition.prototype.isValid = function () {
  48138. switch (this.operator) {
  48139. case ValueCondition.IsGreater:
  48140. return this._effectiveTarget[this._property] > this.value;
  48141. case ValueCondition.IsLesser:
  48142. return this._effectiveTarget[this._property] < this.value;
  48143. case ValueCondition.IsEqual:
  48144. case ValueCondition.IsDifferent:
  48145. var check;
  48146. if (this.value.equals) {
  48147. check = this.value.equals(this._effectiveTarget[this._property]);
  48148. }
  48149. else {
  48150. check = this.value === this._effectiveTarget[this._property];
  48151. }
  48152. return this.operator === ValueCondition.IsEqual ? check : !check;
  48153. }
  48154. return false;
  48155. };
  48156. ValueCondition.prototype.serialize = function () {
  48157. return this._serialize({
  48158. name: "ValueCondition",
  48159. properties: [
  48160. BABYLON.Action._GetTargetProperty(this._target),
  48161. { name: "propertyPath", value: this.propertyPath },
  48162. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48163. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48164. ]
  48165. });
  48166. };
  48167. ValueCondition.GetOperatorName = function (operator) {
  48168. switch (operator) {
  48169. case ValueCondition._IsEqual: return "IsEqual";
  48170. case ValueCondition._IsDifferent: return "IsDifferent";
  48171. case ValueCondition._IsGreater: return "IsGreater";
  48172. case ValueCondition._IsLesser: return "IsLesser";
  48173. default: return "";
  48174. }
  48175. };
  48176. // Statics
  48177. ValueCondition._IsEqual = 0;
  48178. ValueCondition._IsDifferent = 1;
  48179. ValueCondition._IsGreater = 2;
  48180. ValueCondition._IsLesser = 3;
  48181. return ValueCondition;
  48182. }(Condition));
  48183. BABYLON.ValueCondition = ValueCondition;
  48184. var PredicateCondition = /** @class */ (function (_super) {
  48185. __extends(PredicateCondition, _super);
  48186. function PredicateCondition(actionManager, predicate) {
  48187. var _this = _super.call(this, actionManager) || this;
  48188. _this.predicate = predicate;
  48189. return _this;
  48190. }
  48191. PredicateCondition.prototype.isValid = function () {
  48192. return this.predicate();
  48193. };
  48194. return PredicateCondition;
  48195. }(Condition));
  48196. BABYLON.PredicateCondition = PredicateCondition;
  48197. var StateCondition = /** @class */ (function (_super) {
  48198. __extends(StateCondition, _super);
  48199. function StateCondition(actionManager, target, value) {
  48200. var _this = _super.call(this, actionManager) || this;
  48201. _this.value = value;
  48202. _this._target = target;
  48203. return _this;
  48204. }
  48205. // Methods
  48206. StateCondition.prototype.isValid = function () {
  48207. return this._target.state === this.value;
  48208. };
  48209. StateCondition.prototype.serialize = function () {
  48210. return this._serialize({
  48211. name: "StateCondition",
  48212. properties: [
  48213. BABYLON.Action._GetTargetProperty(this._target),
  48214. { name: "value", value: this.value }
  48215. ]
  48216. });
  48217. };
  48218. return StateCondition;
  48219. }(Condition));
  48220. BABYLON.StateCondition = StateCondition;
  48221. })(BABYLON || (BABYLON = {}));
  48222. //# sourceMappingURL=babylon.condition.js.map
  48223. var BABYLON;
  48224. (function (BABYLON) {
  48225. var Action = /** @class */ (function () {
  48226. function Action(triggerOptions, condition) {
  48227. this.triggerOptions = triggerOptions;
  48228. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48229. if (triggerOptions.parameter) {
  48230. this.trigger = triggerOptions.trigger;
  48231. this._triggerParameter = triggerOptions.parameter;
  48232. }
  48233. else {
  48234. this.trigger = triggerOptions;
  48235. }
  48236. this._nextActiveAction = this;
  48237. this._condition = condition;
  48238. }
  48239. // Methods
  48240. Action.prototype._prepare = function () {
  48241. };
  48242. Action.prototype.getTriggerParameter = function () {
  48243. return this._triggerParameter;
  48244. };
  48245. Action.prototype._executeCurrent = function (evt) {
  48246. if (this._nextActiveAction._condition) {
  48247. var condition = this._nextActiveAction._condition;
  48248. var currentRenderId = this._actionManager.getScene().getRenderId();
  48249. // We cache the current evaluation for the current frame
  48250. if (condition._evaluationId === currentRenderId) {
  48251. if (!condition._currentResult) {
  48252. return;
  48253. }
  48254. }
  48255. else {
  48256. condition._evaluationId = currentRenderId;
  48257. if (!condition.isValid()) {
  48258. condition._currentResult = false;
  48259. return;
  48260. }
  48261. condition._currentResult = true;
  48262. }
  48263. }
  48264. this.onBeforeExecuteObservable.notifyObservers(this);
  48265. this._nextActiveAction.execute(evt);
  48266. this.skipToNextActiveAction();
  48267. };
  48268. Action.prototype.execute = function (evt) {
  48269. };
  48270. Action.prototype.skipToNextActiveAction = function () {
  48271. if (this._nextActiveAction._child) {
  48272. if (!this._nextActiveAction._child._actionManager) {
  48273. this._nextActiveAction._child._actionManager = this._actionManager;
  48274. }
  48275. this._nextActiveAction = this._nextActiveAction._child;
  48276. }
  48277. else {
  48278. this._nextActiveAction = this;
  48279. }
  48280. };
  48281. Action.prototype.then = function (action) {
  48282. this._child = action;
  48283. action._actionManager = this._actionManager;
  48284. action._prepare();
  48285. return action;
  48286. };
  48287. Action.prototype._getProperty = function (propertyPath) {
  48288. return this._actionManager._getProperty(propertyPath);
  48289. };
  48290. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48291. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48292. };
  48293. Action.prototype.serialize = function (parent) {
  48294. };
  48295. // Called by BABYLON.Action objects in serialize(...). Internal use
  48296. Action.prototype._serialize = function (serializedAction, parent) {
  48297. var serializationObject = {
  48298. type: 1,
  48299. children: [],
  48300. name: serializedAction.name,
  48301. properties: serializedAction.properties || []
  48302. };
  48303. // Serialize child
  48304. if (this._child) {
  48305. this._child.serialize(serializationObject);
  48306. }
  48307. // Check if "this" has a condition
  48308. if (this._condition) {
  48309. var serializedCondition = this._condition.serialize();
  48310. serializedCondition.children.push(serializationObject);
  48311. if (parent) {
  48312. parent.children.push(serializedCondition);
  48313. }
  48314. return serializedCondition;
  48315. }
  48316. if (parent) {
  48317. parent.children.push(serializationObject);
  48318. }
  48319. return serializationObject;
  48320. };
  48321. Action._SerializeValueAsString = function (value) {
  48322. if (typeof value === "number") {
  48323. return value.toString();
  48324. }
  48325. if (typeof value === "boolean") {
  48326. return value ? "true" : "false";
  48327. }
  48328. if (value instanceof BABYLON.Vector2) {
  48329. return value.x + ", " + value.y;
  48330. }
  48331. if (value instanceof BABYLON.Vector3) {
  48332. return value.x + ", " + value.y + ", " + value.z;
  48333. }
  48334. if (value instanceof BABYLON.Color3) {
  48335. return value.r + ", " + value.g + ", " + value.b;
  48336. }
  48337. if (value instanceof BABYLON.Color4) {
  48338. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48339. }
  48340. return value; // string
  48341. };
  48342. Action._GetTargetProperty = function (target) {
  48343. return {
  48344. name: "target",
  48345. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48346. : target instanceof BABYLON.Light ? "LightProperties"
  48347. : target instanceof BABYLON.Camera ? "CameraProperties"
  48348. : "SceneProperties",
  48349. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48350. };
  48351. };
  48352. return Action;
  48353. }());
  48354. BABYLON.Action = Action;
  48355. })(BABYLON || (BABYLON = {}));
  48356. //# sourceMappingURL=babylon.action.js.map
  48357. var BABYLON;
  48358. (function (BABYLON) {
  48359. /**
  48360. * ActionEvent is the event beint sent when an action is triggered.
  48361. */
  48362. var ActionEvent = /** @class */ (function () {
  48363. /**
  48364. * @param source The mesh or sprite that triggered the action.
  48365. * @param pointerX The X mouse cursor position at the time of the event
  48366. * @param pointerY The Y mouse cursor position at the time of the event
  48367. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48368. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48369. */
  48370. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48371. this.source = source;
  48372. this.pointerX = pointerX;
  48373. this.pointerY = pointerY;
  48374. this.meshUnderPointer = meshUnderPointer;
  48375. this.sourceEvent = sourceEvent;
  48376. this.additionalData = additionalData;
  48377. }
  48378. /**
  48379. * Helper function to auto-create an ActionEvent from a source mesh.
  48380. * @param source The source mesh that triggered the event
  48381. * @param evt {Event} The original (browser) event
  48382. */
  48383. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48384. var scene = source.getScene();
  48385. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48386. };
  48387. /**
  48388. * Helper function to auto-create an ActionEvent from a source mesh.
  48389. * @param source The source sprite that triggered the event
  48390. * @param scene Scene associated with the sprite
  48391. * @param evt {Event} The original (browser) event
  48392. */
  48393. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48394. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48395. };
  48396. /**
  48397. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48398. * @param scene the scene where the event occurred
  48399. * @param evt {Event} The original (browser) event
  48400. */
  48401. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48402. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48403. };
  48404. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48405. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48406. };
  48407. return ActionEvent;
  48408. }());
  48409. BABYLON.ActionEvent = ActionEvent;
  48410. /**
  48411. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48412. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48413. */
  48414. var ActionManager = /** @class */ (function () {
  48415. function ActionManager(scene) {
  48416. // Members
  48417. this.actions = new Array();
  48418. this.hoverCursor = '';
  48419. this._scene = scene;
  48420. scene._actionManagers.push(this);
  48421. }
  48422. Object.defineProperty(ActionManager, "NothingTrigger", {
  48423. get: function () {
  48424. return ActionManager._NothingTrigger;
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48430. get: function () {
  48431. return ActionManager._OnPickTrigger;
  48432. },
  48433. enumerable: true,
  48434. configurable: true
  48435. });
  48436. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48437. get: function () {
  48438. return ActionManager._OnLeftPickTrigger;
  48439. },
  48440. enumerable: true,
  48441. configurable: true
  48442. });
  48443. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48444. get: function () {
  48445. return ActionManager._OnRightPickTrigger;
  48446. },
  48447. enumerable: true,
  48448. configurable: true
  48449. });
  48450. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48451. get: function () {
  48452. return ActionManager._OnCenterPickTrigger;
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48458. get: function () {
  48459. return ActionManager._OnPickDownTrigger;
  48460. },
  48461. enumerable: true,
  48462. configurable: true
  48463. });
  48464. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48465. get: function () {
  48466. return ActionManager._OnDoublePickTrigger;
  48467. },
  48468. enumerable: true,
  48469. configurable: true
  48470. });
  48471. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48472. get: function () {
  48473. return ActionManager._OnPickUpTrigger;
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48479. /// This trigger will only be raised if you also declared a OnPickDown
  48480. get: function () {
  48481. return ActionManager._OnPickOutTrigger;
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48487. get: function () {
  48488. return ActionManager._OnLongPressTrigger;
  48489. },
  48490. enumerable: true,
  48491. configurable: true
  48492. });
  48493. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48494. get: function () {
  48495. return ActionManager._OnPointerOverTrigger;
  48496. },
  48497. enumerable: true,
  48498. configurable: true
  48499. });
  48500. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48501. get: function () {
  48502. return ActionManager._OnPointerOutTrigger;
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48508. get: function () {
  48509. return ActionManager._OnEveryFrameTrigger;
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48515. get: function () {
  48516. return ActionManager._OnIntersectionEnterTrigger;
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48522. get: function () {
  48523. return ActionManager._OnIntersectionExitTrigger;
  48524. },
  48525. enumerable: true,
  48526. configurable: true
  48527. });
  48528. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48529. get: function () {
  48530. return ActionManager._OnKeyDownTrigger;
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48536. get: function () {
  48537. return ActionManager._OnKeyUpTrigger;
  48538. },
  48539. enumerable: true,
  48540. configurable: true
  48541. });
  48542. // Methods
  48543. ActionManager.prototype.dispose = function () {
  48544. var index = this._scene._actionManagers.indexOf(this);
  48545. for (var i = 0; i < this.actions.length; i++) {
  48546. var action = this.actions[i];
  48547. ActionManager.Triggers[action.trigger]--;
  48548. if (ActionManager.Triggers[action.trigger] === 0) {
  48549. delete ActionManager.Triggers[action.trigger];
  48550. }
  48551. }
  48552. if (index > -1) {
  48553. this._scene._actionManagers.splice(index, 1);
  48554. }
  48555. };
  48556. ActionManager.prototype.getScene = function () {
  48557. return this._scene;
  48558. };
  48559. /**
  48560. * Does this action manager handles actions of any of the given triggers
  48561. * @param {number[]} triggers - the triggers to be tested
  48562. * @return {boolean} whether one (or more) of the triggers is handeled
  48563. */
  48564. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48565. for (var index = 0; index < this.actions.length; index++) {
  48566. var action = this.actions[index];
  48567. if (triggers.indexOf(action.trigger) > -1) {
  48568. return true;
  48569. }
  48570. }
  48571. return false;
  48572. };
  48573. /**
  48574. * Does this action manager handles actions of a given trigger
  48575. * @param {number} trigger - the trigger to be tested
  48576. * @return {boolean} whether the trigger is handeled
  48577. */
  48578. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48579. for (var index = 0; index < this.actions.length; index++) {
  48580. var action = this.actions[index];
  48581. if (action.trigger === trigger) {
  48582. return true;
  48583. }
  48584. }
  48585. return false;
  48586. };
  48587. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48588. /**
  48589. * Does this action manager has pointer triggers
  48590. * @return {boolean} whether or not it has pointer triggers
  48591. */
  48592. get: function () {
  48593. for (var index = 0; index < this.actions.length; index++) {
  48594. var action = this.actions[index];
  48595. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48596. return true;
  48597. }
  48598. }
  48599. return false;
  48600. },
  48601. enumerable: true,
  48602. configurable: true
  48603. });
  48604. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48605. /**
  48606. * Does this action manager has pick triggers
  48607. * @return {boolean} whether or not it has pick triggers
  48608. */
  48609. get: function () {
  48610. for (var index = 0; index < this.actions.length; index++) {
  48611. var action = this.actions[index];
  48612. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48613. return true;
  48614. }
  48615. }
  48616. return false;
  48617. },
  48618. enumerable: true,
  48619. configurable: true
  48620. });
  48621. Object.defineProperty(ActionManager, "HasTriggers", {
  48622. /**
  48623. * Does exist one action manager with at least one trigger
  48624. * @return {boolean} whether or not it exists one action manager with one trigger
  48625. **/
  48626. get: function () {
  48627. for (var t in ActionManager.Triggers) {
  48628. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48629. return true;
  48630. }
  48631. }
  48632. return false;
  48633. },
  48634. enumerable: true,
  48635. configurable: true
  48636. });
  48637. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48638. /**
  48639. * Does exist one action manager with at least one pick trigger
  48640. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48641. **/
  48642. get: function () {
  48643. for (var t in ActionManager.Triggers) {
  48644. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48645. var t_int = parseInt(t);
  48646. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48647. return true;
  48648. }
  48649. }
  48650. }
  48651. return false;
  48652. },
  48653. enumerable: true,
  48654. configurable: true
  48655. });
  48656. /**
  48657. * Does exist one action manager that handles actions of a given trigger
  48658. * @param {number} trigger - the trigger to be tested
  48659. * @return {boolean} whether the trigger is handeled by at least one action manager
  48660. **/
  48661. ActionManager.HasSpecificTrigger = function (trigger) {
  48662. for (var t in ActionManager.Triggers) {
  48663. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48664. var t_int = parseInt(t);
  48665. if (t_int === trigger) {
  48666. return true;
  48667. }
  48668. }
  48669. }
  48670. return false;
  48671. };
  48672. /**
  48673. * Registers an action to this action manager
  48674. * @param {BABYLON.Action} action - the action to be registered
  48675. * @return {BABYLON.Action} the action amended (prepared) after registration
  48676. */
  48677. ActionManager.prototype.registerAction = function (action) {
  48678. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48679. if (this.getScene().actionManager !== this) {
  48680. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48681. return null;
  48682. }
  48683. }
  48684. this.actions.push(action);
  48685. if (ActionManager.Triggers[action.trigger]) {
  48686. ActionManager.Triggers[action.trigger]++;
  48687. }
  48688. else {
  48689. ActionManager.Triggers[action.trigger] = 1;
  48690. }
  48691. action._actionManager = this;
  48692. action._prepare();
  48693. return action;
  48694. };
  48695. /**
  48696. * Unregisters an action to this action manager
  48697. * @param action The action to be unregistered
  48698. * @return whether the action has been unregistered
  48699. */
  48700. ActionManager.prototype.unregisterAction = function (action) {
  48701. var index = this.actions.indexOf(action);
  48702. if (index !== -1) {
  48703. this.actions.splice(index, 1);
  48704. ActionManager.Triggers[action.trigger] -= 1;
  48705. if (ActionManager.Triggers[action.trigger] === 0) {
  48706. delete ActionManager.Triggers[action.trigger];
  48707. }
  48708. delete action._actionManager;
  48709. return true;
  48710. }
  48711. return false;
  48712. };
  48713. /**
  48714. * Process a specific trigger
  48715. * @param {number} trigger - the trigger to process
  48716. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48717. */
  48718. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48719. for (var index = 0; index < this.actions.length; index++) {
  48720. var action = this.actions[index];
  48721. if (action.trigger === trigger) {
  48722. if (evt) {
  48723. if (trigger === ActionManager.OnKeyUpTrigger
  48724. || trigger === ActionManager.OnKeyDownTrigger) {
  48725. var parameter = action.getTriggerParameter();
  48726. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48727. if (!parameter.toLowerCase) {
  48728. continue;
  48729. }
  48730. var lowerCase = parameter.toLowerCase();
  48731. if (lowerCase !== evt.sourceEvent.key) {
  48732. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48733. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48734. if (actualkey !== lowerCase) {
  48735. continue;
  48736. }
  48737. }
  48738. }
  48739. }
  48740. }
  48741. action._executeCurrent(evt);
  48742. }
  48743. }
  48744. };
  48745. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48746. var properties = propertyPath.split(".");
  48747. for (var index = 0; index < properties.length - 1; index++) {
  48748. target = target[properties[index]];
  48749. }
  48750. return target;
  48751. };
  48752. ActionManager.prototype._getProperty = function (propertyPath) {
  48753. var properties = propertyPath.split(".");
  48754. return properties[properties.length - 1];
  48755. };
  48756. ActionManager.prototype.serialize = function (name) {
  48757. var root = {
  48758. children: new Array(),
  48759. name: name,
  48760. type: 3,
  48761. properties: new Array() // Empty for root but required
  48762. };
  48763. for (var i = 0; i < this.actions.length; i++) {
  48764. var triggerObject = {
  48765. type: 0,
  48766. children: new Array(),
  48767. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48768. properties: new Array()
  48769. };
  48770. var triggerOptions = this.actions[i].triggerOptions;
  48771. if (triggerOptions && typeof triggerOptions !== "number") {
  48772. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48773. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48774. }
  48775. else {
  48776. var parameter = {};
  48777. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48778. if (triggerOptions.parameter.mesh) {
  48779. parameter._meshId = triggerOptions.parameter.mesh.id;
  48780. }
  48781. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48782. }
  48783. }
  48784. // Serialize child action, recursively
  48785. this.actions[i].serialize(triggerObject);
  48786. // Add serialized trigger
  48787. root.children.push(triggerObject);
  48788. }
  48789. return root;
  48790. };
  48791. ActionManager.Parse = function (parsedActions, object, scene) {
  48792. var actionManager = new ActionManager(scene);
  48793. if (object === null)
  48794. scene.actionManager = actionManager;
  48795. else
  48796. object.actionManager = actionManager;
  48797. // instanciate a new object
  48798. var instanciate = function (name, params) {
  48799. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48800. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48801. newInstance.constructor.apply(newInstance, params);
  48802. return newInstance;
  48803. };
  48804. var parseParameter = function (name, value, target, propertyPath) {
  48805. if (propertyPath === null) {
  48806. // String, boolean or float
  48807. var floatValue = parseFloat(value);
  48808. if (value === "true" || value === "false")
  48809. return value === "true";
  48810. else
  48811. return isNaN(floatValue) ? value : floatValue;
  48812. }
  48813. var effectiveTarget = propertyPath.split(".");
  48814. var values = value.split(",");
  48815. // Get effective Target
  48816. for (var i = 0; i < effectiveTarget.length; i++) {
  48817. target = target[effectiveTarget[i]];
  48818. }
  48819. // Return appropriate value with its type
  48820. if (typeof (target) === "boolean")
  48821. return values[0] === "true";
  48822. if (typeof (target) === "string")
  48823. return values[0];
  48824. // Parameters with multiple values such as Vector3 etc.
  48825. var split = new Array();
  48826. for (var i = 0; i < values.length; i++)
  48827. split.push(parseFloat(values[i]));
  48828. if (target instanceof BABYLON.Vector3)
  48829. return BABYLON.Vector3.FromArray(split);
  48830. if (target instanceof BABYLON.Vector4)
  48831. return BABYLON.Vector4.FromArray(split);
  48832. if (target instanceof BABYLON.Color3)
  48833. return BABYLON.Color3.FromArray(split);
  48834. if (target instanceof BABYLON.Color4)
  48835. return BABYLON.Color4.FromArray(split);
  48836. return parseFloat(values[0]);
  48837. };
  48838. // traverse graph per trigger
  48839. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48840. if (combineArray === void 0) { combineArray = null; }
  48841. if (parsedAction.detached)
  48842. return;
  48843. var parameters = new Array();
  48844. var target = null;
  48845. var propertyPath = null;
  48846. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48847. // Parameters
  48848. if (parsedAction.type === 2)
  48849. parameters.push(actionManager);
  48850. else
  48851. parameters.push(trigger);
  48852. if (combine) {
  48853. var actions = new Array();
  48854. for (var j = 0; j < parsedAction.combine.length; j++) {
  48855. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48856. }
  48857. parameters.push(actions);
  48858. }
  48859. else {
  48860. for (var i = 0; i < parsedAction.properties.length; i++) {
  48861. var value = parsedAction.properties[i].value;
  48862. var name = parsedAction.properties[i].name;
  48863. var targetType = parsedAction.properties[i].targetType;
  48864. if (name === "target")
  48865. if (targetType !== null && targetType === "SceneProperties")
  48866. value = target = scene;
  48867. else
  48868. value = target = scene.getNodeByName(value);
  48869. else if (name === "parent")
  48870. value = scene.getNodeByName(value);
  48871. else if (name === "sound")
  48872. value = scene.getSoundByName(value);
  48873. else if (name !== "propertyPath") {
  48874. if (parsedAction.type === 2 && name === "operator")
  48875. value = BABYLON.ValueCondition[value];
  48876. else
  48877. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48878. }
  48879. else {
  48880. propertyPath = value;
  48881. }
  48882. parameters.push(value);
  48883. }
  48884. }
  48885. if (combineArray === null) {
  48886. parameters.push(condition);
  48887. }
  48888. else {
  48889. parameters.push(null);
  48890. }
  48891. // If interpolate value action
  48892. if (parsedAction.name === "InterpolateValueAction") {
  48893. var param = parameters[parameters.length - 2];
  48894. parameters[parameters.length - 1] = param;
  48895. parameters[parameters.length - 2] = condition;
  48896. }
  48897. // Action or condition(s) and not CombineAction
  48898. var newAction = instanciate(parsedAction.name, parameters);
  48899. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48900. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48901. if (action)
  48902. action.then(nothing);
  48903. else
  48904. actionManager.registerAction(nothing);
  48905. action = nothing;
  48906. }
  48907. if (combineArray === null) {
  48908. if (newAction instanceof BABYLON.Condition) {
  48909. condition = newAction;
  48910. newAction = action;
  48911. }
  48912. else {
  48913. condition = null;
  48914. if (action)
  48915. action.then(newAction);
  48916. else
  48917. actionManager.registerAction(newAction);
  48918. }
  48919. }
  48920. else {
  48921. combineArray.push(newAction);
  48922. }
  48923. for (var i = 0; i < parsedAction.children.length; i++)
  48924. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48925. };
  48926. // triggers
  48927. for (var i = 0; i < parsedActions.children.length; i++) {
  48928. var triggerParams;
  48929. var trigger = parsedActions.children[i];
  48930. if (trigger.properties.length > 0) {
  48931. var param = trigger.properties[0].value;
  48932. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48933. if (value._meshId) {
  48934. value.mesh = scene.getMeshByID(value._meshId);
  48935. }
  48936. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48937. }
  48938. else
  48939. triggerParams = ActionManager[trigger.name];
  48940. for (var j = 0; j < trigger.children.length; j++) {
  48941. if (!trigger.detached)
  48942. traverse(trigger.children[j], triggerParams, null, null);
  48943. }
  48944. }
  48945. };
  48946. ActionManager.GetTriggerName = function (trigger) {
  48947. switch (trigger) {
  48948. case 0: return "NothingTrigger";
  48949. case 1: return "OnPickTrigger";
  48950. case 2: return "OnLeftPickTrigger";
  48951. case 3: return "OnRightPickTrigger";
  48952. case 4: return "OnCenterPickTrigger";
  48953. case 5: return "OnPickDownTrigger";
  48954. case 6: return "OnPickUpTrigger";
  48955. case 7: return "OnLongPressTrigger";
  48956. case 8: return "OnPointerOverTrigger";
  48957. case 9: return "OnPointerOutTrigger";
  48958. case 10: return "OnEveryFrameTrigger";
  48959. case 11: return "OnIntersectionEnterTrigger";
  48960. case 12: return "OnIntersectionExitTrigger";
  48961. case 13: return "OnKeyDownTrigger";
  48962. case 14: return "OnKeyUpTrigger";
  48963. case 15: return "OnPickOutTrigger";
  48964. default: return "";
  48965. }
  48966. };
  48967. // Statics
  48968. ActionManager._NothingTrigger = 0;
  48969. ActionManager._OnPickTrigger = 1;
  48970. ActionManager._OnLeftPickTrigger = 2;
  48971. ActionManager._OnRightPickTrigger = 3;
  48972. ActionManager._OnCenterPickTrigger = 4;
  48973. ActionManager._OnPickDownTrigger = 5;
  48974. ActionManager._OnDoublePickTrigger = 6;
  48975. ActionManager._OnPickUpTrigger = 7;
  48976. ActionManager._OnLongPressTrigger = 8;
  48977. ActionManager._OnPointerOverTrigger = 9;
  48978. ActionManager._OnPointerOutTrigger = 10;
  48979. ActionManager._OnEveryFrameTrigger = 11;
  48980. ActionManager._OnIntersectionEnterTrigger = 12;
  48981. ActionManager._OnIntersectionExitTrigger = 13;
  48982. ActionManager._OnKeyDownTrigger = 14;
  48983. ActionManager._OnKeyUpTrigger = 15;
  48984. ActionManager._OnPickOutTrigger = 16;
  48985. ActionManager.Triggers = {};
  48986. return ActionManager;
  48987. }());
  48988. BABYLON.ActionManager = ActionManager;
  48989. })(BABYLON || (BABYLON = {}));
  48990. //# sourceMappingURL=babylon.actionManager.js.map
  48991. var BABYLON;
  48992. (function (BABYLON) {
  48993. var InterpolateValueAction = /** @class */ (function (_super) {
  48994. __extends(InterpolateValueAction, _super);
  48995. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48996. if (duration === void 0) { duration = 1000; }
  48997. var _this = _super.call(this, triggerOptions, condition) || this;
  48998. _this.propertyPath = propertyPath;
  48999. _this.value = value;
  49000. _this.duration = duration;
  49001. _this.stopOtherAnimations = stopOtherAnimations;
  49002. _this.onInterpolationDone = onInterpolationDone;
  49003. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49004. _this._target = _this._effectiveTarget = target;
  49005. return _this;
  49006. }
  49007. InterpolateValueAction.prototype._prepare = function () {
  49008. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49009. this._property = this._getProperty(this.propertyPath);
  49010. };
  49011. InterpolateValueAction.prototype.execute = function () {
  49012. var _this = this;
  49013. var scene = this._actionManager.getScene();
  49014. var keys = [
  49015. {
  49016. frame: 0,
  49017. value: this._effectiveTarget[this._property]
  49018. }, {
  49019. frame: 100,
  49020. value: this.value
  49021. }
  49022. ];
  49023. var dataType;
  49024. if (typeof this.value === "number") {
  49025. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49026. }
  49027. else if (this.value instanceof BABYLON.Color3) {
  49028. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49029. }
  49030. else if (this.value instanceof BABYLON.Vector3) {
  49031. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49032. }
  49033. else if (this.value instanceof BABYLON.Matrix) {
  49034. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49035. }
  49036. else if (this.value instanceof BABYLON.Quaternion) {
  49037. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49038. }
  49039. else {
  49040. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49041. return;
  49042. }
  49043. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49044. animation.setKeys(keys);
  49045. if (this.stopOtherAnimations) {
  49046. scene.stopAnimation(this._effectiveTarget);
  49047. }
  49048. var wrapper = function () {
  49049. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49050. if (_this.onInterpolationDone) {
  49051. _this.onInterpolationDone();
  49052. }
  49053. };
  49054. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49055. };
  49056. InterpolateValueAction.prototype.serialize = function (parent) {
  49057. return _super.prototype._serialize.call(this, {
  49058. name: "InterpolateValueAction",
  49059. properties: [
  49060. BABYLON.Action._GetTargetProperty(this._target),
  49061. { name: "propertyPath", value: this.propertyPath },
  49062. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49063. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49064. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49065. ]
  49066. }, parent);
  49067. };
  49068. return InterpolateValueAction;
  49069. }(BABYLON.Action));
  49070. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49071. })(BABYLON || (BABYLON = {}));
  49072. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49073. var BABYLON;
  49074. (function (BABYLON) {
  49075. var SwitchBooleanAction = /** @class */ (function (_super) {
  49076. __extends(SwitchBooleanAction, _super);
  49077. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49078. var _this = _super.call(this, triggerOptions, condition) || this;
  49079. _this.propertyPath = propertyPath;
  49080. _this._target = _this._effectiveTarget = target;
  49081. return _this;
  49082. }
  49083. SwitchBooleanAction.prototype._prepare = function () {
  49084. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49085. this._property = this._getProperty(this.propertyPath);
  49086. };
  49087. SwitchBooleanAction.prototype.execute = function () {
  49088. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49089. };
  49090. SwitchBooleanAction.prototype.serialize = function (parent) {
  49091. return _super.prototype._serialize.call(this, {
  49092. name: "SwitchBooleanAction",
  49093. properties: [
  49094. BABYLON.Action._GetTargetProperty(this._target),
  49095. { name: "propertyPath", value: this.propertyPath }
  49096. ]
  49097. }, parent);
  49098. };
  49099. return SwitchBooleanAction;
  49100. }(BABYLON.Action));
  49101. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49102. var SetStateAction = /** @class */ (function (_super) {
  49103. __extends(SetStateAction, _super);
  49104. function SetStateAction(triggerOptions, target, value, condition) {
  49105. var _this = _super.call(this, triggerOptions, condition) || this;
  49106. _this.value = value;
  49107. _this._target = target;
  49108. return _this;
  49109. }
  49110. SetStateAction.prototype.execute = function () {
  49111. this._target.state = this.value;
  49112. };
  49113. SetStateAction.prototype.serialize = function (parent) {
  49114. return _super.prototype._serialize.call(this, {
  49115. name: "SetStateAction",
  49116. properties: [
  49117. BABYLON.Action._GetTargetProperty(this._target),
  49118. { name: "value", value: this.value }
  49119. ]
  49120. }, parent);
  49121. };
  49122. return SetStateAction;
  49123. }(BABYLON.Action));
  49124. BABYLON.SetStateAction = SetStateAction;
  49125. var SetValueAction = /** @class */ (function (_super) {
  49126. __extends(SetValueAction, _super);
  49127. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49128. var _this = _super.call(this, triggerOptions, condition) || this;
  49129. _this.propertyPath = propertyPath;
  49130. _this.value = value;
  49131. _this._target = _this._effectiveTarget = target;
  49132. return _this;
  49133. }
  49134. SetValueAction.prototype._prepare = function () {
  49135. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49136. this._property = this._getProperty(this.propertyPath);
  49137. };
  49138. SetValueAction.prototype.execute = function () {
  49139. this._effectiveTarget[this._property] = this.value;
  49140. if (this._target.markAsDirty) {
  49141. this._target.markAsDirty(this._property);
  49142. }
  49143. };
  49144. SetValueAction.prototype.serialize = function (parent) {
  49145. return _super.prototype._serialize.call(this, {
  49146. name: "SetValueAction",
  49147. properties: [
  49148. BABYLON.Action._GetTargetProperty(this._target),
  49149. { name: "propertyPath", value: this.propertyPath },
  49150. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49151. ]
  49152. }, parent);
  49153. };
  49154. return SetValueAction;
  49155. }(BABYLON.Action));
  49156. BABYLON.SetValueAction = SetValueAction;
  49157. var IncrementValueAction = /** @class */ (function (_super) {
  49158. __extends(IncrementValueAction, _super);
  49159. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49160. var _this = _super.call(this, triggerOptions, condition) || this;
  49161. _this.propertyPath = propertyPath;
  49162. _this.value = value;
  49163. _this._target = _this._effectiveTarget = target;
  49164. return _this;
  49165. }
  49166. IncrementValueAction.prototype._prepare = function () {
  49167. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49168. this._property = this._getProperty(this.propertyPath);
  49169. if (typeof this._effectiveTarget[this._property] !== "number") {
  49170. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49171. }
  49172. };
  49173. IncrementValueAction.prototype.execute = function () {
  49174. this._effectiveTarget[this._property] += this.value;
  49175. if (this._target.markAsDirty) {
  49176. this._target.markAsDirty(this._property);
  49177. }
  49178. };
  49179. IncrementValueAction.prototype.serialize = function (parent) {
  49180. return _super.prototype._serialize.call(this, {
  49181. name: "IncrementValueAction",
  49182. properties: [
  49183. BABYLON.Action._GetTargetProperty(this._target),
  49184. { name: "propertyPath", value: this.propertyPath },
  49185. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49186. ]
  49187. }, parent);
  49188. };
  49189. return IncrementValueAction;
  49190. }(BABYLON.Action));
  49191. BABYLON.IncrementValueAction = IncrementValueAction;
  49192. var PlayAnimationAction = /** @class */ (function (_super) {
  49193. __extends(PlayAnimationAction, _super);
  49194. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49195. var _this = _super.call(this, triggerOptions, condition) || this;
  49196. _this.from = from;
  49197. _this.to = to;
  49198. _this.loop = loop;
  49199. _this._target = target;
  49200. return _this;
  49201. }
  49202. PlayAnimationAction.prototype._prepare = function () {
  49203. };
  49204. PlayAnimationAction.prototype.execute = function () {
  49205. var scene = this._actionManager.getScene();
  49206. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49207. };
  49208. PlayAnimationAction.prototype.serialize = function (parent) {
  49209. return _super.prototype._serialize.call(this, {
  49210. name: "PlayAnimationAction",
  49211. properties: [
  49212. BABYLON.Action._GetTargetProperty(this._target),
  49213. { name: "from", value: String(this.from) },
  49214. { name: "to", value: String(this.to) },
  49215. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49216. ]
  49217. }, parent);
  49218. };
  49219. return PlayAnimationAction;
  49220. }(BABYLON.Action));
  49221. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49222. var StopAnimationAction = /** @class */ (function (_super) {
  49223. __extends(StopAnimationAction, _super);
  49224. function StopAnimationAction(triggerOptions, target, condition) {
  49225. var _this = _super.call(this, triggerOptions, condition) || this;
  49226. _this._target = target;
  49227. return _this;
  49228. }
  49229. StopAnimationAction.prototype._prepare = function () {
  49230. };
  49231. StopAnimationAction.prototype.execute = function () {
  49232. var scene = this._actionManager.getScene();
  49233. scene.stopAnimation(this._target);
  49234. };
  49235. StopAnimationAction.prototype.serialize = function (parent) {
  49236. return _super.prototype._serialize.call(this, {
  49237. name: "StopAnimationAction",
  49238. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49239. }, parent);
  49240. };
  49241. return StopAnimationAction;
  49242. }(BABYLON.Action));
  49243. BABYLON.StopAnimationAction = StopAnimationAction;
  49244. var DoNothingAction = /** @class */ (function (_super) {
  49245. __extends(DoNothingAction, _super);
  49246. function DoNothingAction(triggerOptions, condition) {
  49247. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49248. return _super.call(this, triggerOptions, condition) || this;
  49249. }
  49250. DoNothingAction.prototype.execute = function () {
  49251. };
  49252. DoNothingAction.prototype.serialize = function (parent) {
  49253. return _super.prototype._serialize.call(this, {
  49254. name: "DoNothingAction",
  49255. properties: []
  49256. }, parent);
  49257. };
  49258. return DoNothingAction;
  49259. }(BABYLON.Action));
  49260. BABYLON.DoNothingAction = DoNothingAction;
  49261. var CombineAction = /** @class */ (function (_super) {
  49262. __extends(CombineAction, _super);
  49263. function CombineAction(triggerOptions, children, condition) {
  49264. var _this = _super.call(this, triggerOptions, condition) || this;
  49265. _this.children = children;
  49266. return _this;
  49267. }
  49268. CombineAction.prototype._prepare = function () {
  49269. for (var index = 0; index < this.children.length; index++) {
  49270. this.children[index]._actionManager = this._actionManager;
  49271. this.children[index]._prepare();
  49272. }
  49273. };
  49274. CombineAction.prototype.execute = function (evt) {
  49275. for (var index = 0; index < this.children.length; index++) {
  49276. this.children[index].execute(evt);
  49277. }
  49278. };
  49279. CombineAction.prototype.serialize = function (parent) {
  49280. var serializationObject = _super.prototype._serialize.call(this, {
  49281. name: "CombineAction",
  49282. properties: [],
  49283. combine: []
  49284. }, parent);
  49285. for (var i = 0; i < this.children.length; i++) {
  49286. serializationObject.combine.push(this.children[i].serialize(null));
  49287. }
  49288. return serializationObject;
  49289. };
  49290. return CombineAction;
  49291. }(BABYLON.Action));
  49292. BABYLON.CombineAction = CombineAction;
  49293. var ExecuteCodeAction = /** @class */ (function (_super) {
  49294. __extends(ExecuteCodeAction, _super);
  49295. function ExecuteCodeAction(triggerOptions, func, condition) {
  49296. var _this = _super.call(this, triggerOptions, condition) || this;
  49297. _this.func = func;
  49298. return _this;
  49299. }
  49300. ExecuteCodeAction.prototype.execute = function (evt) {
  49301. this.func(evt);
  49302. };
  49303. return ExecuteCodeAction;
  49304. }(BABYLON.Action));
  49305. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49306. var SetParentAction = /** @class */ (function (_super) {
  49307. __extends(SetParentAction, _super);
  49308. function SetParentAction(triggerOptions, target, parent, condition) {
  49309. var _this = _super.call(this, triggerOptions, condition) || this;
  49310. _this._target = target;
  49311. _this._parent = parent;
  49312. return _this;
  49313. }
  49314. SetParentAction.prototype._prepare = function () {
  49315. };
  49316. SetParentAction.prototype.execute = function () {
  49317. if (this._target.parent === this._parent) {
  49318. return;
  49319. }
  49320. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49321. invertParentWorldMatrix.invert();
  49322. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49323. this._target.parent = this._parent;
  49324. };
  49325. SetParentAction.prototype.serialize = function (parent) {
  49326. return _super.prototype._serialize.call(this, {
  49327. name: "SetParentAction",
  49328. properties: [
  49329. BABYLON.Action._GetTargetProperty(this._target),
  49330. BABYLON.Action._GetTargetProperty(this._parent),
  49331. ]
  49332. }, parent);
  49333. };
  49334. return SetParentAction;
  49335. }(BABYLON.Action));
  49336. BABYLON.SetParentAction = SetParentAction;
  49337. var PlaySoundAction = /** @class */ (function (_super) {
  49338. __extends(PlaySoundAction, _super);
  49339. function PlaySoundAction(triggerOptions, sound, condition) {
  49340. var _this = _super.call(this, triggerOptions, condition) || this;
  49341. _this._sound = sound;
  49342. return _this;
  49343. }
  49344. PlaySoundAction.prototype._prepare = function () {
  49345. };
  49346. PlaySoundAction.prototype.execute = function () {
  49347. if (this._sound !== undefined)
  49348. this._sound.play();
  49349. };
  49350. PlaySoundAction.prototype.serialize = function (parent) {
  49351. return _super.prototype._serialize.call(this, {
  49352. name: "PlaySoundAction",
  49353. properties: [{ name: "sound", value: this._sound.name }]
  49354. }, parent);
  49355. };
  49356. return PlaySoundAction;
  49357. }(BABYLON.Action));
  49358. BABYLON.PlaySoundAction = PlaySoundAction;
  49359. var StopSoundAction = /** @class */ (function (_super) {
  49360. __extends(StopSoundAction, _super);
  49361. function StopSoundAction(triggerOptions, sound, condition) {
  49362. var _this = _super.call(this, triggerOptions, condition) || this;
  49363. _this._sound = sound;
  49364. return _this;
  49365. }
  49366. StopSoundAction.prototype._prepare = function () {
  49367. };
  49368. StopSoundAction.prototype.execute = function () {
  49369. if (this._sound !== undefined)
  49370. this._sound.stop();
  49371. };
  49372. StopSoundAction.prototype.serialize = function (parent) {
  49373. return _super.prototype._serialize.call(this, {
  49374. name: "StopSoundAction",
  49375. properties: [{ name: "sound", value: this._sound.name }]
  49376. }, parent);
  49377. };
  49378. return StopSoundAction;
  49379. }(BABYLON.Action));
  49380. BABYLON.StopSoundAction = StopSoundAction;
  49381. })(BABYLON || (BABYLON = {}));
  49382. //# sourceMappingURL=babylon.directActions.js.map
  49383. var BABYLON;
  49384. (function (BABYLON) {
  49385. var SpriteManager = /** @class */ (function () {
  49386. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49387. if (epsilon === void 0) { epsilon = 0.01; }
  49388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49389. this.name = name;
  49390. this.sprites = new Array();
  49391. this.renderingGroupId = 0;
  49392. this.layerMask = 0x0FFFFFFF;
  49393. this.fogEnabled = true;
  49394. this.isPickable = false;
  49395. /**
  49396. * An event triggered when the manager is disposed.
  49397. * @type {BABYLON.Observable}
  49398. */
  49399. this.onDisposeObservable = new BABYLON.Observable();
  49400. this._vertexBuffers = {};
  49401. this._capacity = capacity;
  49402. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49403. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49404. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49405. if (cellSize.width && cellSize.height) {
  49406. this.cellWidth = cellSize.width;
  49407. this.cellHeight = cellSize.height;
  49408. }
  49409. else if (cellSize !== undefined) {
  49410. this.cellWidth = cellSize;
  49411. this.cellHeight = cellSize;
  49412. }
  49413. else {
  49414. return;
  49415. }
  49416. this._epsilon = epsilon;
  49417. this._scene = scene;
  49418. this._scene.spriteManagers.push(this);
  49419. var indices = [];
  49420. var index = 0;
  49421. for (var count = 0; count < capacity; count++) {
  49422. indices.push(index);
  49423. indices.push(index + 1);
  49424. indices.push(index + 2);
  49425. indices.push(index);
  49426. indices.push(index + 2);
  49427. indices.push(index + 3);
  49428. index += 4;
  49429. }
  49430. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49431. // VBO
  49432. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49433. this._vertexData = new Float32Array(capacity * 16 * 4);
  49434. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49435. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49436. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49437. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49438. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49439. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49440. this._vertexBuffers["options"] = options;
  49441. this._vertexBuffers["cellInfo"] = cellInfo;
  49442. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49443. // Effects
  49444. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49445. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49446. }
  49447. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49448. set: function (callback) {
  49449. if (this._onDisposeObserver) {
  49450. this.onDisposeObservable.remove(this._onDisposeObserver);
  49451. }
  49452. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49453. },
  49454. enumerable: true,
  49455. configurable: true
  49456. });
  49457. Object.defineProperty(SpriteManager.prototype, "texture", {
  49458. get: function () {
  49459. return this._spriteTexture;
  49460. },
  49461. set: function (value) {
  49462. this._spriteTexture = value;
  49463. },
  49464. enumerable: true,
  49465. configurable: true
  49466. });
  49467. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49468. var arrayOffset = index * 16;
  49469. if (offsetX === 0)
  49470. offsetX = this._epsilon;
  49471. else if (offsetX === 1)
  49472. offsetX = 1 - this._epsilon;
  49473. if (offsetY === 0)
  49474. offsetY = this._epsilon;
  49475. else if (offsetY === 1)
  49476. offsetY = 1 - this._epsilon;
  49477. this._vertexData[arrayOffset] = sprite.position.x;
  49478. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49479. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49480. this._vertexData[arrayOffset + 3] = sprite.angle;
  49481. this._vertexData[arrayOffset + 4] = sprite.width;
  49482. this._vertexData[arrayOffset + 5] = sprite.height;
  49483. this._vertexData[arrayOffset + 6] = offsetX;
  49484. this._vertexData[arrayOffset + 7] = offsetY;
  49485. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49486. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49487. var offset = (sprite.cellIndex / rowSize) >> 0;
  49488. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49489. this._vertexData[arrayOffset + 11] = offset;
  49490. // Color
  49491. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49492. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49493. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49494. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49495. };
  49496. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49497. var count = Math.min(this._capacity, this.sprites.length);
  49498. var min = BABYLON.Vector3.Zero();
  49499. var max = BABYLON.Vector3.Zero();
  49500. var distance = Number.MAX_VALUE;
  49501. var currentSprite = null;
  49502. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49503. var cameraView = camera.getViewMatrix();
  49504. for (var index = 0; index < count; index++) {
  49505. var sprite = this.sprites[index];
  49506. if (!sprite) {
  49507. continue;
  49508. }
  49509. if (predicate) {
  49510. if (!predicate(sprite)) {
  49511. continue;
  49512. }
  49513. }
  49514. else if (!sprite.isPickable) {
  49515. continue;
  49516. }
  49517. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49518. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49519. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49520. if (ray.intersectsBoxMinMax(min, max)) {
  49521. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49522. if (distance > currentDistance) {
  49523. distance = currentDistance;
  49524. currentSprite = sprite;
  49525. if (fastCheck) {
  49526. break;
  49527. }
  49528. }
  49529. }
  49530. }
  49531. if (currentSprite) {
  49532. var result = new BABYLON.PickingInfo();
  49533. result.hit = true;
  49534. result.pickedSprite = currentSprite;
  49535. result.distance = distance;
  49536. return result;
  49537. }
  49538. return null;
  49539. };
  49540. SpriteManager.prototype.render = function () {
  49541. // Check
  49542. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49543. return;
  49544. var engine = this._scene.getEngine();
  49545. var baseSize = this._spriteTexture.getBaseSize();
  49546. // Sprites
  49547. var deltaTime = engine.getDeltaTime();
  49548. var max = Math.min(this._capacity, this.sprites.length);
  49549. var rowSize = baseSize.width / this.cellWidth;
  49550. var offset = 0;
  49551. for (var index = 0; index < max; index++) {
  49552. var sprite = this.sprites[index];
  49553. if (!sprite) {
  49554. continue;
  49555. }
  49556. sprite._animate(deltaTime);
  49557. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49558. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49559. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49560. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49561. }
  49562. this._buffer.update(this._vertexData);
  49563. // Render
  49564. var effect = this._effectBase;
  49565. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49566. effect = this._effectFog;
  49567. }
  49568. engine.enableEffect(effect);
  49569. var viewMatrix = this._scene.getViewMatrix();
  49570. effect.setTexture("diffuseSampler", this._spriteTexture);
  49571. effect.setMatrix("view", viewMatrix);
  49572. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49573. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49574. // Fog
  49575. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49576. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49577. effect.setColor3("vFogColor", this._scene.fogColor);
  49578. }
  49579. // VBOs
  49580. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49581. // Draw order
  49582. engine.setDepthFunctionToLessOrEqual();
  49583. effect.setBool("alphaTest", true);
  49584. engine.setColorWrite(false);
  49585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49586. engine.setColorWrite(true);
  49587. effect.setBool("alphaTest", false);
  49588. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49589. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49591. };
  49592. SpriteManager.prototype.dispose = function () {
  49593. if (this._buffer) {
  49594. this._buffer.dispose();
  49595. this._buffer = null;
  49596. }
  49597. if (this._indexBuffer) {
  49598. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49599. this._indexBuffer = null;
  49600. }
  49601. if (this._spriteTexture) {
  49602. this._spriteTexture.dispose();
  49603. this._spriteTexture = null;
  49604. }
  49605. // Remove from scene
  49606. var index = this._scene.spriteManagers.indexOf(this);
  49607. this._scene.spriteManagers.splice(index, 1);
  49608. // Callback
  49609. this.onDisposeObservable.notifyObservers(this);
  49610. this.onDisposeObservable.clear();
  49611. };
  49612. return SpriteManager;
  49613. }());
  49614. BABYLON.SpriteManager = SpriteManager;
  49615. })(BABYLON || (BABYLON = {}));
  49616. //# sourceMappingURL=babylon.spriteManager.js.map
  49617. var BABYLON;
  49618. (function (BABYLON) {
  49619. var Sprite = /** @class */ (function () {
  49620. function Sprite(name, manager) {
  49621. this.name = name;
  49622. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49623. this.width = 1.0;
  49624. this.height = 1.0;
  49625. this.angle = 0;
  49626. this.cellIndex = 0;
  49627. this.invertU = 0;
  49628. this.invertV = 0;
  49629. this.animations = new Array();
  49630. this.isPickable = false;
  49631. this._animationStarted = false;
  49632. this._loopAnimation = false;
  49633. this._fromIndex = 0;
  49634. this._toIndex = 0;
  49635. this._delay = 0;
  49636. this._direction = 1;
  49637. this._time = 0;
  49638. this._manager = manager;
  49639. this._manager.sprites.push(this);
  49640. this.position = BABYLON.Vector3.Zero();
  49641. }
  49642. Object.defineProperty(Sprite.prototype, "size", {
  49643. get: function () {
  49644. return this.width;
  49645. },
  49646. set: function (value) {
  49647. this.width = value;
  49648. this.height = value;
  49649. },
  49650. enumerable: true,
  49651. configurable: true
  49652. });
  49653. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49654. this._fromIndex = from;
  49655. this._toIndex = to;
  49656. this._loopAnimation = loop;
  49657. this._delay = delay;
  49658. this._animationStarted = true;
  49659. this._direction = from < to ? 1 : -1;
  49660. this.cellIndex = from;
  49661. this._time = 0;
  49662. this._onAnimationEnd = onAnimationEnd;
  49663. };
  49664. Sprite.prototype.stopAnimation = function () {
  49665. this._animationStarted = false;
  49666. };
  49667. Sprite.prototype._animate = function (deltaTime) {
  49668. if (!this._animationStarted)
  49669. return;
  49670. this._time += deltaTime;
  49671. if (this._time > this._delay) {
  49672. this._time = this._time % this._delay;
  49673. this.cellIndex += this._direction;
  49674. if (this.cellIndex > this._toIndex) {
  49675. if (this._loopAnimation) {
  49676. this.cellIndex = this._fromIndex;
  49677. }
  49678. else {
  49679. this.cellIndex = this._toIndex;
  49680. this._animationStarted = false;
  49681. if (this._onAnimationEnd) {
  49682. this._onAnimationEnd();
  49683. }
  49684. if (this.disposeWhenFinishedAnimating) {
  49685. this.dispose();
  49686. }
  49687. }
  49688. }
  49689. }
  49690. };
  49691. Sprite.prototype.dispose = function () {
  49692. for (var i = 0; i < this._manager.sprites.length; i++) {
  49693. if (this._manager.sprites[i] == this) {
  49694. this._manager.sprites.splice(i, 1);
  49695. }
  49696. }
  49697. };
  49698. return Sprite;
  49699. }());
  49700. BABYLON.Sprite = Sprite;
  49701. })(BABYLON || (BABYLON = {}));
  49702. //# sourceMappingURL=babylon.sprite.js.map
  49703. var BABYLON;
  49704. (function (BABYLON) {
  49705. var IntersectionInfo = /** @class */ (function () {
  49706. function IntersectionInfo(bu, bv, distance) {
  49707. this.bu = bu;
  49708. this.bv = bv;
  49709. this.distance = distance;
  49710. this.faceId = 0;
  49711. this.subMeshId = 0;
  49712. }
  49713. return IntersectionInfo;
  49714. }());
  49715. BABYLON.IntersectionInfo = IntersectionInfo;
  49716. var PickingInfo = /** @class */ (function () {
  49717. function PickingInfo() {
  49718. this.hit = false;
  49719. this.distance = 0;
  49720. this.pickedPoint = null;
  49721. this.pickedMesh = null;
  49722. this.bu = 0;
  49723. this.bv = 0;
  49724. this.faceId = -1;
  49725. this.subMeshId = 0;
  49726. this.pickedSprite = null;
  49727. }
  49728. // Methods
  49729. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49730. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49731. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49732. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49733. return null;
  49734. }
  49735. var indices = this.pickedMesh.getIndices();
  49736. if (!indices) {
  49737. return null;
  49738. }
  49739. var result;
  49740. if (useVerticesNormals) {
  49741. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49742. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49743. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49744. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49745. normal0 = normal0.scale(this.bu);
  49746. normal1 = normal1.scale(this.bv);
  49747. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49748. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49749. }
  49750. else {
  49751. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49752. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49753. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49754. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49755. var p1p2 = vertex1.subtract(vertex2);
  49756. var p3p2 = vertex3.subtract(vertex2);
  49757. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49758. }
  49759. if (useWorldCoordinates) {
  49760. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49761. }
  49762. return BABYLON.Vector3.Normalize(result);
  49763. };
  49764. PickingInfo.prototype.getTextureCoordinates = function () {
  49765. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49766. return null;
  49767. }
  49768. var indices = this.pickedMesh.getIndices();
  49769. if (!indices) {
  49770. return null;
  49771. }
  49772. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49773. if (!uvs) {
  49774. return null;
  49775. }
  49776. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49777. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49778. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49779. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49780. uv1 = uv1.scale(this.bu);
  49781. uv2 = uv2.scale(this.bv);
  49782. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49783. };
  49784. return PickingInfo;
  49785. }());
  49786. BABYLON.PickingInfo = PickingInfo;
  49787. })(BABYLON || (BABYLON = {}));
  49788. //# sourceMappingURL=babylon.pickingInfo.js.map
  49789. var BABYLON;
  49790. (function (BABYLON) {
  49791. var Ray = /** @class */ (function () {
  49792. function Ray(origin, direction, length) {
  49793. if (length === void 0) { length = Number.MAX_VALUE; }
  49794. this.origin = origin;
  49795. this.direction = direction;
  49796. this.length = length;
  49797. }
  49798. // Methods
  49799. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49800. var d = 0.0;
  49801. var maxValue = Number.MAX_VALUE;
  49802. var inv;
  49803. var min;
  49804. var max;
  49805. var temp;
  49806. if (Math.abs(this.direction.x) < 0.0000001) {
  49807. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49808. return false;
  49809. }
  49810. }
  49811. else {
  49812. inv = 1.0 / this.direction.x;
  49813. min = (minimum.x - this.origin.x) * inv;
  49814. max = (maximum.x - this.origin.x) * inv;
  49815. if (max === -Infinity) {
  49816. max = Infinity;
  49817. }
  49818. if (min > max) {
  49819. temp = min;
  49820. min = max;
  49821. max = temp;
  49822. }
  49823. d = Math.max(min, d);
  49824. maxValue = Math.min(max, maxValue);
  49825. if (d > maxValue) {
  49826. return false;
  49827. }
  49828. }
  49829. if (Math.abs(this.direction.y) < 0.0000001) {
  49830. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49831. return false;
  49832. }
  49833. }
  49834. else {
  49835. inv = 1.0 / this.direction.y;
  49836. min = (minimum.y - this.origin.y) * inv;
  49837. max = (maximum.y - this.origin.y) * inv;
  49838. if (max === -Infinity) {
  49839. max = Infinity;
  49840. }
  49841. if (min > max) {
  49842. temp = min;
  49843. min = max;
  49844. max = temp;
  49845. }
  49846. d = Math.max(min, d);
  49847. maxValue = Math.min(max, maxValue);
  49848. if (d > maxValue) {
  49849. return false;
  49850. }
  49851. }
  49852. if (Math.abs(this.direction.z) < 0.0000001) {
  49853. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49854. return false;
  49855. }
  49856. }
  49857. else {
  49858. inv = 1.0 / this.direction.z;
  49859. min = (minimum.z - this.origin.z) * inv;
  49860. max = (maximum.z - this.origin.z) * inv;
  49861. if (max === -Infinity) {
  49862. max = Infinity;
  49863. }
  49864. if (min > max) {
  49865. temp = min;
  49866. min = max;
  49867. max = temp;
  49868. }
  49869. d = Math.max(min, d);
  49870. maxValue = Math.min(max, maxValue);
  49871. if (d > maxValue) {
  49872. return false;
  49873. }
  49874. }
  49875. return true;
  49876. };
  49877. Ray.prototype.intersectsBox = function (box) {
  49878. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49879. };
  49880. Ray.prototype.intersectsSphere = function (sphere) {
  49881. var x = sphere.center.x - this.origin.x;
  49882. var y = sphere.center.y - this.origin.y;
  49883. var z = sphere.center.z - this.origin.z;
  49884. var pyth = (x * x) + (y * y) + (z * z);
  49885. var rr = sphere.radius * sphere.radius;
  49886. if (pyth <= rr) {
  49887. return true;
  49888. }
  49889. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49890. if (dot < 0.0) {
  49891. return false;
  49892. }
  49893. var temp = pyth - (dot * dot);
  49894. return temp <= rr;
  49895. };
  49896. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49897. if (!this._edge1) {
  49898. this._edge1 = BABYLON.Vector3.Zero();
  49899. this._edge2 = BABYLON.Vector3.Zero();
  49900. this._pvec = BABYLON.Vector3.Zero();
  49901. this._tvec = BABYLON.Vector3.Zero();
  49902. this._qvec = BABYLON.Vector3.Zero();
  49903. }
  49904. vertex1.subtractToRef(vertex0, this._edge1);
  49905. vertex2.subtractToRef(vertex0, this._edge2);
  49906. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49907. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49908. if (det === 0) {
  49909. return null;
  49910. }
  49911. var invdet = 1 / det;
  49912. this.origin.subtractToRef(vertex0, this._tvec);
  49913. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49914. if (bu < 0 || bu > 1.0) {
  49915. return null;
  49916. }
  49917. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49918. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49919. if (bv < 0 || bu + bv > 1.0) {
  49920. return null;
  49921. }
  49922. //check if the distance is longer than the predefined length.
  49923. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49924. if (distance > this.length) {
  49925. return null;
  49926. }
  49927. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49928. };
  49929. Ray.prototype.intersectsPlane = function (plane) {
  49930. var distance;
  49931. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49932. if (Math.abs(result1) < 9.99999997475243E-07) {
  49933. return null;
  49934. }
  49935. else {
  49936. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49937. distance = (-plane.d - result2) / result1;
  49938. if (distance < 0.0) {
  49939. if (distance < -9.99999997475243E-07) {
  49940. return null;
  49941. }
  49942. else {
  49943. return 0;
  49944. }
  49945. }
  49946. return distance;
  49947. }
  49948. };
  49949. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49950. var tm = BABYLON.Tmp.Matrix[0];
  49951. mesh.getWorldMatrix().invertToRef(tm);
  49952. if (this._tmpRay) {
  49953. Ray.TransformToRef(this, tm, this._tmpRay);
  49954. }
  49955. else {
  49956. this._tmpRay = Ray.Transform(this, tm);
  49957. }
  49958. return mesh.intersects(this._tmpRay, fastCheck);
  49959. };
  49960. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49961. if (results) {
  49962. results.length = 0;
  49963. }
  49964. else {
  49965. results = [];
  49966. }
  49967. for (var i = 0; i < meshes.length; i++) {
  49968. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49969. if (pickInfo.hit) {
  49970. results.push(pickInfo);
  49971. }
  49972. }
  49973. results.sort(this._comparePickingInfo);
  49974. return results;
  49975. };
  49976. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49977. if (pickingInfoA.distance < pickingInfoB.distance) {
  49978. return -1;
  49979. }
  49980. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49981. return 1;
  49982. }
  49983. else {
  49984. return 0;
  49985. }
  49986. };
  49987. /**
  49988. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49989. * @param sega the first point of the segment to test the intersection against
  49990. * @param segb the second point of the segment to test the intersection against
  49991. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49992. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49993. */
  49994. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49995. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49996. var u = segb.subtract(sega);
  49997. var v = rsegb.subtract(this.origin);
  49998. var w = sega.subtract(this.origin);
  49999. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50000. var b = BABYLON.Vector3.Dot(u, v);
  50001. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50002. var d = BABYLON.Vector3.Dot(u, w);
  50003. var e = BABYLON.Vector3.Dot(v, w);
  50004. var D = a * c - b * b; // always >= 0
  50005. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50006. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50007. // compute the line parameters of the two closest points
  50008. if (D < Ray.smallnum) {
  50009. sN = 0.0; // force using point P0 on segment S1
  50010. sD = 1.0; // to prevent possible division by 0.0 later
  50011. tN = e;
  50012. tD = c;
  50013. }
  50014. else {
  50015. sN = (b * e - c * d);
  50016. tN = (a * e - b * d);
  50017. if (sN < 0.0) {
  50018. sN = 0.0;
  50019. tN = e;
  50020. tD = c;
  50021. }
  50022. else if (sN > sD) {
  50023. sN = sD;
  50024. tN = e + b;
  50025. tD = c;
  50026. }
  50027. }
  50028. if (tN < 0.0) {
  50029. tN = 0.0;
  50030. // recompute sc for this edge
  50031. if (-d < 0.0) {
  50032. sN = 0.0;
  50033. }
  50034. else if (-d > a)
  50035. sN = sD;
  50036. else {
  50037. sN = -d;
  50038. sD = a;
  50039. }
  50040. }
  50041. else if (tN > tD) {
  50042. tN = tD;
  50043. // recompute sc for this edge
  50044. if ((-d + b) < 0.0) {
  50045. sN = 0;
  50046. }
  50047. else if ((-d + b) > a) {
  50048. sN = sD;
  50049. }
  50050. else {
  50051. sN = (-d + b);
  50052. sD = a;
  50053. }
  50054. }
  50055. // finally do the division to get sc and tc
  50056. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50057. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50058. // get the difference of the two closest points
  50059. var qtc = v.multiplyByFloats(tc, tc, tc);
  50060. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50061. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50062. if (isIntersected) {
  50063. return qtc.length();
  50064. }
  50065. return -1;
  50066. };
  50067. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50068. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50069. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50070. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50071. this.direction.normalize();
  50072. return this;
  50073. };
  50074. // Statics
  50075. Ray.Zero = function () {
  50076. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50077. };
  50078. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50079. var result = Ray.Zero();
  50080. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50081. };
  50082. /**
  50083. * 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
  50084. * transformed to the given world matrix.
  50085. * @param origin The origin point
  50086. * @param end The end point
  50087. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50088. */
  50089. Ray.CreateNewFromTo = function (origin, end, world) {
  50090. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50091. var direction = end.subtract(origin);
  50092. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50093. direction.normalize();
  50094. return Ray.Transform(new Ray(origin, direction, length), world);
  50095. };
  50096. Ray.Transform = function (ray, matrix) {
  50097. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50098. Ray.TransformToRef(ray, matrix, result);
  50099. return result;
  50100. };
  50101. Ray.TransformToRef = function (ray, matrix, result) {
  50102. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50103. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50104. result.length = ray.length;
  50105. var dir = result.direction;
  50106. var len = dir.length();
  50107. if (!(len === 0 || len === 1)) {
  50108. var num = 1.0 / len;
  50109. dir.x *= num;
  50110. dir.y *= num;
  50111. dir.z *= num;
  50112. result.length *= len;
  50113. }
  50114. };
  50115. Ray.smallnum = 0.00000001;
  50116. Ray.rayl = 10e8;
  50117. return Ray;
  50118. }());
  50119. BABYLON.Ray = Ray;
  50120. })(BABYLON || (BABYLON = {}));
  50121. //# sourceMappingURL=babylon.ray.js.map
  50122. var BABYLON;
  50123. (function (BABYLON) {
  50124. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50125. if (boxMin.x > sphereCenter.x + sphereRadius)
  50126. return false;
  50127. if (sphereCenter.x - sphereRadius > boxMax.x)
  50128. return false;
  50129. if (boxMin.y > sphereCenter.y + sphereRadius)
  50130. return false;
  50131. if (sphereCenter.y - sphereRadius > boxMax.y)
  50132. return false;
  50133. if (boxMin.z > sphereCenter.z + sphereRadius)
  50134. return false;
  50135. if (sphereCenter.z - sphereRadius > boxMax.z)
  50136. return false;
  50137. return true;
  50138. };
  50139. var getLowestRoot = (function () {
  50140. var result = { root: 0, found: false };
  50141. return function (a, b, c, maxR) {
  50142. result.root = 0;
  50143. result.found = false;
  50144. var determinant = b * b - 4.0 * a * c;
  50145. if (determinant < 0)
  50146. return result;
  50147. var sqrtD = Math.sqrt(determinant);
  50148. var r1 = (-b - sqrtD) / (2.0 * a);
  50149. var r2 = (-b + sqrtD) / (2.0 * a);
  50150. if (r1 > r2) {
  50151. var temp = r2;
  50152. r2 = r1;
  50153. r1 = temp;
  50154. }
  50155. if (r1 > 0 && r1 < maxR) {
  50156. result.root = r1;
  50157. result.found = true;
  50158. return result;
  50159. }
  50160. if (r2 > 0 && r2 < maxR) {
  50161. result.root = r2;
  50162. result.found = true;
  50163. return result;
  50164. }
  50165. return result;
  50166. };
  50167. })();
  50168. var Collider = /** @class */ (function () {
  50169. function Collider() {
  50170. this._collisionPoint = BABYLON.Vector3.Zero();
  50171. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50172. this._tempVector = BABYLON.Vector3.Zero();
  50173. this._tempVector2 = BABYLON.Vector3.Zero();
  50174. this._tempVector3 = BABYLON.Vector3.Zero();
  50175. this._tempVector4 = BABYLON.Vector3.Zero();
  50176. this._edge = BABYLON.Vector3.Zero();
  50177. this._baseToVertex = BABYLON.Vector3.Zero();
  50178. this._destinationPoint = BABYLON.Vector3.Zero();
  50179. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50180. this._displacementVector = BABYLON.Vector3.Zero();
  50181. this._radius = BABYLON.Vector3.One();
  50182. this._retry = 0;
  50183. this._basePointWorld = BABYLON.Vector3.Zero();
  50184. this._velocityWorld = BABYLON.Vector3.Zero();
  50185. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50186. this._collisionMask = -1;
  50187. }
  50188. Object.defineProperty(Collider.prototype, "collisionMask", {
  50189. get: function () {
  50190. return this._collisionMask;
  50191. },
  50192. set: function (mask) {
  50193. this._collisionMask = !isNaN(mask) ? mask : -1;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50199. /**
  50200. * Gets the plane normal used to compute the sliding response (in local space)
  50201. */
  50202. get: function () {
  50203. return this._slidePlaneNormal;
  50204. },
  50205. enumerable: true,
  50206. configurable: true
  50207. });
  50208. // Methods
  50209. Collider.prototype._initialize = function (source, dir, e) {
  50210. this._velocity = dir;
  50211. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50212. this._basePoint = source;
  50213. source.multiplyToRef(this._radius, this._basePointWorld);
  50214. dir.multiplyToRef(this._radius, this._velocityWorld);
  50215. this._velocityWorldLength = this._velocityWorld.length();
  50216. this._epsilon = e;
  50217. this.collisionFound = false;
  50218. };
  50219. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50220. pa.subtractToRef(point, this._tempVector);
  50221. pb.subtractToRef(point, this._tempVector2);
  50222. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50223. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50224. if (d < 0)
  50225. return false;
  50226. pc.subtractToRef(point, this._tempVector3);
  50227. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50228. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50229. if (d < 0)
  50230. return false;
  50231. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50232. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50233. return d >= 0;
  50234. };
  50235. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50236. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50237. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50238. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50239. return false;
  50240. }
  50241. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50242. return false;
  50243. return true;
  50244. };
  50245. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50246. var t0;
  50247. var embeddedInPlane = false;
  50248. //defensive programming, actually not needed.
  50249. if (!trianglePlaneArray) {
  50250. trianglePlaneArray = [];
  50251. }
  50252. if (!trianglePlaneArray[faceIndex]) {
  50253. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50254. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50255. }
  50256. var trianglePlane = trianglePlaneArray[faceIndex];
  50257. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50258. return;
  50259. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50260. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50261. if (normalDotVelocity == 0) {
  50262. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50263. return;
  50264. embeddedInPlane = true;
  50265. t0 = 0;
  50266. }
  50267. else {
  50268. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50269. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50270. if (t0 > t1) {
  50271. var temp = t1;
  50272. t1 = t0;
  50273. t0 = temp;
  50274. }
  50275. if (t0 > 1.0 || t1 < 0.0)
  50276. return;
  50277. if (t0 < 0)
  50278. t0 = 0;
  50279. if (t0 > 1.0)
  50280. t0 = 1.0;
  50281. }
  50282. this._collisionPoint.copyFromFloats(0, 0, 0);
  50283. var found = false;
  50284. var t = 1.0;
  50285. if (!embeddedInPlane) {
  50286. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50287. this._velocity.scaleToRef(t0, this._tempVector);
  50288. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50289. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50290. found = true;
  50291. t = t0;
  50292. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50293. }
  50294. }
  50295. if (!found) {
  50296. var velocitySquaredLength = this._velocity.lengthSquared();
  50297. var a = velocitySquaredLength;
  50298. this._basePoint.subtractToRef(p1, this._tempVector);
  50299. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50300. var c = this._tempVector.lengthSquared() - 1.0;
  50301. var lowestRoot = getLowestRoot(a, b, c, t);
  50302. if (lowestRoot.found) {
  50303. t = lowestRoot.root;
  50304. found = true;
  50305. this._collisionPoint.copyFrom(p1);
  50306. }
  50307. this._basePoint.subtractToRef(p2, this._tempVector);
  50308. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50309. c = this._tempVector.lengthSquared() - 1.0;
  50310. lowestRoot = getLowestRoot(a, b, c, t);
  50311. if (lowestRoot.found) {
  50312. t = lowestRoot.root;
  50313. found = true;
  50314. this._collisionPoint.copyFrom(p2);
  50315. }
  50316. this._basePoint.subtractToRef(p3, this._tempVector);
  50317. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50318. c = this._tempVector.lengthSquared() - 1.0;
  50319. lowestRoot = getLowestRoot(a, b, c, t);
  50320. if (lowestRoot.found) {
  50321. t = lowestRoot.root;
  50322. found = true;
  50323. this._collisionPoint.copyFrom(p3);
  50324. }
  50325. p2.subtractToRef(p1, this._edge);
  50326. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50327. var edgeSquaredLength = this._edge.lengthSquared();
  50328. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50329. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50330. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50331. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50332. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50333. lowestRoot = getLowestRoot(a, b, c, t);
  50334. if (lowestRoot.found) {
  50335. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50336. if (f >= 0.0 && f <= 1.0) {
  50337. t = lowestRoot.root;
  50338. found = true;
  50339. this._edge.scaleInPlace(f);
  50340. p1.addToRef(this._edge, this._collisionPoint);
  50341. }
  50342. }
  50343. p3.subtractToRef(p2, this._edge);
  50344. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50345. edgeSquaredLength = this._edge.lengthSquared();
  50346. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50347. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50348. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50349. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50350. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50351. lowestRoot = getLowestRoot(a, b, c, t);
  50352. if (lowestRoot.found) {
  50353. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50354. if (f >= 0.0 && f <= 1.0) {
  50355. t = lowestRoot.root;
  50356. found = true;
  50357. this._edge.scaleInPlace(f);
  50358. p2.addToRef(this._edge, this._collisionPoint);
  50359. }
  50360. }
  50361. p1.subtractToRef(p3, this._edge);
  50362. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50363. edgeSquaredLength = this._edge.lengthSquared();
  50364. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50365. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50366. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50367. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50368. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50369. lowestRoot = getLowestRoot(a, b, c, t);
  50370. if (lowestRoot.found) {
  50371. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50372. if (f >= 0.0 && f <= 1.0) {
  50373. t = lowestRoot.root;
  50374. found = true;
  50375. this._edge.scaleInPlace(f);
  50376. p3.addToRef(this._edge, this._collisionPoint);
  50377. }
  50378. }
  50379. }
  50380. if (found) {
  50381. var distToCollision = t * this._velocity.length();
  50382. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50383. if (!this.intersectionPoint) {
  50384. this.intersectionPoint = this._collisionPoint.clone();
  50385. }
  50386. else {
  50387. this.intersectionPoint.copyFrom(this._collisionPoint);
  50388. }
  50389. this._nearestDistance = distToCollision;
  50390. this.collisionFound = true;
  50391. }
  50392. }
  50393. };
  50394. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50395. for (var i = indexStart; i < indexEnd; i += 3) {
  50396. var p1 = pts[indices[i] - decal];
  50397. var p2 = pts[indices[i + 1] - decal];
  50398. var p3 = pts[indices[i + 2] - decal];
  50399. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50400. }
  50401. };
  50402. Collider.prototype._getResponse = function (pos, vel) {
  50403. pos.addToRef(vel, this._destinationPoint);
  50404. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50405. this._basePoint.addToRef(vel, pos);
  50406. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50407. this._slidePlaneNormal.normalize();
  50408. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50409. pos.addInPlace(this._displacementVector);
  50410. this.intersectionPoint.addInPlace(this._displacementVector);
  50411. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50412. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50413. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50414. };
  50415. return Collider;
  50416. }());
  50417. BABYLON.Collider = Collider;
  50418. })(BABYLON || (BABYLON = {}));
  50419. //# sourceMappingURL=babylon.collider.js.map
  50420. var BABYLON;
  50421. (function (BABYLON) {
  50422. //WebWorker code will be inserted to this variable.
  50423. BABYLON.CollisionWorker = "";
  50424. var WorkerTaskType;
  50425. (function (WorkerTaskType) {
  50426. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50427. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50428. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50429. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50430. var WorkerReplyType;
  50431. (function (WorkerReplyType) {
  50432. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50433. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50434. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50435. var CollisionCoordinatorWorker = /** @class */ (function () {
  50436. function CollisionCoordinatorWorker() {
  50437. var _this = this;
  50438. this._scaledPosition = BABYLON.Vector3.Zero();
  50439. this._scaledVelocity = BABYLON.Vector3.Zero();
  50440. this.onMeshUpdated = function (transformNode) {
  50441. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50442. };
  50443. this.onGeometryUpdated = function (geometry) {
  50444. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50445. };
  50446. this._afterRender = function () {
  50447. if (!_this._init)
  50448. return;
  50449. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50450. return;
  50451. }
  50452. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50453. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50454. if (_this._runningUpdated > 4) {
  50455. return;
  50456. }
  50457. ++_this._runningUpdated;
  50458. var payload = {
  50459. updatedMeshes: _this._addUpdateMeshesList,
  50460. updatedGeometries: _this._addUpdateGeometriesList,
  50461. removedGeometries: _this._toRemoveGeometryArray,
  50462. removedMeshes: _this._toRemoveMeshesArray
  50463. };
  50464. var message = {
  50465. payload: payload,
  50466. taskType: WorkerTaskType.UPDATE
  50467. };
  50468. var serializable = [];
  50469. for (var id in payload.updatedGeometries) {
  50470. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50471. //prepare transferables
  50472. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50473. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50474. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50475. }
  50476. }
  50477. _this._worker.postMessage(message, serializable);
  50478. _this._addUpdateMeshesList = {};
  50479. _this._addUpdateGeometriesList = {};
  50480. _this._toRemoveGeometryArray = [];
  50481. _this._toRemoveMeshesArray = [];
  50482. };
  50483. this._onMessageFromWorker = function (e) {
  50484. var returnData = e.data;
  50485. if (returnData.error != WorkerReplyType.SUCCESS) {
  50486. //TODO what errors can be returned from the worker?
  50487. BABYLON.Tools.Warn("error returned from worker!");
  50488. return;
  50489. }
  50490. switch (returnData.taskType) {
  50491. case WorkerTaskType.INIT:
  50492. _this._init = true;
  50493. //Update the worked with ALL of the scene's current state
  50494. _this._scene.meshes.forEach(function (mesh) {
  50495. _this.onMeshAdded(mesh);
  50496. });
  50497. _this._scene.getGeometries().forEach(function (geometry) {
  50498. _this.onGeometryAdded(geometry);
  50499. });
  50500. break;
  50501. case WorkerTaskType.UPDATE:
  50502. _this._runningUpdated--;
  50503. break;
  50504. case WorkerTaskType.COLLIDE:
  50505. var returnPayload = returnData.payload;
  50506. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50507. return;
  50508. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50509. if (callback) {
  50510. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50511. if (mesh) {
  50512. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50513. }
  50514. }
  50515. //cleanup
  50516. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50517. break;
  50518. }
  50519. };
  50520. this._collisionsCallbackArray = [];
  50521. this._init = false;
  50522. this._runningUpdated = 0;
  50523. this._addUpdateMeshesList = {};
  50524. this._addUpdateGeometriesList = {};
  50525. this._toRemoveGeometryArray = [];
  50526. this._toRemoveMeshesArray = [];
  50527. }
  50528. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50529. if (!this._init)
  50530. return;
  50531. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50532. return;
  50533. position.divideToRef(collider._radius, this._scaledPosition);
  50534. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50535. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50536. var payload = {
  50537. collider: {
  50538. position: this._scaledPosition.asArray(),
  50539. velocity: this._scaledVelocity.asArray(),
  50540. radius: collider._radius.asArray()
  50541. },
  50542. collisionId: collisionIndex,
  50543. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50544. maximumRetry: maximumRetry
  50545. };
  50546. var message = {
  50547. payload: payload,
  50548. taskType: WorkerTaskType.COLLIDE
  50549. };
  50550. this._worker.postMessage(message);
  50551. };
  50552. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50553. this._scene = scene;
  50554. this._scene.registerAfterRender(this._afterRender);
  50555. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50556. this._worker = new Worker(workerUrl);
  50557. this._worker.onmessage = this._onMessageFromWorker;
  50558. var message = {
  50559. payload: {},
  50560. taskType: WorkerTaskType.INIT
  50561. };
  50562. this._worker.postMessage(message);
  50563. };
  50564. CollisionCoordinatorWorker.prototype.destroy = function () {
  50565. this._scene.unregisterAfterRender(this._afterRender);
  50566. this._worker.terminate();
  50567. };
  50568. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50569. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50570. this.onMeshUpdated(mesh);
  50571. };
  50572. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50573. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50574. };
  50575. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50576. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50577. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50578. this.onGeometryUpdated(geometry);
  50579. };
  50580. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50581. this._toRemoveGeometryArray.push(geometry.id);
  50582. };
  50583. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50584. var submeshes = [];
  50585. if (mesh.subMeshes) {
  50586. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50587. var boundingInfo = sm.getBoundingInfo();
  50588. return {
  50589. position: idx,
  50590. verticesStart: sm.verticesStart,
  50591. verticesCount: sm.verticesCount,
  50592. indexStart: sm.indexStart,
  50593. indexCount: sm.indexCount,
  50594. hasMaterial: !!sm.getMaterial(),
  50595. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50596. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50597. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50598. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50599. };
  50600. });
  50601. }
  50602. var geometryId = null;
  50603. if (mesh instanceof BABYLON.Mesh) {
  50604. var geometry = mesh.geometry;
  50605. geometryId = geometry ? geometry.id : null;
  50606. }
  50607. else if (mesh instanceof BABYLON.InstancedMesh) {
  50608. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50609. geometryId = geometry ? geometry.id : null;
  50610. }
  50611. var boundingInfo = mesh.getBoundingInfo();
  50612. return {
  50613. uniqueId: mesh.uniqueId,
  50614. id: mesh.id,
  50615. name: mesh.name,
  50616. geometryId: geometryId,
  50617. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50618. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50619. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50620. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50621. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50622. subMeshes: submeshes,
  50623. checkCollisions: mesh.checkCollisions
  50624. };
  50625. };
  50626. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50627. return {
  50628. id: geometry.id,
  50629. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50630. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50631. indices: new Uint32Array(geometry.getIndices() || []),
  50632. };
  50633. };
  50634. return CollisionCoordinatorWorker;
  50635. }());
  50636. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50637. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50638. function CollisionCoordinatorLegacy() {
  50639. this._scaledPosition = BABYLON.Vector3.Zero();
  50640. this._scaledVelocity = BABYLON.Vector3.Zero();
  50641. this._finalPosition = BABYLON.Vector3.Zero();
  50642. }
  50643. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50644. position.divideToRef(collider._radius, this._scaledPosition);
  50645. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50646. collider.collidedMesh = null;
  50647. collider._retry = 0;
  50648. collider._initialVelocity = this._scaledVelocity;
  50649. collider._initialPosition = this._scaledPosition;
  50650. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50651. this._finalPosition.multiplyInPlace(collider._radius);
  50652. //run the callback
  50653. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50654. };
  50655. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50656. this._scene = scene;
  50657. };
  50658. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50659. //Legacy need no destruction method.
  50660. };
  50661. //No update in legacy mode
  50662. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50663. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50664. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50665. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50666. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50667. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50668. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50669. if (excludedMesh === void 0) { excludedMesh = null; }
  50670. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50671. if (collider._retry >= maximumRetry) {
  50672. finalPosition.copyFrom(position);
  50673. return;
  50674. }
  50675. // Check if this is a mesh else camera or -1
  50676. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50677. collider._initialize(position, velocity, closeDistance);
  50678. // Check all meshes
  50679. for (var index = 0; index < this._scene.meshes.length; index++) {
  50680. var mesh = this._scene.meshes[index];
  50681. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50682. mesh._checkCollision(collider);
  50683. }
  50684. }
  50685. if (!collider.collisionFound) {
  50686. position.addToRef(velocity, finalPosition);
  50687. return;
  50688. }
  50689. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50690. collider._getResponse(position, velocity);
  50691. }
  50692. if (velocity.length() <= closeDistance) {
  50693. finalPosition.copyFrom(position);
  50694. return;
  50695. }
  50696. collider._retry++;
  50697. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50698. };
  50699. return CollisionCoordinatorLegacy;
  50700. }());
  50701. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50702. })(BABYLON || (BABYLON = {}));
  50703. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50704. var BABYLON;
  50705. (function (BABYLON) {
  50706. /**
  50707. * A particle represents one of the element emitted by a particle system.
  50708. * This is mainly define by its coordinates, direction, velocity and age.
  50709. */
  50710. var Particle = /** @class */ (function () {
  50711. /**
  50712. * Creates a new instance of @see Particle
  50713. * @param particleSystem the particle system the particle belongs to
  50714. */
  50715. function Particle(particleSystem) {
  50716. this.particleSystem = particleSystem;
  50717. /**
  50718. * The world position of the particle in the scene.
  50719. */
  50720. this.position = BABYLON.Vector3.Zero();
  50721. /**
  50722. * The world direction of the particle in the scene.
  50723. */
  50724. this.direction = BABYLON.Vector3.Zero();
  50725. /**
  50726. * The color of the particle.
  50727. */
  50728. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50729. /**
  50730. * The color change of the particle per step.
  50731. */
  50732. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50733. /**
  50734. * Defines how long will the life of the particle be.
  50735. */
  50736. this.lifeTime = 1.0;
  50737. /**
  50738. * The current age of the particle.
  50739. */
  50740. this.age = 0;
  50741. /**
  50742. * The current size of the particle.
  50743. */
  50744. this.size = 0;
  50745. /**
  50746. * The current angle of the particle.
  50747. */
  50748. this.angle = 0;
  50749. /**
  50750. * Defines how fast is the angle changing.
  50751. */
  50752. this.angularSpeed = 0;
  50753. /**
  50754. * Defines the cell index used by the particle to be rendered from a sprite.
  50755. */
  50756. this.cellIndex = 0;
  50757. this._currentFrameCounter = 0;
  50758. if (!this.particleSystem.isAnimationSheetEnabled) {
  50759. return;
  50760. }
  50761. this.cellIndex = this.particleSystem.startSpriteCellID;
  50762. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50763. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50764. }
  50765. else {
  50766. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50767. }
  50768. }
  50769. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50770. // (ageOffset / scaledUpdateSpeed) / available cells
  50771. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50772. this._currentFrameCounter += scaledUpdateSpeed;
  50773. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50774. this._currentFrameCounter = 0;
  50775. this.cellIndex++;
  50776. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50777. this.cellIndex = this.particleSystem.endSpriteCellID;
  50778. }
  50779. }
  50780. };
  50781. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50782. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50783. this.cellIndex++;
  50784. this._currentFrameCounter = 0;
  50785. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50786. if (this.particleSystem.spriteCellLoop) {
  50787. this.cellIndex = this.particleSystem.startSpriteCellID;
  50788. }
  50789. else {
  50790. this.cellIndex = this.particleSystem.endSpriteCellID;
  50791. }
  50792. }
  50793. }
  50794. else {
  50795. this._currentFrameCounter++;
  50796. }
  50797. };
  50798. /**
  50799. * Copy the properties of particle to another one.
  50800. * @param other the particle to copy the information to.
  50801. */
  50802. Particle.prototype.copyTo = function (other) {
  50803. other.position.copyFrom(this.position);
  50804. other.direction.copyFrom(this.direction);
  50805. other.color.copyFrom(this.color);
  50806. other.colorStep.copyFrom(this.colorStep);
  50807. other.lifeTime = this.lifeTime;
  50808. other.age = this.age;
  50809. other.size = this.size;
  50810. other.angle = this.angle;
  50811. other.angularSpeed = this.angularSpeed;
  50812. other.particleSystem = this.particleSystem;
  50813. other.cellIndex = this.cellIndex;
  50814. };
  50815. return Particle;
  50816. }());
  50817. BABYLON.Particle = Particle;
  50818. })(BABYLON || (BABYLON = {}));
  50819. //# sourceMappingURL=babylon.particle.js.map
  50820. var BABYLON;
  50821. (function (BABYLON) {
  50822. /**
  50823. * This represents a particle system in Babylon.
  50824. * 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.
  50825. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50826. * @example https://doc.babylonjs.com/babylon101/particles
  50827. */
  50828. var ParticleSystem = /** @class */ (function () {
  50829. /**
  50830. * Instantiates a particle system.
  50831. * 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.
  50832. * @param name The name of the particle system
  50833. * @param capacity The max number of particles alive at the same time
  50834. * @param scene The scene the particle system belongs to
  50835. * @param customEffect a custom effect used to change the way particles are rendered by default
  50836. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50837. * @param epsilon Offset used to render the particles
  50838. */
  50839. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50840. if (customEffect === void 0) { customEffect = null; }
  50841. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50842. if (epsilon === void 0) { epsilon = 0.01; }
  50843. var _this = this;
  50844. /**
  50845. * List of animations used by the particle system.
  50846. */
  50847. this.animations = [];
  50848. /**
  50849. * The rendering group used by the Particle system to chose when to render.
  50850. */
  50851. this.renderingGroupId = 0;
  50852. /**
  50853. * The emitter represents the Mesh or position we are attaching the particle system to.
  50854. */
  50855. this.emitter = null;
  50856. /**
  50857. * The maximum number of particles to emit per frame
  50858. */
  50859. this.emitRate = 10;
  50860. /**
  50861. * If you want to launch only a few particles at once, that can be done, as well.
  50862. */
  50863. this.manualEmitCount = -1;
  50864. /**
  50865. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50866. */
  50867. this.updateSpeed = 0.01;
  50868. /**
  50869. * The amount of time the particle system is running (depends of the overall update speed).
  50870. */
  50871. this.targetStopDuration = 0;
  50872. /**
  50873. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50874. */
  50875. this.disposeOnStop = false;
  50876. /**
  50877. * Minimum power of emitting particles.
  50878. */
  50879. this.minEmitPower = 1;
  50880. /**
  50881. * Maximum power of emitting particles.
  50882. */
  50883. this.maxEmitPower = 1;
  50884. /**
  50885. * Minimum life time of emitting particles.
  50886. */
  50887. this.minLifeTime = 1;
  50888. /**
  50889. * Maximum life time of emitting particles.
  50890. */
  50891. this.maxLifeTime = 1;
  50892. /**
  50893. * Minimum Size of emitting particles.
  50894. */
  50895. this.minSize = 1;
  50896. /**
  50897. * Maximum Size of emitting particles.
  50898. */
  50899. this.maxSize = 1;
  50900. /**
  50901. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50902. */
  50903. this.minAngularSpeed = 0;
  50904. /**
  50905. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50906. */
  50907. this.maxAngularSpeed = 0;
  50908. /**
  50909. * The layer mask we are rendering the particles through.
  50910. */
  50911. this.layerMask = 0x0FFFFFFF;
  50912. /**
  50913. * This can help using your own shader to render the particle system.
  50914. * The according effect will be created
  50915. */
  50916. this.customShader = null;
  50917. /**
  50918. * By default particle system starts as soon as they are created. This prevents the
  50919. * automatic start to happen and let you decide when to start emitting particles.
  50920. */
  50921. this.preventAutoStart = false;
  50922. /**
  50923. * Callback triggered when the particle animation is ending.
  50924. */
  50925. this.onAnimationEnd = null;
  50926. /**
  50927. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50928. */
  50929. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50930. /**
  50931. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50932. * to override the particles.
  50933. */
  50934. this.forceDepthWrite = false;
  50935. /**
  50936. * You can use gravity if you want to give an orientation to your particles.
  50937. */
  50938. this.gravity = BABYLON.Vector3.Zero();
  50939. /**
  50940. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50941. */
  50942. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50943. /**
  50944. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50945. */
  50946. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50947. /**
  50948. * Color the particle will have at the end of its lifetime.
  50949. */
  50950. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50951. /**
  50952. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50953. */
  50954. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50955. /**
  50956. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50957. */
  50958. this.spriteCellLoop = true;
  50959. /**
  50960. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50961. */
  50962. this.spriteCellChangeSpeed = 0;
  50963. /**
  50964. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50965. */
  50966. this.startSpriteCellID = 0;
  50967. /**
  50968. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50969. */
  50970. this.endSpriteCellID = 0;
  50971. /**
  50972. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50973. */
  50974. this.spriteCellWidth = 0;
  50975. /**
  50976. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50977. */
  50978. this.spriteCellHeight = 0;
  50979. /**
  50980. * An event triggered when the system is disposed.
  50981. */
  50982. this.onDisposeObservable = new BABYLON.Observable();
  50983. this._particles = new Array();
  50984. this._stockParticles = new Array();
  50985. this._newPartsExcess = 0;
  50986. this._vertexBuffers = {};
  50987. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50988. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50989. this._scaledDirection = BABYLON.Vector3.Zero();
  50990. this._scaledGravity = BABYLON.Vector3.Zero();
  50991. this._currentRenderId = -1;
  50992. this._started = false;
  50993. this._stopped = false;
  50994. this._actualFrame = 0;
  50995. this._vertexBufferSize = 11;
  50996. this._appendParticleVertexes = null;
  50997. this.id = name;
  50998. this.name = name;
  50999. this._capacity = capacity;
  51000. this._epsilon = epsilon;
  51001. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51002. if (isAnimationSheetEnabled) {
  51003. this._vertexBufferSize = 12;
  51004. }
  51005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51006. this._customEffect = customEffect;
  51007. scene.particleSystems.push(this);
  51008. this._createIndexBuffer();
  51009. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51010. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51011. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51012. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51013. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51014. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51015. if (this._isAnimationSheetEnabled) {
  51016. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51017. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51018. }
  51019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51020. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51021. this._vertexBuffers["options"] = options;
  51022. // Default emitter type
  51023. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51024. this.updateFunction = function (particles) {
  51025. for (var index = 0; index < particles.length; index++) {
  51026. var particle = particles[index];
  51027. particle.age += _this._scaledUpdateSpeed;
  51028. if (particle.age >= particle.lifeTime) {
  51029. _this.recycleParticle(particle);
  51030. index--;
  51031. continue;
  51032. }
  51033. else {
  51034. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51035. particle.color.addInPlace(_this._scaledColorStep);
  51036. if (particle.color.a < 0)
  51037. particle.color.a = 0;
  51038. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51039. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51040. particle.position.addInPlace(_this._scaledDirection);
  51041. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51042. particle.direction.addInPlace(_this._scaledGravity);
  51043. if (_this._isAnimationSheetEnabled) {
  51044. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51045. }
  51046. }
  51047. }
  51048. };
  51049. }
  51050. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51051. /**
  51052. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51053. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51054. */
  51055. get: function () {
  51056. if (this.particleEmitterType.direction1) {
  51057. return this.particleEmitterType.direction1;
  51058. }
  51059. return BABYLON.Vector3.Zero();
  51060. },
  51061. set: function (value) {
  51062. if (this.particleEmitterType.direction1) {
  51063. this.particleEmitterType.direction1 = value;
  51064. }
  51065. },
  51066. enumerable: true,
  51067. configurable: true
  51068. });
  51069. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51070. /**
  51071. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51072. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51073. */
  51074. get: function () {
  51075. if (this.particleEmitterType.direction2) {
  51076. return this.particleEmitterType.direction2;
  51077. }
  51078. return BABYLON.Vector3.Zero();
  51079. },
  51080. set: function (value) {
  51081. if (this.particleEmitterType.direction2) {
  51082. this.particleEmitterType.direction2 = value;
  51083. }
  51084. },
  51085. enumerable: true,
  51086. configurable: true
  51087. });
  51088. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51089. /**
  51090. * 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.
  51091. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51092. */
  51093. get: function () {
  51094. if (this.particleEmitterType.minEmitBox) {
  51095. return this.particleEmitterType.minEmitBox;
  51096. }
  51097. return BABYLON.Vector3.Zero();
  51098. },
  51099. set: function (value) {
  51100. if (this.particleEmitterType.minEmitBox) {
  51101. this.particleEmitterType.minEmitBox = value;
  51102. }
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51108. /**
  51109. * 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.
  51110. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51111. */
  51112. get: function () {
  51113. if (this.particleEmitterType.maxEmitBox) {
  51114. return this.particleEmitterType.maxEmitBox;
  51115. }
  51116. return BABYLON.Vector3.Zero();
  51117. },
  51118. set: function (value) {
  51119. if (this.particleEmitterType.maxEmitBox) {
  51120. this.particleEmitterType.maxEmitBox = value;
  51121. }
  51122. },
  51123. enumerable: true,
  51124. configurable: true
  51125. });
  51126. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51127. /**
  51128. * Sets a callback that will be triggered when the system is disposed.
  51129. */
  51130. set: function (callback) {
  51131. if (this._onDisposeObserver) {
  51132. this.onDisposeObservable.remove(this._onDisposeObserver);
  51133. }
  51134. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51135. },
  51136. enumerable: true,
  51137. configurable: true
  51138. });
  51139. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51140. /**
  51141. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51142. */
  51143. get: function () {
  51144. return this._isAnimationSheetEnabled;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51150. /**
  51151. * Gets the current list of active particles
  51152. */
  51153. get: function () {
  51154. return this._particles;
  51155. },
  51156. enumerable: true,
  51157. configurable: true
  51158. });
  51159. /**
  51160. * Returns the string "ParticleSystem"
  51161. * @returns a string containing the class name
  51162. */
  51163. ParticleSystem.prototype.getClassName = function () {
  51164. return "ParticleSystem";
  51165. };
  51166. ParticleSystem.prototype._createIndexBuffer = function () {
  51167. var indices = [];
  51168. var index = 0;
  51169. for (var count = 0; count < this._capacity; count++) {
  51170. indices.push(index);
  51171. indices.push(index + 1);
  51172. indices.push(index + 2);
  51173. indices.push(index);
  51174. indices.push(index + 2);
  51175. indices.push(index + 3);
  51176. index += 4;
  51177. }
  51178. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51179. };
  51180. /**
  51181. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51182. * Its lifetime will start back at 0.
  51183. * @param particle The particle to recycle
  51184. */
  51185. ParticleSystem.prototype.recycleParticle = function (particle) {
  51186. var lastParticle = this._particles.pop();
  51187. if (lastParticle !== particle) {
  51188. lastParticle.copyTo(particle);
  51189. this._stockParticles.push(lastParticle);
  51190. }
  51191. };
  51192. /**
  51193. * Gets the maximum number of particles active at the same time.
  51194. * @returns The max number of active particles.
  51195. */
  51196. ParticleSystem.prototype.getCapacity = function () {
  51197. return this._capacity;
  51198. };
  51199. /**
  51200. * Gets Wether there are still active particles in the system.
  51201. * @returns True if it is alive, otherwise false.
  51202. */
  51203. ParticleSystem.prototype.isAlive = function () {
  51204. return this._alive;
  51205. };
  51206. /**
  51207. * Gets Wether the system has been started.
  51208. * @returns True if it has been started, otherwise false.
  51209. */
  51210. ParticleSystem.prototype.isStarted = function () {
  51211. return this._started;
  51212. };
  51213. /**
  51214. * Starts the particle system and begins to emit.
  51215. */
  51216. ParticleSystem.prototype.start = function () {
  51217. this._started = true;
  51218. this._stopped = false;
  51219. this._actualFrame = 0;
  51220. };
  51221. /**
  51222. * Stops the particle system.
  51223. */
  51224. ParticleSystem.prototype.stop = function () {
  51225. this._stopped = true;
  51226. };
  51227. /**
  51228. * Remove all active particles
  51229. */
  51230. ParticleSystem.prototype.reset = function () {
  51231. this._stockParticles = [];
  51232. this._particles = [];
  51233. };
  51234. /**
  51235. * @ignore (for internal use only)
  51236. */
  51237. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51238. var offset = index * this._vertexBufferSize;
  51239. this._vertexData[offset] = particle.position.x;
  51240. this._vertexData[offset + 1] = particle.position.y;
  51241. this._vertexData[offset + 2] = particle.position.z;
  51242. this._vertexData[offset + 3] = particle.color.r;
  51243. this._vertexData[offset + 4] = particle.color.g;
  51244. this._vertexData[offset + 5] = particle.color.b;
  51245. this._vertexData[offset + 6] = particle.color.a;
  51246. this._vertexData[offset + 7] = particle.angle;
  51247. this._vertexData[offset + 8] = particle.size;
  51248. this._vertexData[offset + 9] = offsetX;
  51249. this._vertexData[offset + 10] = offsetY;
  51250. };
  51251. /**
  51252. * @ignore (for internal use only)
  51253. */
  51254. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51255. if (offsetX === 0)
  51256. offsetX = this._epsilon;
  51257. else if (offsetX === 1)
  51258. offsetX = 1 - this._epsilon;
  51259. if (offsetY === 0)
  51260. offsetY = this._epsilon;
  51261. else if (offsetY === 1)
  51262. offsetY = 1 - this._epsilon;
  51263. var offset = index * this._vertexBufferSize;
  51264. this._vertexData[offset] = particle.position.x;
  51265. this._vertexData[offset + 1] = particle.position.y;
  51266. this._vertexData[offset + 2] = particle.position.z;
  51267. this._vertexData[offset + 3] = particle.color.r;
  51268. this._vertexData[offset + 4] = particle.color.g;
  51269. this._vertexData[offset + 5] = particle.color.b;
  51270. this._vertexData[offset + 6] = particle.color.a;
  51271. this._vertexData[offset + 7] = particle.angle;
  51272. this._vertexData[offset + 8] = particle.size;
  51273. this._vertexData[offset + 9] = offsetX;
  51274. this._vertexData[offset + 10] = offsetY;
  51275. this._vertexData[offset + 11] = particle.cellIndex;
  51276. };
  51277. ParticleSystem.prototype._update = function (newParticles) {
  51278. // Update current
  51279. this._alive = this._particles.length > 0;
  51280. this.updateFunction(this._particles);
  51281. // Add new ones
  51282. var worldMatrix;
  51283. if (this.emitter.position) {
  51284. var emitterMesh = this.emitter;
  51285. worldMatrix = emitterMesh.getWorldMatrix();
  51286. }
  51287. else {
  51288. var emitterPosition = this.emitter;
  51289. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51290. }
  51291. var particle;
  51292. for (var index = 0; index < newParticles; index++) {
  51293. if (this._particles.length === this._capacity) {
  51294. break;
  51295. }
  51296. if (this._stockParticles.length !== 0) {
  51297. particle = this._stockParticles.pop();
  51298. particle.age = 0;
  51299. particle.cellIndex = this.startSpriteCellID;
  51300. }
  51301. else {
  51302. particle = new BABYLON.Particle(this);
  51303. }
  51304. this._particles.push(particle);
  51305. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51306. if (this.startPositionFunction) {
  51307. this.startPositionFunction(worldMatrix, particle.position, particle);
  51308. }
  51309. else {
  51310. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51311. }
  51312. if (this.startDirectionFunction) {
  51313. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51314. }
  51315. else {
  51316. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51317. }
  51318. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51319. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51320. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51321. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51322. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51323. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51324. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51325. }
  51326. };
  51327. ParticleSystem.prototype._getEffect = function () {
  51328. if (this._customEffect) {
  51329. return this._customEffect;
  51330. }
  51331. ;
  51332. var defines = [];
  51333. if (this._scene.clipPlane) {
  51334. defines.push("#define CLIPPLANE");
  51335. }
  51336. if (this._isAnimationSheetEnabled) {
  51337. defines.push("#define ANIMATESHEET");
  51338. }
  51339. // Effect
  51340. var join = defines.join("\n");
  51341. if (this._cachedDefines !== join) {
  51342. this._cachedDefines = join;
  51343. var attributesNamesOrOptions;
  51344. var effectCreationOption;
  51345. if (this._isAnimationSheetEnabled) {
  51346. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51347. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51348. }
  51349. else {
  51350. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51351. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51352. }
  51353. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51354. }
  51355. return this._effect;
  51356. };
  51357. /**
  51358. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51359. */
  51360. ParticleSystem.prototype.animate = function () {
  51361. if (!this._started)
  51362. return;
  51363. var effect = this._getEffect();
  51364. // Check
  51365. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51366. return;
  51367. if (this._currentRenderId === this._scene.getRenderId()) {
  51368. return;
  51369. }
  51370. this._currentRenderId = this._scene.getRenderId();
  51371. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51372. // determine the number of particles we need to create
  51373. var newParticles;
  51374. if (this.manualEmitCount > -1) {
  51375. newParticles = this.manualEmitCount;
  51376. this._newPartsExcess = 0;
  51377. this.manualEmitCount = 0;
  51378. }
  51379. else {
  51380. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51381. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51382. }
  51383. if (this._newPartsExcess > 1.0) {
  51384. newParticles += this._newPartsExcess >> 0;
  51385. this._newPartsExcess -= this._newPartsExcess >> 0;
  51386. }
  51387. this._alive = false;
  51388. if (!this._stopped) {
  51389. this._actualFrame += this._scaledUpdateSpeed;
  51390. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51391. this.stop();
  51392. }
  51393. else {
  51394. newParticles = 0;
  51395. }
  51396. this._update(newParticles);
  51397. // Stopped?
  51398. if (this._stopped) {
  51399. if (!this._alive) {
  51400. this._started = false;
  51401. if (this.onAnimationEnd) {
  51402. this.onAnimationEnd();
  51403. }
  51404. if (this.disposeOnStop) {
  51405. this._scene._toBeDisposed.push(this);
  51406. }
  51407. }
  51408. }
  51409. // Animation sheet
  51410. if (this._isAnimationSheetEnabled) {
  51411. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51412. }
  51413. else {
  51414. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51415. }
  51416. // Update VBO
  51417. var offset = 0;
  51418. for (var index = 0; index < this._particles.length; index++) {
  51419. var particle = this._particles[index];
  51420. this._appendParticleVertexes(offset, particle);
  51421. offset += 4;
  51422. }
  51423. if (this._vertexBuffer) {
  51424. this._vertexBuffer.update(this._vertexData);
  51425. }
  51426. };
  51427. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51428. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51429. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51430. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51431. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51432. };
  51433. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51434. this._appendParticleVertex(offset++, particle, 0, 0);
  51435. this._appendParticleVertex(offset++, particle, 1, 0);
  51436. this._appendParticleVertex(offset++, particle, 1, 1);
  51437. this._appendParticleVertex(offset++, particle, 0, 1);
  51438. };
  51439. /**
  51440. * Rebuilds the particle system.
  51441. */
  51442. ParticleSystem.prototype.rebuild = function () {
  51443. this._createIndexBuffer();
  51444. if (this._vertexBuffer) {
  51445. this._vertexBuffer._rebuild();
  51446. }
  51447. };
  51448. /**
  51449. * Renders the particle system in its current state.
  51450. * @returns the current number of particles
  51451. */
  51452. ParticleSystem.prototype.render = function () {
  51453. var effect = this._getEffect();
  51454. // Check
  51455. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51456. return 0;
  51457. }
  51458. var engine = this._scene.getEngine();
  51459. // Render
  51460. engine.enableEffect(effect);
  51461. engine.setState(false);
  51462. var viewMatrix = this._scene.getViewMatrix();
  51463. effect.setTexture("diffuseSampler", this.particleTexture);
  51464. effect.setMatrix("view", viewMatrix);
  51465. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51466. if (this._isAnimationSheetEnabled) {
  51467. var baseSize = this.particleTexture.getBaseSize();
  51468. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51469. }
  51470. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51471. if (this._scene.clipPlane) {
  51472. var clipPlane = this._scene.clipPlane;
  51473. var invView = viewMatrix.clone();
  51474. invView.invert();
  51475. effect.setMatrix("invView", invView);
  51476. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51477. }
  51478. // VBOs
  51479. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51480. // Draw order
  51481. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51482. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51483. }
  51484. else {
  51485. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51486. }
  51487. if (this.forceDepthWrite) {
  51488. engine.setDepthWrite(true);
  51489. }
  51490. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51491. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51492. return this._particles.length;
  51493. };
  51494. /**
  51495. * Disposes the particle system and free the associated resources
  51496. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51497. */
  51498. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51499. if (disposeTexture === void 0) { disposeTexture = true; }
  51500. if (this._vertexBuffer) {
  51501. this._vertexBuffer.dispose();
  51502. this._vertexBuffer = null;
  51503. }
  51504. if (this._indexBuffer) {
  51505. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51506. this._indexBuffer = null;
  51507. }
  51508. if (disposeTexture && this.particleTexture) {
  51509. this.particleTexture.dispose();
  51510. this.particleTexture = null;
  51511. }
  51512. // Remove from scene
  51513. var index = this._scene.particleSystems.indexOf(this);
  51514. if (index > -1) {
  51515. this._scene.particleSystems.splice(index, 1);
  51516. }
  51517. // Callback
  51518. this.onDisposeObservable.notifyObservers(this);
  51519. this.onDisposeObservable.clear();
  51520. };
  51521. /**
  51522. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51523. * @param radius The radius of the sphere to emit from
  51524. * @returns the emitter
  51525. */
  51526. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51527. if (radius === void 0) { radius = 1; }
  51528. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51529. this.particleEmitterType = particleEmitter;
  51530. return particleEmitter;
  51531. };
  51532. /**
  51533. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51534. * @param radius The radius of the sphere to emit from
  51535. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51536. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51537. * @returns the emitter
  51538. */
  51539. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51540. if (radius === void 0) { radius = 1; }
  51541. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51542. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51543. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51544. this.particleEmitterType = particleEmitter;
  51545. return particleEmitter;
  51546. };
  51547. /**
  51548. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51549. * @param radius The radius of the cone to emit from
  51550. * @param angle The base angle of the cone
  51551. * @returns the emitter
  51552. */
  51553. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51554. if (radius === void 0) { radius = 1; }
  51555. if (angle === void 0) { angle = Math.PI / 4; }
  51556. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51557. this.particleEmitterType = particleEmitter;
  51558. return particleEmitter;
  51559. };
  51560. // 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.
  51561. /**
  51562. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51563. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51564. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51565. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51566. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51567. * @returns the emitter
  51568. */
  51569. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51570. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51571. this.direction1 = direction1;
  51572. this.direction2 = direction2;
  51573. this.minEmitBox = minEmitBox;
  51574. this.maxEmitBox = maxEmitBox;
  51575. this.particleEmitterType = particleEmitter;
  51576. return particleEmitter;
  51577. };
  51578. /**
  51579. * Clones the particle system.
  51580. * @param name The name of the cloned object
  51581. * @param newEmitter The new emitter to use
  51582. * @returns the cloned particle system
  51583. */
  51584. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51585. var custom = null;
  51586. var program = null;
  51587. if (this.customShader != null) {
  51588. program = this.customShader;
  51589. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51590. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51591. }
  51592. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51593. result.customShader = program;
  51594. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51595. if (newEmitter === undefined) {
  51596. newEmitter = this.emitter;
  51597. }
  51598. result.emitter = newEmitter;
  51599. if (this.particleTexture) {
  51600. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51601. }
  51602. if (!this.preventAutoStart) {
  51603. result.start();
  51604. }
  51605. return result;
  51606. };
  51607. /**
  51608. * Serializes the particle system to a JSON object.
  51609. * @returns the JSON object
  51610. */
  51611. ParticleSystem.prototype.serialize = function () {
  51612. var serializationObject = {};
  51613. serializationObject.name = this.name;
  51614. serializationObject.id = this.id;
  51615. // Emitter
  51616. if (this.emitter.position) {
  51617. var emitterMesh = this.emitter;
  51618. serializationObject.emitterId = emitterMesh.id;
  51619. }
  51620. else {
  51621. var emitterPosition = this.emitter;
  51622. serializationObject.emitter = emitterPosition.asArray();
  51623. }
  51624. serializationObject.capacity = this.getCapacity();
  51625. if (this.particleTexture) {
  51626. serializationObject.textureName = this.particleTexture.name;
  51627. }
  51628. // Animations
  51629. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51630. // Particle system
  51631. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51632. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51633. serializationObject.minSize = this.minSize;
  51634. serializationObject.maxSize = this.maxSize;
  51635. serializationObject.minEmitPower = this.minEmitPower;
  51636. serializationObject.maxEmitPower = this.maxEmitPower;
  51637. serializationObject.minLifeTime = this.minLifeTime;
  51638. serializationObject.maxLifeTime = this.maxLifeTime;
  51639. serializationObject.emitRate = this.emitRate;
  51640. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51641. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51642. serializationObject.gravity = this.gravity.asArray();
  51643. serializationObject.direction1 = this.direction1.asArray();
  51644. serializationObject.direction2 = this.direction2.asArray();
  51645. serializationObject.color1 = this.color1.asArray();
  51646. serializationObject.color2 = this.color2.asArray();
  51647. serializationObject.colorDead = this.colorDead.asArray();
  51648. serializationObject.updateSpeed = this.updateSpeed;
  51649. serializationObject.targetStopDuration = this.targetStopDuration;
  51650. serializationObject.textureMask = this.textureMask.asArray();
  51651. serializationObject.blendMode = this.blendMode;
  51652. serializationObject.customShader = this.customShader;
  51653. serializationObject.preventAutoStart = this.preventAutoStart;
  51654. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51655. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51656. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51657. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51658. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51659. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51660. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51661. // Emitter
  51662. if (this.particleEmitterType) {
  51663. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51664. }
  51665. return serializationObject;
  51666. };
  51667. /**
  51668. * Parses a JSON object to create a particle system.
  51669. * @param parsedParticleSystem The JSON object to parse
  51670. * @param scene The scene to create the particle system in
  51671. * @param rootUrl The root url to use to load external dependencies like texture
  51672. * @returns the Parsed particle system
  51673. */
  51674. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51675. var name = parsedParticleSystem.name;
  51676. var custom = null;
  51677. var program = null;
  51678. if (parsedParticleSystem.customShader) {
  51679. program = parsedParticleSystem.customShader;
  51680. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51681. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51682. }
  51683. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51684. particleSystem.customShader = program;
  51685. if (parsedParticleSystem.id) {
  51686. particleSystem.id = parsedParticleSystem.id;
  51687. }
  51688. // Auto start
  51689. if (parsedParticleSystem.preventAutoStart) {
  51690. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51691. }
  51692. // Texture
  51693. if (parsedParticleSystem.textureName) {
  51694. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51695. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51696. }
  51697. // Emitter
  51698. if (parsedParticleSystem.emitterId) {
  51699. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51700. }
  51701. else {
  51702. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51703. }
  51704. // Animations
  51705. if (parsedParticleSystem.animations) {
  51706. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51707. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51708. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51709. }
  51710. }
  51711. if (parsedParticleSystem.autoAnimate) {
  51712. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51713. }
  51714. // Particle system
  51715. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51716. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51717. particleSystem.minSize = parsedParticleSystem.minSize;
  51718. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51719. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51720. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51721. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51722. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51723. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51724. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51725. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51726. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51727. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51728. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51729. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51730. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51731. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51732. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51733. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51734. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51735. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51736. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51737. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51738. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51739. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51740. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51741. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51742. if (!particleSystem.preventAutoStart) {
  51743. particleSystem.start();
  51744. }
  51745. return particleSystem;
  51746. };
  51747. /**
  51748. * Source color is added to the destination color without alpha affecting the result.
  51749. */
  51750. ParticleSystem.BLENDMODE_ONEONE = 0;
  51751. /**
  51752. * Blend current color and particle color using particle’s alpha.
  51753. */
  51754. ParticleSystem.BLENDMODE_STANDARD = 1;
  51755. return ParticleSystem;
  51756. }());
  51757. BABYLON.ParticleSystem = ParticleSystem;
  51758. })(BABYLON || (BABYLON = {}));
  51759. //# sourceMappingURL=babylon.particleSystem.js.map
  51760. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51761. var BABYLON;
  51762. (function (BABYLON) {
  51763. /**
  51764. * Particle emitter emitting particles from the inside of a box.
  51765. * It emits the particles randomly between 2 given directions.
  51766. */
  51767. var BoxParticleEmitter = /** @class */ (function () {
  51768. /**
  51769. * Creates a new instance of @see BoxParticleEmitter
  51770. */
  51771. function BoxParticleEmitter() {
  51772. /**
  51773. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51774. */
  51775. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51776. /**
  51777. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51778. */
  51779. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51780. /**
  51781. * 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.
  51782. */
  51783. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51784. /**
  51785. * 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.
  51786. */
  51787. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51788. }
  51789. /**
  51790. * Called by the particle System when the direction is computed for the created particle.
  51791. * @param emitPower is the power of the particle (speed)
  51792. * @param worldMatrix is the world matrix of the particle system
  51793. * @param directionToUpdate is the direction vector to update with the result
  51794. * @param particle is the particle we are computed the direction for
  51795. */
  51796. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51797. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51798. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51799. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51800. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51801. };
  51802. /**
  51803. * Called by the particle System when the position is computed for the created particle.
  51804. * @param worldMatrix is the world matrix of the particle system
  51805. * @param positionToUpdate is the position vector to update with the result
  51806. * @param particle is the particle we are computed the position for
  51807. */
  51808. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51809. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51810. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51811. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51812. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51813. };
  51814. /**
  51815. * Clones the current emitter and returns a copy of it
  51816. * @returns the new emitter
  51817. */
  51818. BoxParticleEmitter.prototype.clone = function () {
  51819. var newOne = new BoxParticleEmitter();
  51820. BABYLON.Tools.DeepCopy(this, newOne);
  51821. return newOne;
  51822. };
  51823. /**
  51824. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51825. * @param effect defines the update shader
  51826. */
  51827. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51828. effect.setVector3("direction1", this.direction1);
  51829. effect.setVector3("direction2", this.direction2);
  51830. effect.setVector3("minEmitBox", this.minEmitBox);
  51831. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51832. };
  51833. /**
  51834. * Returns a string to use to update the GPU particles update shader
  51835. * @returns a string containng the defines string
  51836. */
  51837. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51838. return "#define BOXEMITTER";
  51839. };
  51840. /**
  51841. * Returns the string "BoxEmitter"
  51842. * @returns a string containing the class name
  51843. */
  51844. BoxParticleEmitter.prototype.getClassName = function () {
  51845. return "BoxEmitter";
  51846. };
  51847. /**
  51848. * Serializes the particle system to a JSON object.
  51849. * @returns the JSON object
  51850. */
  51851. BoxParticleEmitter.prototype.serialize = function () {
  51852. var serializationObject = {};
  51853. serializationObject.type = this.getClassName();
  51854. serializationObject.direction1 = this.direction1.asArray();
  51855. ;
  51856. serializationObject.direction2 = this.direction2.asArray();
  51857. ;
  51858. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51859. ;
  51860. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51861. ;
  51862. return serializationObject;
  51863. };
  51864. /**
  51865. * Parse properties from a JSON object
  51866. * @param serializationObject defines the JSON object
  51867. */
  51868. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51869. this.direction1.copyFrom(serializationObject.direction1);
  51870. this.direction2.copyFrom(serializationObject.direction2);
  51871. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51872. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51873. };
  51874. return BoxParticleEmitter;
  51875. }());
  51876. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51877. })(BABYLON || (BABYLON = {}));
  51878. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51879. var BABYLON;
  51880. (function (BABYLON) {
  51881. /**
  51882. * Particle emitter emitting particles from the inside of a cone.
  51883. * It emits the particles alongside the cone volume from the base to the particle.
  51884. * The emission direction might be randomized.
  51885. */
  51886. var ConeParticleEmitter = /** @class */ (function () {
  51887. /**
  51888. * Creates a new instance of @see ConeParticleEmitter
  51889. * @param radius the radius of the emission cone (1 by default)
  51890. * @param angles the cone base angle (PI by default)
  51891. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51892. */
  51893. function ConeParticleEmitter(radius,
  51894. /**
  51895. * The radius of the emission cone.
  51896. */
  51897. angle,
  51898. /**
  51899. * The cone base angle.
  51900. */
  51901. directionRandomizer) {
  51902. if (radius === void 0) { radius = 1; }
  51903. if (angle === void 0) { angle = Math.PI; }
  51904. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51905. this.angle = angle;
  51906. this.directionRandomizer = directionRandomizer;
  51907. this.radius = radius;
  51908. }
  51909. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51910. /**
  51911. * Gets the radius of the emission cone.
  51912. */
  51913. get: function () {
  51914. return this._radius;
  51915. },
  51916. /**
  51917. * Sets the radius of the emission cone.
  51918. */
  51919. set: function (value) {
  51920. this._radius = value;
  51921. if (this.angle !== 0) {
  51922. this._height = value / Math.tan(this.angle / 2);
  51923. }
  51924. else {
  51925. this._height = 1;
  51926. }
  51927. },
  51928. enumerable: true,
  51929. configurable: true
  51930. });
  51931. /**
  51932. * Called by the particle System when the direction is computed for the created particle.
  51933. * @param emitPower is the power of the particle (speed)
  51934. * @param worldMatrix is the world matrix of the particle system
  51935. * @param directionToUpdate is the direction vector to update with the result
  51936. * @param particle is the particle we are computed the direction for
  51937. */
  51938. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51939. if (this.angle === 0) {
  51940. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51941. }
  51942. else {
  51943. // measure the direction Vector from the emitter to the particle.
  51944. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51945. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51946. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51947. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51948. direction.x += randX;
  51949. direction.y += randY;
  51950. direction.z += randZ;
  51951. direction.normalize();
  51952. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51953. }
  51954. };
  51955. /**
  51956. * Called by the particle System when the position is computed for the created particle.
  51957. * @param worldMatrix is the world matrix of the particle system
  51958. * @param positionToUpdate is the position vector to update with the result
  51959. * @param particle is the particle we are computed the position for
  51960. */
  51961. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51962. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51963. var h = BABYLON.Scalar.RandomRange(0, 1);
  51964. // Better distribution in a cone at normal angles.
  51965. h = 1 - h * h;
  51966. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51967. radius = radius * h / this._height;
  51968. var randX = radius * Math.sin(s);
  51969. var randZ = radius * Math.cos(s);
  51970. var randY = h * this._height;
  51971. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51972. };
  51973. /**
  51974. * Clones the current emitter and returns a copy of it
  51975. * @returns the new emitter
  51976. */
  51977. ConeParticleEmitter.prototype.clone = function () {
  51978. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51979. BABYLON.Tools.DeepCopy(this, newOne);
  51980. return newOne;
  51981. };
  51982. /**
  51983. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51984. * @param effect defines the update shader
  51985. */
  51986. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51987. effect.setFloat("radius", this.radius);
  51988. effect.setFloat("angle", this.angle);
  51989. effect.setFloat("height", this._height);
  51990. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51991. };
  51992. /**
  51993. * Returns a string to use to update the GPU particles update shader
  51994. * @returns a string containng the defines string
  51995. */
  51996. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51997. return "#define CONEEMITTER";
  51998. };
  51999. /**
  52000. * Returns the string "BoxEmitter"
  52001. * @returns a string containing the class name
  52002. */
  52003. ConeParticleEmitter.prototype.getClassName = function () {
  52004. return "ConeEmitter";
  52005. };
  52006. /**
  52007. * Serializes the particle system to a JSON object.
  52008. * @returns the JSON object
  52009. */
  52010. ConeParticleEmitter.prototype.serialize = function () {
  52011. var serializationObject = {};
  52012. serializationObject.type = this.getClassName();
  52013. serializationObject.radius = this.radius;
  52014. serializationObject.angle = this.angle;
  52015. serializationObject.directionRandomizer = this.directionRandomizer;
  52016. return serializationObject;
  52017. };
  52018. /**
  52019. * Parse properties from a JSON object
  52020. * @param serializationObject defines the JSON object
  52021. */
  52022. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52023. this.radius = serializationObject.radius;
  52024. this.angle = serializationObject.angle;
  52025. this.directionRandomizer = serializationObject.directionRandomizer;
  52026. };
  52027. return ConeParticleEmitter;
  52028. }());
  52029. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52030. })(BABYLON || (BABYLON = {}));
  52031. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52032. var BABYLON;
  52033. (function (BABYLON) {
  52034. /**
  52035. * Particle emitter emitting particles from the inside of a sphere.
  52036. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52037. */
  52038. var SphereParticleEmitter = /** @class */ (function () {
  52039. /**
  52040. * Creates a new instance of @see SphereParticleEmitter
  52041. * @param radius the radius of the emission sphere (1 by default)
  52042. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52043. */
  52044. function SphereParticleEmitter(
  52045. /**
  52046. * The radius of the emission sphere.
  52047. */
  52048. radius,
  52049. /**
  52050. * How much to randomize the particle direction [0-1].
  52051. */
  52052. directionRandomizer) {
  52053. if (radius === void 0) { radius = 1; }
  52054. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52055. this.radius = radius;
  52056. this.directionRandomizer = directionRandomizer;
  52057. }
  52058. /**
  52059. * Called by the particle System when the direction is computed for the created particle.
  52060. * @param emitPower is the power of the particle (speed)
  52061. * @param worldMatrix is the world matrix of the particle system
  52062. * @param directionToUpdate is the direction vector to update with the result
  52063. * @param particle is the particle we are computed the direction for
  52064. */
  52065. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52066. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52067. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52068. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52069. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52070. direction.x += randX;
  52071. direction.y += randY;
  52072. direction.z += randZ;
  52073. direction.normalize();
  52074. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52075. };
  52076. /**
  52077. * Called by the particle System when the position is computed for the created particle.
  52078. * @param worldMatrix is the world matrix of the particle system
  52079. * @param positionToUpdate is the position vector to update with the result
  52080. * @param particle is the particle we are computed the position for
  52081. */
  52082. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52083. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52084. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52085. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52086. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52087. var randY = randRadius * Math.cos(theta);
  52088. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52090. };
  52091. /**
  52092. * Clones the current emitter and returns a copy of it
  52093. * @returns the new emitter
  52094. */
  52095. SphereParticleEmitter.prototype.clone = function () {
  52096. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52097. BABYLON.Tools.DeepCopy(this, newOne);
  52098. return newOne;
  52099. };
  52100. /**
  52101. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52102. * @param effect defines the update shader
  52103. */
  52104. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52105. effect.setFloat("radius", this.radius);
  52106. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52107. };
  52108. /**
  52109. * Returns a string to use to update the GPU particles update shader
  52110. * @returns a string containng the defines string
  52111. */
  52112. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52113. return "#define SPHEREEMITTER";
  52114. };
  52115. /**
  52116. * Returns the string "SphereParticleEmitter"
  52117. * @returns a string containing the class name
  52118. */
  52119. SphereParticleEmitter.prototype.getClassName = function () {
  52120. return "SphereParticleEmitter";
  52121. };
  52122. /**
  52123. * Serializes the particle system to a JSON object.
  52124. * @returns the JSON object
  52125. */
  52126. SphereParticleEmitter.prototype.serialize = function () {
  52127. var serializationObject = {};
  52128. serializationObject.type = this.getClassName();
  52129. serializationObject.radius = this.radius;
  52130. serializationObject.directionRandomizer = this.directionRandomizer;
  52131. return serializationObject;
  52132. };
  52133. /**
  52134. * Parse properties from a JSON object
  52135. * @param serializationObject defines the JSON object
  52136. */
  52137. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52138. this.radius = serializationObject.radius;
  52139. this.directionRandomizer = serializationObject.directionRandomizer;
  52140. };
  52141. return SphereParticleEmitter;
  52142. }());
  52143. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52144. /**
  52145. * Particle emitter emitting particles from the inside of a sphere.
  52146. * It emits the particles randomly between two vectors.
  52147. */
  52148. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52149. __extends(SphereDirectedParticleEmitter, _super);
  52150. /**
  52151. * Creates a new instance of @see SphereDirectedParticleEmitter
  52152. * @param radius the radius of the emission sphere (1 by default)
  52153. * @param direction1 the min limit of the emission direction (up vector by default)
  52154. * @param direction2 the max limit of the emission direction (up vector by default)
  52155. */
  52156. function SphereDirectedParticleEmitter(radius,
  52157. /**
  52158. * The min limit of the emission direction.
  52159. */
  52160. direction1,
  52161. /**
  52162. * The max limit of the emission direction.
  52163. */
  52164. direction2) {
  52165. if (radius === void 0) { radius = 1; }
  52166. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52167. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52168. var _this = _super.call(this, radius) || this;
  52169. _this.direction1 = direction1;
  52170. _this.direction2 = direction2;
  52171. return _this;
  52172. }
  52173. /**
  52174. * Called by the particle System when the direction is computed for the created particle.
  52175. * @param emitPower is the power of the particle (speed)
  52176. * @param worldMatrix is the world matrix of the particle system
  52177. * @param directionToUpdate is the direction vector to update with the result
  52178. * @param particle is the particle we are computed the direction for
  52179. */
  52180. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52181. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52182. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52183. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52184. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52185. };
  52186. /**
  52187. * Clones the current emitter and returns a copy of it
  52188. * @returns the new emitter
  52189. */
  52190. SphereDirectedParticleEmitter.prototype.clone = function () {
  52191. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52192. BABYLON.Tools.DeepCopy(this, newOne);
  52193. return newOne;
  52194. };
  52195. /**
  52196. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52197. * @param effect defines the update shader
  52198. */
  52199. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52200. effect.setFloat("radius", this.radius);
  52201. effect.setVector3("direction1", this.direction1);
  52202. effect.setVector3("direction2", this.direction2);
  52203. };
  52204. /**
  52205. * Returns a string to use to update the GPU particles update shader
  52206. * @returns a string containng the defines string
  52207. */
  52208. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52209. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52210. };
  52211. /**
  52212. * Returns the string "SphereDirectedParticleEmitter"
  52213. * @returns a string containing the class name
  52214. */
  52215. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52216. return "SphereDirectedParticleEmitter";
  52217. };
  52218. /**
  52219. * Serializes the particle system to a JSON object.
  52220. * @returns the JSON object
  52221. */
  52222. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52223. var serializationObject = _super.prototype.serialize.call(this);
  52224. ;
  52225. serializationObject.direction1 = this.direction1.asArray();
  52226. ;
  52227. serializationObject.direction2 = this.direction2.asArray();
  52228. ;
  52229. return serializationObject;
  52230. };
  52231. /**
  52232. * Parse properties from a JSON object
  52233. * @param serializationObject defines the JSON object
  52234. */
  52235. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52236. _super.prototype.parse.call(this, serializationObject);
  52237. this.direction1.copyFrom(serializationObject.direction1);
  52238. this.direction2.copyFrom(serializationObject.direction2);
  52239. };
  52240. return SphereDirectedParticleEmitter;
  52241. }(SphereParticleEmitter));
  52242. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52243. })(BABYLON || (BABYLON = {}));
  52244. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52245. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52246. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52247. s = arguments[i];
  52248. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52249. t[p] = s[p];
  52250. }
  52251. return t;
  52252. };
  52253. var BABYLON;
  52254. (function (BABYLON) {
  52255. /**
  52256. * This represents a GPU particle system in Babylon
  52257. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52258. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52259. */
  52260. var GPUParticleSystem = /** @class */ (function () {
  52261. /**
  52262. * Instantiates a GPU particle system.
  52263. * 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.
  52264. * @param name The name of the particle system
  52265. * @param capacity The max number of particles alive at the same time
  52266. * @param scene The scene the particle system belongs to
  52267. */
  52268. function GPUParticleSystem(name, options, scene) {
  52269. /**
  52270. * The emitter represents the Mesh or position we are attaching the particle system to.
  52271. */
  52272. this.emitter = null;
  52273. /**
  52274. * The rendering group used by the Particle system to chose when to render.
  52275. */
  52276. this.renderingGroupId = 0;
  52277. /**
  52278. * The layer mask we are rendering the particles through.
  52279. */
  52280. this.layerMask = 0x0FFFFFFF;
  52281. this._targetIndex = 0;
  52282. this._currentRenderId = -1;
  52283. this._started = false;
  52284. this._stopped = false;
  52285. this._timeDelta = 0;
  52286. this._attributesStrideSize = 14;
  52287. this._actualFrame = 0;
  52288. /**
  52289. * List of animations used by the particle system.
  52290. */
  52291. this.animations = [];
  52292. /**
  52293. * An event triggered when the system is disposed.
  52294. */
  52295. this.onDisposeObservable = new BABYLON.Observable();
  52296. /**
  52297. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52298. */
  52299. this.updateSpeed = 0.01;
  52300. /**
  52301. * The amount of time the particle system is running (depends of the overall update speed).
  52302. */
  52303. this.targetStopDuration = 0;
  52304. /**
  52305. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52306. */
  52307. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52308. /**
  52309. * Minimum life time of emitting particles.
  52310. */
  52311. this.minLifeTime = 1;
  52312. /**
  52313. * Maximum life time of emitting particles.
  52314. */
  52315. this.maxLifeTime = 1;
  52316. /**
  52317. * Minimum Size of emitting particles.
  52318. */
  52319. this.minSize = 1;
  52320. /**
  52321. * Maximum Size of emitting particles.
  52322. */
  52323. this.maxSize = 1;
  52324. /**
  52325. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52326. */
  52327. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52328. /**
  52329. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52330. */
  52331. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52332. /**
  52333. * Color the particle will have at the end of its lifetime.
  52334. */
  52335. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52336. /**
  52337. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52338. */
  52339. this.emitRate = 100;
  52340. /**
  52341. * You can use gravity if you want to give an orientation to your particles.
  52342. */
  52343. this.gravity = BABYLON.Vector3.Zero();
  52344. /**
  52345. * Minimum power of emitting particles.
  52346. */
  52347. this.minEmitPower = 1;
  52348. /**
  52349. * Maximum power of emitting particles.
  52350. */
  52351. this.maxEmitPower = 1;
  52352. /**
  52353. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52354. * to override the particles.
  52355. */
  52356. this.forceDepthWrite = false;
  52357. this.id = name;
  52358. this.name = name;
  52359. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52360. this._engine = this._scene.getEngine();
  52361. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52362. this._capacity = fullOptions.capacity;
  52363. this._activeCount = fullOptions.capacity;
  52364. this._currentActiveCount = 0;
  52365. this._scene.particleSystems.push(this);
  52366. this._updateEffectOptions = {
  52367. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52368. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52369. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52370. uniformBuffersNames: [],
  52371. samplers: ["randomSampler"],
  52372. defines: "",
  52373. fallbacks: null,
  52374. onCompiled: null,
  52375. onError: null,
  52376. indexParameters: null,
  52377. maxSimultaneousLights: 0,
  52378. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52379. };
  52380. // Random data
  52381. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52382. var d = [];
  52383. for (var i = 0; i < maxTextureSize; ++i) {
  52384. d.push(Math.random());
  52385. d.push(Math.random());
  52386. d.push(Math.random());
  52387. d.push(Math.random());
  52388. }
  52389. 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);
  52390. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52391. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52392. this._randomTextureSize = maxTextureSize;
  52393. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52394. }
  52395. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52396. /**
  52397. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52398. */
  52399. get: function () {
  52400. if (!BABYLON.Engine.LastCreatedEngine) {
  52401. return false;
  52402. }
  52403. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52404. },
  52405. enumerable: true,
  52406. configurable: true
  52407. });
  52408. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52409. /**
  52410. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52411. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52412. */
  52413. get: function () {
  52414. if (this.particleEmitterType.direction1) {
  52415. return this.particleEmitterType.direction1;
  52416. }
  52417. return BABYLON.Vector3.Zero();
  52418. },
  52419. set: function (value) {
  52420. if (this.particleEmitterType.direction1) {
  52421. this.particleEmitterType.direction1 = value;
  52422. }
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52428. /**
  52429. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52430. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52431. */
  52432. get: function () {
  52433. if (this.particleEmitterType.direction2) {
  52434. return this.particleEmitterType.direction2;
  52435. }
  52436. return BABYLON.Vector3.Zero();
  52437. },
  52438. set: function (value) {
  52439. if (this.particleEmitterType.direction2) {
  52440. this.particleEmitterType.direction2 = value;
  52441. }
  52442. },
  52443. enumerable: true,
  52444. configurable: true
  52445. });
  52446. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52447. /**
  52448. * 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.
  52449. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52450. */
  52451. get: function () {
  52452. if (this.particleEmitterType.minEmitBox) {
  52453. return this.particleEmitterType.minEmitBox;
  52454. }
  52455. return BABYLON.Vector3.Zero();
  52456. },
  52457. set: function (value) {
  52458. if (this.particleEmitterType.minEmitBox) {
  52459. this.particleEmitterType.minEmitBox = value;
  52460. }
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52466. /**
  52467. * 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.
  52468. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52469. */
  52470. get: function () {
  52471. if (this.particleEmitterType.maxEmitBox) {
  52472. return this.particleEmitterType.maxEmitBox;
  52473. }
  52474. return BABYLON.Vector3.Zero();
  52475. },
  52476. set: function (value) {
  52477. if (this.particleEmitterType.maxEmitBox) {
  52478. this.particleEmitterType.maxEmitBox = value;
  52479. }
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. /**
  52485. * Gets the maximum number of particles active at the same time.
  52486. * @returns The max number of active particles.
  52487. */
  52488. GPUParticleSystem.prototype.getCapacity = function () {
  52489. return this._capacity;
  52490. };
  52491. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52492. /**
  52493. * Gets or set the number of active particles
  52494. */
  52495. get: function () {
  52496. return this._activeCount;
  52497. },
  52498. set: function (value) {
  52499. this._activeCount = Math.min(value, this._capacity);
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. /**
  52505. * Gets Wether the system has been started.
  52506. * @returns True if it has been started, otherwise false.
  52507. */
  52508. GPUParticleSystem.prototype.isStarted = function () {
  52509. return this._started;
  52510. };
  52511. /**
  52512. * Starts the particle system and begins to emit.
  52513. */
  52514. GPUParticleSystem.prototype.start = function () {
  52515. this._started = true;
  52516. this._stopped = false;
  52517. };
  52518. /**
  52519. * Stops the particle system.
  52520. */
  52521. GPUParticleSystem.prototype.stop = function () {
  52522. this._stopped = true;
  52523. };
  52524. /**
  52525. * Remove all active particles
  52526. */
  52527. GPUParticleSystem.prototype.reset = function () {
  52528. this._releaseBuffers();
  52529. this._releaseVAOs();
  52530. this._currentActiveCount = 0;
  52531. this._targetIndex = 0;
  52532. };
  52533. /**
  52534. * Returns the string "GPUParticleSystem"
  52535. * @returns a string containing the class name
  52536. */
  52537. GPUParticleSystem.prototype.getClassName = function () {
  52538. return "GPUParticleSystem";
  52539. };
  52540. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52541. var updateVertexBuffers = {};
  52542. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52543. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52544. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52545. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52546. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52547. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52548. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52549. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52550. this._engine.bindArrayBuffer(null);
  52551. return vao;
  52552. };
  52553. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52554. var renderVertexBuffers = {};
  52555. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52556. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52557. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52558. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52559. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52560. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52561. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52562. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52563. this._engine.bindArrayBuffer(null);
  52564. return vao;
  52565. };
  52566. GPUParticleSystem.prototype._initialize = function (force) {
  52567. if (force === void 0) { force = false; }
  52568. if (this._buffer0 && !force) {
  52569. return;
  52570. }
  52571. var engine = this._scene.getEngine();
  52572. var data = new Array();
  52573. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52574. // position
  52575. data.push(0.0);
  52576. data.push(0.0);
  52577. data.push(0.0);
  52578. // Age and life
  52579. data.push(0.0); // create the particle as a dead one to create a new one at start
  52580. data.push(0.0);
  52581. // Seed
  52582. data.push(Math.random());
  52583. // Size
  52584. data.push(0.0);
  52585. // color
  52586. data.push(0.0);
  52587. data.push(0.0);
  52588. data.push(0.0);
  52589. data.push(0.0);
  52590. // direction
  52591. data.push(0.0);
  52592. data.push(0.0);
  52593. data.push(0.0);
  52594. }
  52595. // Sprite data
  52596. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52597. -0.5, 0.5, 0, 1,
  52598. -0.5, -0.5, 0, 0,
  52599. 0.5, -0.5, 1, 0]);
  52600. // Buffers
  52601. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52602. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52603. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52604. // Update VAO
  52605. this._updateVAO = [];
  52606. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52607. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52608. // Render VAO
  52609. this._renderVAO = [];
  52610. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52611. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52612. // Links
  52613. this._sourceBuffer = this._buffer0;
  52614. this._targetBuffer = this._buffer1;
  52615. };
  52616. /** @ignore */
  52617. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52618. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52619. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52620. return;
  52621. }
  52622. this._updateEffectOptions.defines = defines;
  52623. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52624. };
  52625. /** @ignore */
  52626. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52627. var defines = "";
  52628. if (this._scene.clipPlane) {
  52629. defines = "\n#define CLIPPLANE";
  52630. }
  52631. if (this._renderEffect && this._renderEffect.defines === defines) {
  52632. return;
  52633. }
  52634. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52635. };
  52636. /**
  52637. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52638. */
  52639. GPUParticleSystem.prototype.animate = function () {
  52640. if (!this._stopped) {
  52641. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52642. this._actualFrame += this._timeDelta;
  52643. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52644. this.stop();
  52645. }
  52646. };
  52647. /**
  52648. * Renders the particle system in its current state.
  52649. * @returns the current number of particles
  52650. */
  52651. GPUParticleSystem.prototype.render = function () {
  52652. if (!this._started) {
  52653. return 0;
  52654. }
  52655. this._recreateUpdateEffect();
  52656. this._recreateRenderEffect();
  52657. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52658. return 0;
  52659. }
  52660. if (this._currentRenderId === this._scene.getRenderId()) {
  52661. return 0;
  52662. }
  52663. this._currentRenderId = this._scene.getRenderId();
  52664. // Get everything ready to render
  52665. this._initialize();
  52666. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52667. // Enable update effect
  52668. this._engine.enableEffect(this._updateEffect);
  52669. this._engine.setState(false);
  52670. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52671. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52672. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52673. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52674. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52675. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52676. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52677. this._updateEffect.setDirectColor4("color1", this.color1);
  52678. this._updateEffect.setDirectColor4("color2", this.color2);
  52679. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52680. this._updateEffect.setVector3("gravity", this.gravity);
  52681. if (this.particleEmitterType) {
  52682. this.particleEmitterType.applyToShader(this._updateEffect);
  52683. }
  52684. var emitterWM;
  52685. if (this.emitter.position) {
  52686. var emitterMesh = this.emitter;
  52687. emitterWM = emitterMesh.getWorldMatrix();
  52688. }
  52689. else {
  52690. var emitterPosition = this.emitter;
  52691. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52692. }
  52693. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52694. // Bind source VAO
  52695. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52696. // Update
  52697. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52698. this._engine.setRasterizerState(false);
  52699. this._engine.beginTransformFeedback();
  52700. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52701. this._engine.endTransformFeedback();
  52702. this._engine.setRasterizerState(true);
  52703. this._engine.bindTransformFeedbackBuffer(null);
  52704. // Enable render effect
  52705. this._engine.enableEffect(this._renderEffect);
  52706. var viewMatrix = this._scene.getViewMatrix();
  52707. this._renderEffect.setMatrix("view", viewMatrix);
  52708. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52709. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52710. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52711. if (this._scene.clipPlane) {
  52712. var clipPlane = this._scene.clipPlane;
  52713. var invView = viewMatrix.clone();
  52714. invView.invert();
  52715. this._renderEffect.setMatrix("invView", invView);
  52716. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52717. }
  52718. // Draw order
  52719. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52720. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52721. }
  52722. else {
  52723. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52724. }
  52725. if (this.forceDepthWrite) {
  52726. this._engine.setDepthWrite(true);
  52727. }
  52728. // Bind source VAO
  52729. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52730. // Render
  52731. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52732. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52733. // Switch VAOs
  52734. this._targetIndex++;
  52735. if (this._targetIndex === 2) {
  52736. this._targetIndex = 0;
  52737. }
  52738. // Switch buffers
  52739. var tmpBuffer = this._sourceBuffer;
  52740. this._sourceBuffer = this._targetBuffer;
  52741. this._targetBuffer = tmpBuffer;
  52742. return this._currentActiveCount;
  52743. };
  52744. /**
  52745. * Rebuilds the particle system
  52746. */
  52747. GPUParticleSystem.prototype.rebuild = function () {
  52748. this._initialize(true);
  52749. };
  52750. GPUParticleSystem.prototype._releaseBuffers = function () {
  52751. if (this._buffer0) {
  52752. this._buffer0.dispose();
  52753. this._buffer0 = null;
  52754. }
  52755. if (this._buffer1) {
  52756. this._buffer1.dispose();
  52757. this._buffer1 = null;
  52758. }
  52759. if (this._spriteBuffer) {
  52760. this._spriteBuffer.dispose();
  52761. this._spriteBuffer = null;
  52762. }
  52763. };
  52764. GPUParticleSystem.prototype._releaseVAOs = function () {
  52765. if (!this._updateVAO) {
  52766. return;
  52767. }
  52768. for (var index = 0; index < this._updateVAO.length; index++) {
  52769. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52770. }
  52771. this._updateVAO = [];
  52772. for (var index = 0; index < this._renderVAO.length; index++) {
  52773. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52774. }
  52775. this._renderVAO = [];
  52776. };
  52777. /**
  52778. * Disposes the particle system and free the associated resources
  52779. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52780. */
  52781. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52782. if (disposeTexture === void 0) { disposeTexture = true; }
  52783. var index = this._scene.particleSystems.indexOf(this);
  52784. if (index > -1) {
  52785. this._scene.particleSystems.splice(index, 1);
  52786. }
  52787. this._releaseBuffers();
  52788. this._releaseVAOs();
  52789. if (this._randomTexture) {
  52790. this._randomTexture.dispose();
  52791. this._randomTexture = null;
  52792. }
  52793. if (disposeTexture && this.particleTexture) {
  52794. this.particleTexture.dispose();
  52795. this.particleTexture = null;
  52796. }
  52797. // Callback
  52798. this.onDisposeObservable.notifyObservers(this);
  52799. this.onDisposeObservable.clear();
  52800. };
  52801. /**
  52802. * Clones the particle system.
  52803. * @param name The name of the cloned object
  52804. * @param newEmitter The new emitter to use
  52805. * @returns the cloned particle system
  52806. */
  52807. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52808. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52809. BABYLON.Tools.DeepCopy(this, result);
  52810. if (newEmitter === undefined) {
  52811. newEmitter = this.emitter;
  52812. }
  52813. result.emitter = newEmitter;
  52814. if (this.particleTexture) {
  52815. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52816. }
  52817. return result;
  52818. };
  52819. /**
  52820. * Serializes the particle system to a JSON object.
  52821. * @returns the JSON object
  52822. */
  52823. GPUParticleSystem.prototype.serialize = function () {
  52824. var serializationObject = {};
  52825. serializationObject.name = this.name;
  52826. serializationObject.id = this.id;
  52827. // Emitter
  52828. if (this.emitter.position) {
  52829. var emitterMesh = this.emitter;
  52830. serializationObject.emitterId = emitterMesh.id;
  52831. }
  52832. else {
  52833. var emitterPosition = this.emitter;
  52834. serializationObject.emitter = emitterPosition.asArray();
  52835. }
  52836. serializationObject.capacity = this.getCapacity();
  52837. if (this.particleTexture) {
  52838. serializationObject.textureName = this.particleTexture.name;
  52839. }
  52840. // Animations
  52841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52842. // Particle system
  52843. serializationObject.activeParticleCount = this.activeParticleCount;
  52844. serializationObject.randomTextureSize = this._randomTextureSize;
  52845. serializationObject.minSize = this.minSize;
  52846. serializationObject.maxSize = this.maxSize;
  52847. serializationObject.minEmitPower = this.minEmitPower;
  52848. serializationObject.maxEmitPower = this.maxEmitPower;
  52849. serializationObject.minLifeTime = this.minLifeTime;
  52850. serializationObject.maxLifeTime = this.maxLifeTime;
  52851. serializationObject.emitRate = this.emitRate;
  52852. serializationObject.gravity = this.gravity.asArray();
  52853. serializationObject.color1 = this.color1.asArray();
  52854. serializationObject.color2 = this.color2.asArray();
  52855. serializationObject.colorDead = this.colorDead.asArray();
  52856. serializationObject.updateSpeed = this.updateSpeed;
  52857. serializationObject.targetStopDuration = this.targetStopDuration;
  52858. serializationObject.blendMode = this.blendMode;
  52859. // Emitter
  52860. if (this.particleEmitterType) {
  52861. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52862. }
  52863. return serializationObject;
  52864. };
  52865. /**
  52866. * Parses a JSON object to create a GPU particle system.
  52867. * @param parsedParticleSystem The JSON object to parse
  52868. * @param scene The scene to create the particle system in
  52869. * @param rootUrl The root url to use to load external dependencies like texture
  52870. * @returns the parsed GPU particle system
  52871. */
  52872. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52873. var name = parsedParticleSystem.name;
  52874. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52875. if (parsedParticleSystem.id) {
  52876. particleSystem.id = parsedParticleSystem.id;
  52877. }
  52878. // Texture
  52879. if (parsedParticleSystem.textureName) {
  52880. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52881. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52882. }
  52883. // Emitter
  52884. if (parsedParticleSystem.emitterId) {
  52885. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52886. }
  52887. else {
  52888. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52889. }
  52890. // Animations
  52891. if (parsedParticleSystem.animations) {
  52892. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52893. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52894. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52895. }
  52896. }
  52897. // Particle system
  52898. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52899. particleSystem.minSize = parsedParticleSystem.minSize;
  52900. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52901. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52902. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52903. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52904. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52905. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52906. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52907. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52908. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52909. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52910. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52911. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52912. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52913. // Emitter
  52914. if (parsedParticleSystem.particleEmitterType) {
  52915. var emitterType = void 0;
  52916. switch (parsedParticleSystem.particleEmitterType.type) {
  52917. case "SphereEmitter":
  52918. emitterType = new BABYLON.SphereParticleEmitter();
  52919. break;
  52920. case "SphereDirectedParticleEmitter":
  52921. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52922. break;
  52923. case "ConeEmitter":
  52924. emitterType = new BABYLON.ConeParticleEmitter();
  52925. break;
  52926. case "BoxEmitter":
  52927. default:
  52928. emitterType = new BABYLON.BoxParticleEmitter();
  52929. break;
  52930. }
  52931. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52932. particleSystem.particleEmitterType = emitterType;
  52933. }
  52934. return particleSystem;
  52935. };
  52936. return GPUParticleSystem;
  52937. }());
  52938. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52939. })(BABYLON || (BABYLON = {}));
  52940. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52941. var BABYLON;
  52942. (function (BABYLON) {
  52943. /**
  52944. * Represents one particle of a solid particle system.
  52945. * @see SolidParticleSystem
  52946. */
  52947. var SolidParticle = /** @class */ (function () {
  52948. /**
  52949. * Creates a Solid Particle object.
  52950. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52951. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52952. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52953. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52954. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52955. * @param shapeId (integer) is the model shape identifier in the SPS.
  52956. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52957. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52958. */
  52959. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52960. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52961. /**
  52962. * particle global index
  52963. */
  52964. this.idx = 0;
  52965. /**
  52966. * The color of the particle
  52967. */
  52968. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52969. /**
  52970. * The world space position of the particle.
  52971. */
  52972. this.position = BABYLON.Vector3.Zero();
  52973. /**
  52974. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52975. */
  52976. this.rotation = BABYLON.Vector3.Zero();
  52977. /**
  52978. * The scaling of the particle.
  52979. */
  52980. this.scaling = BABYLON.Vector3.One();
  52981. /**
  52982. * The uvs of the particle.
  52983. */
  52984. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52985. /**
  52986. * The current speed of the particle.
  52987. */
  52988. this.velocity = BABYLON.Vector3.Zero();
  52989. /**
  52990. * The pivot point in the particle local space.
  52991. */
  52992. this.pivot = BABYLON.Vector3.Zero();
  52993. /**
  52994. * Must the particle be translated from its pivot point in its local space ?
  52995. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52996. * Default : false
  52997. */
  52998. this.translateFromPivot = false;
  52999. /**
  53000. * Is the particle active or not ?
  53001. */
  53002. this.alive = true;
  53003. /**
  53004. * Is the particle visible or not ?
  53005. */
  53006. this.isVisible = true;
  53007. /**
  53008. * Index of this particle in the global "positions" array (Internal use)
  53009. */
  53010. this._pos = 0;
  53011. /**
  53012. * Index of this particle in the global "indices" array (Internal use)
  53013. */
  53014. this._ind = 0;
  53015. /**
  53016. * ModelShape id of this particle
  53017. */
  53018. this.shapeId = 0;
  53019. /**
  53020. * Index of the particle in its shape id (Internal use)
  53021. */
  53022. this.idxInShape = 0;
  53023. /**
  53024. * Still set as invisible in order to skip useless computations (Internal use)
  53025. */
  53026. this._stillInvisible = false;
  53027. /**
  53028. * Last computed particle rotation matrix
  53029. */
  53030. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53031. /**
  53032. * Parent particle Id, if any.
  53033. * Default null.
  53034. */
  53035. this.parentId = null;
  53036. /**
  53037. * Internal global position in the SPS.
  53038. */
  53039. this._globalPosition = BABYLON.Vector3.Zero();
  53040. this.idx = particleIndex;
  53041. this._pos = positionIndex;
  53042. this._ind = indiceIndex;
  53043. this._model = model;
  53044. this.shapeId = shapeId;
  53045. this.idxInShape = idxInShape;
  53046. this._sps = sps;
  53047. if (modelBoundingInfo) {
  53048. this._modelBoundingInfo = modelBoundingInfo;
  53049. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53050. }
  53051. }
  53052. Object.defineProperty(SolidParticle.prototype, "scale", {
  53053. /**
  53054. * Legacy support, changed scale to scaling
  53055. */
  53056. get: function () {
  53057. return this.scaling;
  53058. },
  53059. /**
  53060. * Legacy support, changed scale to scaling
  53061. */
  53062. set: function (scale) {
  53063. this.scaling = scale;
  53064. },
  53065. enumerable: true,
  53066. configurable: true
  53067. });
  53068. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53069. /**
  53070. * Legacy support, changed quaternion to rotationQuaternion
  53071. */
  53072. get: function () {
  53073. return this.rotationQuaternion;
  53074. },
  53075. /**
  53076. * Legacy support, changed quaternion to rotationQuaternion
  53077. */
  53078. set: function (q) {
  53079. this.rotationQuaternion = q;
  53080. },
  53081. enumerable: true,
  53082. configurable: true
  53083. });
  53084. /**
  53085. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53086. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53087. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53088. * @returns true if it intersects
  53089. */
  53090. SolidParticle.prototype.intersectsMesh = function (target) {
  53091. if (!this._boundingInfo || !target._boundingInfo) {
  53092. return false;
  53093. }
  53094. if (this._sps._bSphereOnly) {
  53095. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53096. }
  53097. return this._boundingInfo.intersects(target._boundingInfo, false);
  53098. };
  53099. return SolidParticle;
  53100. }());
  53101. BABYLON.SolidParticle = SolidParticle;
  53102. /**
  53103. * Represents the shape of the model used by one particle of a solid particle system.
  53104. * SPS internal tool, don't use it manually.
  53105. * @see SolidParticleSystem
  53106. */
  53107. var ModelShape = /** @class */ (function () {
  53108. /**
  53109. * 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.
  53110. * SPS internal tool, don't use it manually.
  53111. * @ignore
  53112. */
  53113. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53114. /**
  53115. * length of the shape in the model indices array (internal use)
  53116. */
  53117. this._indicesLength = 0;
  53118. this.shapeID = id;
  53119. this._shape = shape;
  53120. this._indicesLength = indicesLength;
  53121. this._shapeUV = shapeUV;
  53122. this._positionFunction = posFunction;
  53123. this._vertexFunction = vtxFunction;
  53124. }
  53125. return ModelShape;
  53126. }());
  53127. BABYLON.ModelShape = ModelShape;
  53128. /**
  53129. * Represents a Depth Sorted Particle in the solid particle system.
  53130. * @see SolidParticleSystem
  53131. */
  53132. var DepthSortedParticle = /** @class */ (function () {
  53133. function DepthSortedParticle() {
  53134. /**
  53135. * Index of the particle in the "indices" array
  53136. */
  53137. this.ind = 0;
  53138. /**
  53139. * Length of the particle shape in the "indices" array
  53140. */
  53141. this.indicesLength = 0;
  53142. /**
  53143. * Squared distance from the particle to the camera
  53144. */
  53145. this.sqDistance = 0.0;
  53146. }
  53147. return DepthSortedParticle;
  53148. }());
  53149. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53150. })(BABYLON || (BABYLON = {}));
  53151. //# sourceMappingURL=babylon.solidParticle.js.map
  53152. var BABYLON;
  53153. (function (BABYLON) {
  53154. /**
  53155. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53156. *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.
  53157. * The SPS is also a particle system. It provides some methods to manage the particles.
  53158. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53159. *
  53160. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53161. */
  53162. var SolidParticleSystem = /** @class */ (function () {
  53163. /**
  53164. * Creates a SPS (Solid Particle System) object.
  53165. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53166. * @param scene (Scene) is the scene in which the SPS is added.
  53167. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53168. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53169. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53170. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53171. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53172. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53173. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53174. */
  53175. function SolidParticleSystem(name, scene, options) {
  53176. /**
  53177. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53178. * Example : var p = SPS.particles[i];
  53179. */
  53180. this.particles = new Array();
  53181. /**
  53182. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53183. */
  53184. this.nbParticles = 0;
  53185. /**
  53186. * If the particles must ever face the camera (default false). Useful for planar particles.
  53187. */
  53188. this.billboard = false;
  53189. /**
  53190. * Recompute normals when adding a shape
  53191. */
  53192. this.recomputeNormals = true;
  53193. /**
  53194. * This a counter ofr your own usage. It's not set by any SPS functions.
  53195. */
  53196. this.counter = 0;
  53197. /**
  53198. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53199. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53200. */
  53201. this.vars = {};
  53202. /**
  53203. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53204. */
  53205. this._bSphereOnly = false;
  53206. /**
  53207. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53208. */
  53209. this._bSphereRadiusFactor = 1.0;
  53210. this._positions = new Array();
  53211. this._indices = new Array();
  53212. this._normals = new Array();
  53213. this._colors = new Array();
  53214. this._uvs = new Array();
  53215. this._index = 0; // indices index
  53216. this._updatable = true;
  53217. this._pickable = false;
  53218. this._isVisibilityBoxLocked = false;
  53219. this._alwaysVisible = false;
  53220. this._depthSort = false;
  53221. this._shapeCounter = 0;
  53222. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53223. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53224. this._computeParticleColor = true;
  53225. this._computeParticleTexture = true;
  53226. this._computeParticleRotation = true;
  53227. this._computeParticleVertex = false;
  53228. this._computeBoundingBox = false;
  53229. this._depthSortParticles = true;
  53230. this._cam_axisZ = BABYLON.Vector3.Zero();
  53231. this._cam_axisY = BABYLON.Vector3.Zero();
  53232. this._cam_axisX = BABYLON.Vector3.Zero();
  53233. this._axisZ = BABYLON.Axis.Z;
  53234. this._camDir = BABYLON.Vector3.Zero();
  53235. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53236. this._rotMatrix = new BABYLON.Matrix();
  53237. this._invertMatrix = new BABYLON.Matrix();
  53238. this._rotated = BABYLON.Vector3.Zero();
  53239. this._quaternion = new BABYLON.Quaternion();
  53240. this._vertex = BABYLON.Vector3.Zero();
  53241. this._normal = BABYLON.Vector3.Zero();
  53242. this._yaw = 0.0;
  53243. this._pitch = 0.0;
  53244. this._roll = 0.0;
  53245. this._halfroll = 0.0;
  53246. this._halfpitch = 0.0;
  53247. this._halfyaw = 0.0;
  53248. this._sinRoll = 0.0;
  53249. this._cosRoll = 0.0;
  53250. this._sinPitch = 0.0;
  53251. this._cosPitch = 0.0;
  53252. this._sinYaw = 0.0;
  53253. this._cosYaw = 0.0;
  53254. this._mustUnrotateFixedNormals = false;
  53255. this._minimum = BABYLON.Vector3.Zero();
  53256. this._maximum = BABYLON.Vector3.Zero();
  53257. this._minBbox = BABYLON.Vector3.Zero();
  53258. this._maxBbox = BABYLON.Vector3.Zero();
  53259. this._particlesIntersect = false;
  53260. this._depthSortFunction = function (p1, p2) {
  53261. return (p2.sqDistance - p1.sqDistance);
  53262. };
  53263. this._needs32Bits = false;
  53264. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53265. this._scaledPivot = BABYLON.Vector3.Zero();
  53266. this._particleHasParent = false;
  53267. this.name = name;
  53268. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53269. this._camera = scene.activeCamera;
  53270. this._pickable = options ? options.isPickable : false;
  53271. this._depthSort = options ? options.enableDepthSort : false;
  53272. this._particlesIntersect = options ? options.particleIntersection : false;
  53273. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53274. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53275. if (options && options.updatable) {
  53276. this._updatable = options.updatable;
  53277. }
  53278. else {
  53279. this._updatable = true;
  53280. }
  53281. if (this._pickable) {
  53282. this.pickedParticles = [];
  53283. }
  53284. if (this._depthSort) {
  53285. this.depthSortedParticles = [];
  53286. }
  53287. }
  53288. /**
  53289. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53290. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53291. * @returns the created mesh
  53292. */
  53293. SolidParticleSystem.prototype.buildMesh = function () {
  53294. if (this.nbParticles === 0) {
  53295. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53296. this.addShape(triangle, 1);
  53297. triangle.dispose();
  53298. }
  53299. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53300. this._positions32 = new Float32Array(this._positions);
  53301. this._uvs32 = new Float32Array(this._uvs);
  53302. this._colors32 = new Float32Array(this._colors);
  53303. if (this.recomputeNormals) {
  53304. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53305. }
  53306. this._normals32 = new Float32Array(this._normals);
  53307. this._fixedNormal32 = new Float32Array(this._normals);
  53308. if (this._mustUnrotateFixedNormals) {
  53309. this._unrotateFixedNormals();
  53310. }
  53311. var vertexData = new BABYLON.VertexData();
  53312. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53313. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53314. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53315. if (this._uvs32) {
  53316. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53317. ;
  53318. }
  53319. if (this._colors32) {
  53320. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53321. }
  53322. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53323. vertexData.applyToMesh(mesh, this._updatable);
  53324. this.mesh = mesh;
  53325. this.mesh.isPickable = this._pickable;
  53326. // free memory
  53327. if (!this._depthSort) {
  53328. this._indices = null;
  53329. }
  53330. this._positions = null;
  53331. this._normals = null;
  53332. this._uvs = null;
  53333. this._colors = null;
  53334. if (!this._updatable) {
  53335. this.particles.length = 0;
  53336. }
  53337. return mesh;
  53338. };
  53339. /**
  53340. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53341. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53342. * Thus the particles generated from `digest()` have their property `position` set yet.
  53343. * @param mesh ( Mesh ) is the mesh to be digested
  53344. * @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
  53345. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53346. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53347. * @returns the current SPS
  53348. */
  53349. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53350. var size = (options && options.facetNb) || 1;
  53351. var number = (options && options.number) || 0;
  53352. var delta = (options && options.delta) || 0;
  53353. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53354. var meshInd = mesh.getIndices();
  53355. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53356. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53357. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53358. var f = 0; // facet counter
  53359. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53360. // compute size from number
  53361. if (number) {
  53362. number = (number > totalFacets) ? totalFacets : number;
  53363. size = Math.round(totalFacets / number);
  53364. delta = 0;
  53365. }
  53366. else {
  53367. size = (size > totalFacets) ? totalFacets : size;
  53368. }
  53369. var facetPos = []; // submesh positions
  53370. var facetInd = []; // submesh indices
  53371. var facetUV = []; // submesh UV
  53372. var facetCol = []; // submesh colors
  53373. var barycenter = BABYLON.Vector3.Zero();
  53374. var sizeO = size;
  53375. while (f < totalFacets) {
  53376. size = sizeO + Math.floor((1 + delta) * Math.random());
  53377. if (f > totalFacets - size) {
  53378. size = totalFacets - f;
  53379. }
  53380. // reset temp arrays
  53381. facetPos.length = 0;
  53382. facetInd.length = 0;
  53383. facetUV.length = 0;
  53384. facetCol.length = 0;
  53385. // iterate over "size" facets
  53386. var fi = 0;
  53387. for (var j = f * 3; j < (f + size) * 3; j++) {
  53388. facetInd.push(fi);
  53389. var i = meshInd[j];
  53390. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53391. if (meshUV) {
  53392. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53393. }
  53394. if (meshCol) {
  53395. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53396. }
  53397. fi++;
  53398. }
  53399. // create a model shape for each single particle
  53400. var idx = this.nbParticles;
  53401. var shape = this._posToShape(facetPos);
  53402. var shapeUV = this._uvsToShapeUV(facetUV);
  53403. // compute the barycenter of the shape
  53404. var v;
  53405. for (v = 0; v < shape.length; v++) {
  53406. barycenter.addInPlace(shape[v]);
  53407. }
  53408. barycenter.scaleInPlace(1 / shape.length);
  53409. // shift the shape from its barycenter to the origin
  53410. for (v = 0; v < shape.length; v++) {
  53411. shape[v].subtractInPlace(barycenter);
  53412. }
  53413. var bInfo;
  53414. if (this._particlesIntersect) {
  53415. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53416. }
  53417. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53418. // add the particle in the SPS
  53419. var currentPos = this._positions.length;
  53420. var currentInd = this._indices.length;
  53421. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53422. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53423. // initialize the particle position
  53424. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53425. this._index += shape.length;
  53426. idx++;
  53427. this.nbParticles++;
  53428. this._shapeCounter++;
  53429. f += size;
  53430. }
  53431. return this;
  53432. };
  53433. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53434. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53435. var index = 0;
  53436. var idx = 0;
  53437. for (var p = 0; p < this.particles.length; p++) {
  53438. this._particle = this.particles[p];
  53439. this._shape = this._particle._model._shape;
  53440. if (this._particle.rotationQuaternion) {
  53441. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53442. }
  53443. else {
  53444. this._yaw = this._particle.rotation.y;
  53445. this._pitch = this._particle.rotation.x;
  53446. this._roll = this._particle.rotation.z;
  53447. this._quaternionRotationYPR();
  53448. }
  53449. this._quaternionToRotationMatrix();
  53450. this._rotMatrix.invertToRef(this._invertMatrix);
  53451. for (var pt = 0; pt < this._shape.length; pt++) {
  53452. idx = index + pt * 3;
  53453. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53454. this._fixedNormal32[idx] = this._normal.x;
  53455. this._fixedNormal32[idx + 1] = this._normal.y;
  53456. this._fixedNormal32[idx + 2] = this._normal.z;
  53457. }
  53458. index = idx + 3;
  53459. }
  53460. };
  53461. //reset copy
  53462. SolidParticleSystem.prototype._resetCopy = function () {
  53463. this._copy.position.x = 0;
  53464. this._copy.position.y = 0;
  53465. this._copy.position.z = 0;
  53466. this._copy.rotation.x = 0;
  53467. this._copy.rotation.y = 0;
  53468. this._copy.rotation.z = 0;
  53469. this._copy.rotationQuaternion = null;
  53470. this._copy.scaling.x = 1.0;
  53471. this._copy.scaling.y = 1.0;
  53472. this._copy.scaling.z = 1.0;
  53473. this._copy.uvs.x = 0;
  53474. this._copy.uvs.y = 0;
  53475. this._copy.uvs.z = 1.0;
  53476. this._copy.uvs.w = 1.0;
  53477. this._copy.color = null;
  53478. this._copy.translateFromPivot = false;
  53479. };
  53480. // _meshBuilder : inserts the shape model in the global SPS mesh
  53481. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53482. var i;
  53483. var u = 0;
  53484. var c = 0;
  53485. var n = 0;
  53486. this._resetCopy();
  53487. if (options && options.positionFunction) {
  53488. options.positionFunction(this._copy, idx, idxInShape);
  53489. this._mustUnrotateFixedNormals = true;
  53490. }
  53491. if (this._copy.rotationQuaternion) {
  53492. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53493. }
  53494. else {
  53495. this._yaw = this._copy.rotation.y;
  53496. this._pitch = this._copy.rotation.x;
  53497. this._roll = this._copy.rotation.z;
  53498. this._quaternionRotationYPR();
  53499. }
  53500. this._quaternionToRotationMatrix();
  53501. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53502. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53503. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53504. if (this._copy.translateFromPivot) {
  53505. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53506. }
  53507. else {
  53508. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53509. }
  53510. for (i = 0; i < shape.length; i++) {
  53511. this._vertex.x = shape[i].x;
  53512. this._vertex.y = shape[i].y;
  53513. this._vertex.z = shape[i].z;
  53514. if (options && options.vertexFunction) {
  53515. options.vertexFunction(this._copy, this._vertex, i);
  53516. }
  53517. this._vertex.x *= this._copy.scaling.x;
  53518. this._vertex.y *= this._copy.scaling.y;
  53519. this._vertex.z *= this._copy.scaling.z;
  53520. this._vertex.x -= this._scaledPivot.x;
  53521. this._vertex.y -= this._scaledPivot.y;
  53522. this._vertex.z -= this._scaledPivot.z;
  53523. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53524. this._rotated.addInPlace(this._pivotBackTranslation);
  53525. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53526. if (meshUV) {
  53527. 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);
  53528. u += 2;
  53529. }
  53530. if (this._copy.color) {
  53531. this._color = this._copy.color;
  53532. }
  53533. else if (meshCol && meshCol[c] !== undefined) {
  53534. this._color.r = meshCol[c];
  53535. this._color.g = meshCol[c + 1];
  53536. this._color.b = meshCol[c + 2];
  53537. this._color.a = meshCol[c + 3];
  53538. }
  53539. else {
  53540. this._color.r = 1.0;
  53541. this._color.g = 1.0;
  53542. this._color.b = 1.0;
  53543. this._color.a = 1.0;
  53544. }
  53545. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53546. c += 4;
  53547. if (!this.recomputeNormals && meshNor) {
  53548. this._normal.x = meshNor[n];
  53549. this._normal.y = meshNor[n + 1];
  53550. this._normal.z = meshNor[n + 2];
  53551. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53552. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53553. n += 3;
  53554. }
  53555. }
  53556. for (i = 0; i < meshInd.length; i++) {
  53557. var current_ind = p + meshInd[i];
  53558. indices.push(current_ind);
  53559. if (current_ind > 65535) {
  53560. this._needs32Bits = true;
  53561. }
  53562. }
  53563. if (this._pickable) {
  53564. var nbfaces = meshInd.length / 3;
  53565. for (i = 0; i < nbfaces; i++) {
  53566. this.pickedParticles.push({ idx: idx, faceId: i });
  53567. }
  53568. }
  53569. if (this._depthSort) {
  53570. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53571. }
  53572. return this._copy;
  53573. };
  53574. // returns a shape array from positions array
  53575. SolidParticleSystem.prototype._posToShape = function (positions) {
  53576. var shape = [];
  53577. for (var i = 0; i < positions.length; i += 3) {
  53578. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53579. }
  53580. return shape;
  53581. };
  53582. // returns a shapeUV array from a Vector4 uvs
  53583. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53584. var shapeUV = [];
  53585. if (uvs) {
  53586. for (var i = 0; i < uvs.length; i++)
  53587. shapeUV.push(uvs[i]);
  53588. }
  53589. return shapeUV;
  53590. };
  53591. // adds a new particle object in the particles array
  53592. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53593. if (bInfo === void 0) { bInfo = null; }
  53594. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53595. this.particles.push(sp);
  53596. return sp;
  53597. };
  53598. /**
  53599. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53600. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53601. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53602. * @param nb (positive integer) the number of particles to be created from this model
  53603. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53604. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53605. * @returns the number of shapes in the system
  53606. */
  53607. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53608. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53609. var meshInd = mesh.getIndices();
  53610. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53611. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53612. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53613. var bbInfo;
  53614. if (this._particlesIntersect) {
  53615. bbInfo = mesh.getBoundingInfo();
  53616. }
  53617. var shape = this._posToShape(meshPos);
  53618. var shapeUV = this._uvsToShapeUV(meshUV);
  53619. var posfunc = options ? options.positionFunction : null;
  53620. var vtxfunc = options ? options.vertexFunction : null;
  53621. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53622. // particles
  53623. var sp;
  53624. var currentCopy;
  53625. var idx = this.nbParticles;
  53626. for (var i = 0; i < nb; i++) {
  53627. var currentPos = this._positions.length;
  53628. var currentInd = this._indices.length;
  53629. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53630. if (this._updatable) {
  53631. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53632. sp.position.copyFrom(currentCopy.position);
  53633. sp.rotation.copyFrom(currentCopy.rotation);
  53634. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53635. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53636. }
  53637. if (currentCopy.color && sp.color) {
  53638. sp.color.copyFrom(currentCopy.color);
  53639. }
  53640. sp.scaling.copyFrom(currentCopy.scaling);
  53641. sp.uvs.copyFrom(currentCopy.uvs);
  53642. }
  53643. this._index += shape.length;
  53644. idx++;
  53645. }
  53646. this.nbParticles += nb;
  53647. this._shapeCounter++;
  53648. return this._shapeCounter - 1;
  53649. };
  53650. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53651. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53652. this._resetCopy();
  53653. if (particle._model._positionFunction) {
  53654. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53655. }
  53656. if (this._copy.rotationQuaternion) {
  53657. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53658. }
  53659. else {
  53660. this._yaw = this._copy.rotation.y;
  53661. this._pitch = this._copy.rotation.x;
  53662. this._roll = this._copy.rotation.z;
  53663. this._quaternionRotationYPR();
  53664. }
  53665. this._quaternionToRotationMatrix();
  53666. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53667. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53668. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53669. if (this._copy.translateFromPivot) {
  53670. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53671. }
  53672. else {
  53673. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53674. }
  53675. this._shape = particle._model._shape;
  53676. for (var pt = 0; pt < this._shape.length; pt++) {
  53677. this._vertex.x = this._shape[pt].x;
  53678. this._vertex.y = this._shape[pt].y;
  53679. this._vertex.z = this._shape[pt].z;
  53680. if (particle._model._vertexFunction) {
  53681. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53682. }
  53683. this._vertex.x *= this._copy.scaling.x;
  53684. this._vertex.y *= this._copy.scaling.y;
  53685. this._vertex.z *= this._copy.scaling.z;
  53686. this._vertex.x -= this._scaledPivot.x;
  53687. this._vertex.y -= this._scaledPivot.y;
  53688. this._vertex.z -= this._scaledPivot.z;
  53689. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53690. this._rotated.addInPlace(this._pivotBackTranslation);
  53691. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53692. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53693. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53694. }
  53695. particle.position.x = 0.0;
  53696. particle.position.y = 0.0;
  53697. particle.position.z = 0.0;
  53698. particle.rotation.x = 0.0;
  53699. particle.rotation.y = 0.0;
  53700. particle.rotation.z = 0.0;
  53701. particle.rotationQuaternion = null;
  53702. particle.scaling.x = 1.0;
  53703. particle.scaling.y = 1.0;
  53704. particle.scaling.z = 1.0;
  53705. particle.uvs.x = 0.0;
  53706. particle.uvs.y = 0.0;
  53707. particle.uvs.z = 1.0;
  53708. particle.uvs.w = 1.0;
  53709. particle.pivot.x = 0.0;
  53710. particle.pivot.y = 0.0;
  53711. particle.pivot.z = 0.0;
  53712. particle.translateFromPivot = false;
  53713. particle.parentId = null;
  53714. };
  53715. /**
  53716. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53717. * @returns the SPS.
  53718. */
  53719. SolidParticleSystem.prototype.rebuildMesh = function () {
  53720. for (var p = 0; p < this.particles.length; p++) {
  53721. this._rebuildParticle(this.particles[p]);
  53722. }
  53723. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53724. return this;
  53725. };
  53726. /**
  53727. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53728. * This method calls `updateParticle()` for each particle of the SPS.
  53729. * For an animated SPS, it is usually called within the render loop.
  53730. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53731. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53732. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53733. * @returns the SPS.
  53734. */
  53735. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53736. if (start === void 0) { start = 0; }
  53737. if (end === void 0) { end = this.nbParticles - 1; }
  53738. if (update === void 0) { update = true; }
  53739. if (!this._updatable) {
  53740. return this;
  53741. }
  53742. // custom beforeUpdate
  53743. this.beforeUpdateParticles(start, end, update);
  53744. this._cam_axisX.x = 1.0;
  53745. this._cam_axisX.y = 0.0;
  53746. this._cam_axisX.z = 0.0;
  53747. this._cam_axisY.x = 0.0;
  53748. this._cam_axisY.y = 1.0;
  53749. this._cam_axisY.z = 0.0;
  53750. this._cam_axisZ.x = 0.0;
  53751. this._cam_axisZ.y = 0.0;
  53752. this._cam_axisZ.z = 1.0;
  53753. // cases when the World Matrix is to be computed first
  53754. if (this.billboard || this._depthSort) {
  53755. this.mesh.computeWorldMatrix(true);
  53756. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53757. }
  53758. // if the particles will always face the camera
  53759. if (this.billboard) {
  53760. // compute the camera position and un-rotate it by the current mesh rotation
  53761. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53762. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53763. this._cam_axisZ.normalize();
  53764. // same for camera up vector extracted from the cam view matrix
  53765. var view = this._camera.getViewMatrix(true);
  53766. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53767. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53768. this._cam_axisY.normalize();
  53769. this._cam_axisX.normalize();
  53770. }
  53771. // if depthSort, compute the camera global position in the mesh local system
  53772. if (this._depthSort) {
  53773. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53774. }
  53775. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53776. var idx = 0; // current position index in the global array positions32
  53777. var index = 0; // position start index in the global array positions32 of the current particle
  53778. var colidx = 0; // current color index in the global array colors32
  53779. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53780. var uvidx = 0; // current uv index in the global array uvs32
  53781. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53782. var pt = 0; // current index in the particle model shape
  53783. if (this.mesh.isFacetDataEnabled) {
  53784. this._computeBoundingBox = true;
  53785. }
  53786. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53787. if (this._computeBoundingBox) {
  53788. if (start == 0 && end == this.nbParticles - 1) {
  53789. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53790. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53791. }
  53792. else {
  53793. if (this.mesh._boundingInfo) {
  53794. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53795. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53796. }
  53797. }
  53798. }
  53799. // particle loop
  53800. index = this.particles[start]._pos;
  53801. var vpos = (index / 3) | 0;
  53802. colorIndex = vpos * 4;
  53803. uvIndex = vpos * 2;
  53804. for (var p = start; p <= end; p++) {
  53805. this._particle = this.particles[p];
  53806. this._shape = this._particle._model._shape;
  53807. this._shapeUV = this._particle._model._shapeUV;
  53808. // call to custom user function to update the particle properties
  53809. this.updateParticle(this._particle);
  53810. // camera-particle distance for depth sorting
  53811. if (this._depthSort && this._depthSortParticles) {
  53812. var dsp = this.depthSortedParticles[p];
  53813. dsp.ind = this._particle._ind;
  53814. dsp.indicesLength = this._particle._model._indicesLength;
  53815. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53816. }
  53817. // skip the computations for inactive or already invisible particles
  53818. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53819. // increment indexes for the next particle
  53820. pt = this._shape.length;
  53821. index += pt * 3;
  53822. colorIndex += pt * 4;
  53823. uvIndex += pt * 2;
  53824. continue;
  53825. }
  53826. if (this._particle.isVisible) {
  53827. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53828. this._particleHasParent = (this._particle.parentId !== null);
  53829. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53830. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53831. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53832. // particle rotation matrix
  53833. if (this.billboard) {
  53834. this._particle.rotation.x = 0.0;
  53835. this._particle.rotation.y = 0.0;
  53836. }
  53837. if (this._computeParticleRotation || this.billboard) {
  53838. if (this._particle.rotationQuaternion) {
  53839. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53840. }
  53841. else {
  53842. this._yaw = this._particle.rotation.y;
  53843. this._pitch = this._particle.rotation.x;
  53844. this._roll = this._particle.rotation.z;
  53845. this._quaternionRotationYPR();
  53846. }
  53847. this._quaternionToRotationMatrix();
  53848. }
  53849. if (this._particleHasParent) {
  53850. this._parent = this.particles[this._particle.parentId];
  53851. 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];
  53852. 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];
  53853. 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];
  53854. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53855. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53856. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53857. if (this._computeParticleRotation || this.billboard) {
  53858. 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];
  53859. 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];
  53860. 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];
  53861. 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];
  53862. 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];
  53863. 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];
  53864. 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];
  53865. 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];
  53866. 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];
  53867. }
  53868. }
  53869. else {
  53870. this._particle._globalPosition.x = this._particle.position.x;
  53871. this._particle._globalPosition.y = this._particle.position.y;
  53872. this._particle._globalPosition.z = this._particle.position.z;
  53873. if (this._computeParticleRotation || this.billboard) {
  53874. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53875. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53876. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53877. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53878. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53879. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53880. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53881. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53882. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53883. }
  53884. }
  53885. if (this._particle.translateFromPivot) {
  53886. this._pivotBackTranslation.x = 0.0;
  53887. this._pivotBackTranslation.y = 0.0;
  53888. this._pivotBackTranslation.z = 0.0;
  53889. }
  53890. else {
  53891. this._pivotBackTranslation.x = this._scaledPivot.x;
  53892. this._pivotBackTranslation.y = this._scaledPivot.y;
  53893. this._pivotBackTranslation.z = this._scaledPivot.z;
  53894. }
  53895. // particle vertex loop
  53896. for (pt = 0; pt < this._shape.length; pt++) {
  53897. idx = index + pt * 3;
  53898. colidx = colorIndex + pt * 4;
  53899. uvidx = uvIndex + pt * 2;
  53900. this._vertex.x = this._shape[pt].x;
  53901. this._vertex.y = this._shape[pt].y;
  53902. this._vertex.z = this._shape[pt].z;
  53903. if (this._computeParticleVertex) {
  53904. this.updateParticleVertex(this._particle, this._vertex, pt);
  53905. }
  53906. // positions
  53907. this._vertex.x *= this._particle.scaling.x;
  53908. this._vertex.y *= this._particle.scaling.y;
  53909. this._vertex.z *= this._particle.scaling.z;
  53910. this._vertex.x -= this._scaledPivot.x;
  53911. this._vertex.y -= this._scaledPivot.y;
  53912. this._vertex.z -= this._scaledPivot.z;
  53913. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53914. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53915. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53916. this._rotated.x += this._pivotBackTranslation.x;
  53917. this._rotated.y += this._pivotBackTranslation.y;
  53918. this._rotated.z += this._pivotBackTranslation.z;
  53919. 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;
  53920. 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;
  53921. 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;
  53922. if (this._computeBoundingBox) {
  53923. if (this._positions32[idx] < this._minimum.x) {
  53924. this._minimum.x = this._positions32[idx];
  53925. }
  53926. if (this._positions32[idx] > this._maximum.x) {
  53927. this._maximum.x = this._positions32[idx];
  53928. }
  53929. if (this._positions32[idx + 1] < this._minimum.y) {
  53930. this._minimum.y = this._positions32[idx + 1];
  53931. }
  53932. if (this._positions32[idx + 1] > this._maximum.y) {
  53933. this._maximum.y = this._positions32[idx + 1];
  53934. }
  53935. if (this._positions32[idx + 2] < this._minimum.z) {
  53936. this._minimum.z = this._positions32[idx + 2];
  53937. }
  53938. if (this._positions32[idx + 2] > this._maximum.z) {
  53939. this._maximum.z = this._positions32[idx + 2];
  53940. }
  53941. }
  53942. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53943. if (!this._computeParticleVertex) {
  53944. this._normal.x = this._fixedNormal32[idx];
  53945. this._normal.y = this._fixedNormal32[idx + 1];
  53946. this._normal.z = this._fixedNormal32[idx + 2];
  53947. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53948. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53949. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53950. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53951. 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;
  53952. 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;
  53953. }
  53954. if (this._computeParticleColor && this._particle.color) {
  53955. this._colors32[colidx] = this._particle.color.r;
  53956. this._colors32[colidx + 1] = this._particle.color.g;
  53957. this._colors32[colidx + 2] = this._particle.color.b;
  53958. this._colors32[colidx + 3] = this._particle.color.a;
  53959. }
  53960. if (this._computeParticleTexture) {
  53961. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53962. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53963. }
  53964. }
  53965. }
  53966. else {
  53967. this._particle._stillInvisible = true; // mark the particle as invisible
  53968. for (pt = 0; pt < this._shape.length; pt++) {
  53969. idx = index + pt * 3;
  53970. colidx = colorIndex + pt * 4;
  53971. uvidx = uvIndex + pt * 2;
  53972. this._positions32[idx] = 0.0;
  53973. this._positions32[idx + 1] = 0.0;
  53974. this._positions32[idx + 2] = 0.0;
  53975. this._normals32[idx] = 0.0;
  53976. this._normals32[idx + 1] = 0.0;
  53977. this._normals32[idx + 2] = 0.0;
  53978. if (this._computeParticleColor && this._particle.color) {
  53979. this._colors32[colidx] = this._particle.color.r;
  53980. this._colors32[colidx + 1] = this._particle.color.g;
  53981. this._colors32[colidx + 2] = this._particle.color.b;
  53982. this._colors32[colidx + 3] = this._particle.color.a;
  53983. }
  53984. if (this._computeParticleTexture) {
  53985. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53986. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53987. }
  53988. }
  53989. }
  53990. // if the particle intersections must be computed : update the bbInfo
  53991. if (this._particlesIntersect) {
  53992. var bInfo = this._particle._boundingInfo;
  53993. var bBox = bInfo.boundingBox;
  53994. var bSphere = bInfo.boundingSphere;
  53995. if (!this._bSphereOnly) {
  53996. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53997. for (var b = 0; b < bBox.vectors.length; b++) {
  53998. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53999. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54000. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54001. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54002. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54003. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54004. 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;
  54005. 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;
  54006. 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;
  54007. }
  54008. bBox._update(this.mesh._worldMatrix);
  54009. }
  54010. // place and scale the particle bouding sphere in the SPS local system, then update it
  54011. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54012. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54013. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54014. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54015. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54016. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54017. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54018. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54019. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54020. 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));
  54021. bSphere._update(this.mesh._worldMatrix);
  54022. }
  54023. // increment indexes for the next particle
  54024. index = idx + 3;
  54025. colorIndex = colidx + 4;
  54026. uvIndex = uvidx + 2;
  54027. }
  54028. // if the VBO must be updated
  54029. if (update) {
  54030. if (this._computeParticleColor) {
  54031. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54032. }
  54033. if (this._computeParticleTexture) {
  54034. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54035. }
  54036. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54037. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54038. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54039. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54040. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54041. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54042. for (var i = 0; i < this._normals32.length; i++) {
  54043. this._fixedNormal32[i] = this._normals32[i];
  54044. }
  54045. }
  54046. if (!this.mesh.areNormalsFrozen) {
  54047. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54048. }
  54049. }
  54050. if (this._depthSort && this._depthSortParticles) {
  54051. this.depthSortedParticles.sort(this._depthSortFunction);
  54052. var dspl = this.depthSortedParticles.length;
  54053. var sorted = 0;
  54054. var lind = 0;
  54055. var sind = 0;
  54056. var sid = 0;
  54057. for (sorted = 0; sorted < dspl; sorted++) {
  54058. lind = this.depthSortedParticles[sorted].indicesLength;
  54059. sind = this.depthSortedParticles[sorted].ind;
  54060. for (var i = 0; i < lind; i++) {
  54061. this._indices32[sid] = this._indices[sind + i];
  54062. sid++;
  54063. }
  54064. }
  54065. this.mesh.updateIndices(this._indices32);
  54066. }
  54067. }
  54068. if (this._computeBoundingBox) {
  54069. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54070. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54071. }
  54072. this.afterUpdateParticles(start, end, update);
  54073. return this;
  54074. };
  54075. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54076. this._halfroll = this._roll * 0.5;
  54077. this._halfpitch = this._pitch * 0.5;
  54078. this._halfyaw = this._yaw * 0.5;
  54079. this._sinRoll = Math.sin(this._halfroll);
  54080. this._cosRoll = Math.cos(this._halfroll);
  54081. this._sinPitch = Math.sin(this._halfpitch);
  54082. this._cosPitch = Math.cos(this._halfpitch);
  54083. this._sinYaw = Math.sin(this._halfyaw);
  54084. this._cosYaw = Math.cos(this._halfyaw);
  54085. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54086. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54087. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54088. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54089. };
  54090. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54091. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54092. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54093. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54094. this._rotMatrix.m[3] = 0;
  54095. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54096. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54097. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54098. this._rotMatrix.m[7] = 0;
  54099. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54100. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54101. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54102. this._rotMatrix.m[11] = 0;
  54103. this._rotMatrix.m[12] = 0;
  54104. this._rotMatrix.m[13] = 0;
  54105. this._rotMatrix.m[14] = 0;
  54106. this._rotMatrix.m[15] = 1.0;
  54107. };
  54108. /**
  54109. * Disposes the SPS.
  54110. */
  54111. SolidParticleSystem.prototype.dispose = function () {
  54112. this.mesh.dispose();
  54113. this.vars = null;
  54114. // drop references to internal big arrays for the GC
  54115. this._positions = null;
  54116. this._indices = null;
  54117. this._normals = null;
  54118. this._uvs = null;
  54119. this._colors = null;
  54120. this._indices32 = null;
  54121. this._positions32 = null;
  54122. this._normals32 = null;
  54123. this._fixedNormal32 = null;
  54124. this._uvs32 = null;
  54125. this._colors32 = null;
  54126. this.pickedParticles = null;
  54127. };
  54128. /**
  54129. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54130. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54131. * @returns the SPS.
  54132. */
  54133. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54134. if (!this._isVisibilityBoxLocked) {
  54135. this.mesh.refreshBoundingInfo();
  54136. }
  54137. return this;
  54138. };
  54139. /**
  54140. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54141. * @param size the size (float) of the visibility box
  54142. * note : this doesn't lock the SPS mesh bounding box.
  54143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54144. */
  54145. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54146. var vis = size / 2;
  54147. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54148. };
  54149. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54150. /**
  54151. * Gets whether the SPS as always visible or not
  54152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54153. */
  54154. get: function () {
  54155. return this._alwaysVisible;
  54156. },
  54157. /**
  54158. * Sets the SPS as always visible or not
  54159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54160. */
  54161. set: function (val) {
  54162. this._alwaysVisible = val;
  54163. this.mesh.alwaysSelectAsActiveMesh = val;
  54164. },
  54165. enumerable: true,
  54166. configurable: true
  54167. });
  54168. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54169. /**
  54170. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54171. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54172. */
  54173. get: function () {
  54174. return this._isVisibilityBoxLocked;
  54175. },
  54176. /**
  54177. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54178. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54179. */
  54180. set: function (val) {
  54181. this._isVisibilityBoxLocked = val;
  54182. var boundingInfo = this.mesh.getBoundingInfo();
  54183. boundingInfo.isLocked = val;
  54184. },
  54185. enumerable: true,
  54186. configurable: true
  54187. });
  54188. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54189. /**
  54190. * Gets if `setParticles()` computes the particle rotations or not.
  54191. * Default value : true. The SPS is faster when it's set to false.
  54192. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54193. */
  54194. get: function () {
  54195. return this._computeParticleRotation;
  54196. },
  54197. /**
  54198. * Tells to `setParticles()` to compute the particle rotations or not.
  54199. * Default value : true. The SPS is faster when it's set to false.
  54200. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54201. */
  54202. set: function (val) {
  54203. this._computeParticleRotation = val;
  54204. },
  54205. enumerable: true,
  54206. configurable: true
  54207. });
  54208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54209. /**
  54210. * Gets if `setParticles()` computes the particle colors or not.
  54211. * Default value : true. The SPS is faster when it's set to false.
  54212. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54213. */
  54214. get: function () {
  54215. return this._computeParticleColor;
  54216. },
  54217. /**
  54218. * Tells to `setParticles()` to compute the particle colors or not.
  54219. * Default value : true. The SPS is faster when it's set to false.
  54220. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54221. */
  54222. set: function (val) {
  54223. this._computeParticleColor = val;
  54224. },
  54225. enumerable: true,
  54226. configurable: true
  54227. });
  54228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54229. /**
  54230. * Gets if `setParticles()` computes the particle textures or not.
  54231. * Default value : true. The SPS is faster when it's set to false.
  54232. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54233. */
  54234. get: function () {
  54235. return this._computeParticleTexture;
  54236. },
  54237. set: function (val) {
  54238. this._computeParticleTexture = val;
  54239. },
  54240. enumerable: true,
  54241. configurable: true
  54242. });
  54243. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54244. /**
  54245. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54246. * Default value : false. The SPS is faster when it's set to false.
  54247. * Note : the particle custom vertex positions aren't stored values.
  54248. */
  54249. get: function () {
  54250. return this._computeParticleVertex;
  54251. },
  54252. /**
  54253. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54254. * Default value : false. The SPS is faster when it's set to false.
  54255. * Note : the particle custom vertex positions aren't stored values.
  54256. */
  54257. set: function (val) {
  54258. this._computeParticleVertex = val;
  54259. },
  54260. enumerable: true,
  54261. configurable: true
  54262. });
  54263. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54264. /**
  54265. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54266. */
  54267. get: function () {
  54268. return this._computeBoundingBox;
  54269. },
  54270. /**
  54271. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54272. */
  54273. set: function (val) {
  54274. this._computeBoundingBox = val;
  54275. },
  54276. enumerable: true,
  54277. configurable: true
  54278. });
  54279. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54280. /**
  54281. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54282. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54283. * Default : `true`
  54284. */
  54285. get: function () {
  54286. return this._depthSortParticles;
  54287. },
  54288. /**
  54289. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54290. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54291. * Default : `true`
  54292. */
  54293. set: function (val) {
  54294. this._depthSortParticles = val;
  54295. },
  54296. enumerable: true,
  54297. configurable: true
  54298. });
  54299. // =======================================================================
  54300. // Particle behavior logic
  54301. // these following methods may be overwritten by the user to fit his needs
  54302. /**
  54303. * This function does nothing. It may be overwritten to set all the particle first values.
  54304. * The SPS doesn't call this function, you may have to call it by your own.
  54305. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54306. */
  54307. SolidParticleSystem.prototype.initParticles = function () {
  54308. };
  54309. /**
  54310. * This function does nothing. It may be overwritten to recycle a particle.
  54311. * The SPS doesn't call this function, you may have to call it by your own.
  54312. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54313. * @param particle The particle to recycle
  54314. * @returns the recycled particle
  54315. */
  54316. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54317. return particle;
  54318. };
  54319. /**
  54320. * Updates a particle : this function should be overwritten by the user.
  54321. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54322. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54323. * @example : just set a particle position or velocity and recycle conditions
  54324. * @param particle The particle to update
  54325. * @returns the updated particle
  54326. */
  54327. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54328. return particle;
  54329. };
  54330. /**
  54331. * Updates a vertex of a particle : it can be overwritten by the user.
  54332. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54333. * @param particle the current particle
  54334. * @param vertex the current index of the current particle
  54335. * @param pt the index of the current vertex in the particle shape
  54336. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54337. * @example : just set a vertex particle position
  54338. * @returns the updated vertex
  54339. */
  54340. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54341. return vertex;
  54342. };
  54343. /**
  54344. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54345. * This does nothing and may be overwritten by the user.
  54346. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54347. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54348. * @param update the boolean update value actually passed to setParticles()
  54349. */
  54350. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54351. };
  54352. /**
  54353. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54354. * This will be passed three parameters.
  54355. * This does nothing and may be overwritten by the user.
  54356. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54357. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54358. * @param update the boolean update value actually passed to setParticles()
  54359. */
  54360. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54361. };
  54362. return SolidParticleSystem;
  54363. }());
  54364. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54365. })(BABYLON || (BABYLON = {}));
  54366. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54367. var BABYLON;
  54368. (function (BABYLON) {
  54369. var ShaderMaterial = /** @class */ (function (_super) {
  54370. __extends(ShaderMaterial, _super);
  54371. function ShaderMaterial(name, scene, shaderPath, options) {
  54372. var _this = _super.call(this, name, scene) || this;
  54373. _this._textures = {};
  54374. _this._textureArrays = {};
  54375. _this._floats = {};
  54376. _this._ints = {};
  54377. _this._floatsArrays = {};
  54378. _this._colors3 = {};
  54379. _this._colors3Arrays = {};
  54380. _this._colors4 = {};
  54381. _this._vectors2 = {};
  54382. _this._vectors3 = {};
  54383. _this._vectors4 = {};
  54384. _this._matrices = {};
  54385. _this._matrices3x3 = {};
  54386. _this._matrices2x2 = {};
  54387. _this._vectors2Arrays = {};
  54388. _this._vectors3Arrays = {};
  54389. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54390. _this._shaderPath = shaderPath;
  54391. options.needAlphaBlending = options.needAlphaBlending || false;
  54392. options.needAlphaTesting = options.needAlphaTesting || false;
  54393. options.attributes = options.attributes || ["position", "normal", "uv"];
  54394. options.uniforms = options.uniforms || ["worldViewProjection"];
  54395. options.uniformBuffers = options.uniformBuffers || [];
  54396. options.samplers = options.samplers || [];
  54397. options.defines = options.defines || [];
  54398. _this._options = options;
  54399. return _this;
  54400. }
  54401. ShaderMaterial.prototype.getClassName = function () {
  54402. return "ShaderMaterial";
  54403. };
  54404. ShaderMaterial.prototype.needAlphaBlending = function () {
  54405. return this._options.needAlphaBlending;
  54406. };
  54407. ShaderMaterial.prototype.needAlphaTesting = function () {
  54408. return this._options.needAlphaTesting;
  54409. };
  54410. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54411. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54412. this._options.uniforms.push(uniformName);
  54413. }
  54414. };
  54415. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54416. if (this._options.samplers.indexOf(name) === -1) {
  54417. this._options.samplers.push(name);
  54418. }
  54419. this._textures[name] = texture;
  54420. return this;
  54421. };
  54422. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54423. if (this._options.samplers.indexOf(name) === -1) {
  54424. this._options.samplers.push(name);
  54425. }
  54426. this._checkUniform(name);
  54427. this._textureArrays[name] = textures;
  54428. return this;
  54429. };
  54430. ShaderMaterial.prototype.setFloat = function (name, value) {
  54431. this._checkUniform(name);
  54432. this._floats[name] = value;
  54433. return this;
  54434. };
  54435. ShaderMaterial.prototype.setInt = function (name, value) {
  54436. this._checkUniform(name);
  54437. this._ints[name] = value;
  54438. return this;
  54439. };
  54440. ShaderMaterial.prototype.setFloats = function (name, value) {
  54441. this._checkUniform(name);
  54442. this._floatsArrays[name] = value;
  54443. return this;
  54444. };
  54445. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54446. this._checkUniform(name);
  54447. this._colors3[name] = value;
  54448. return this;
  54449. };
  54450. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54451. this._checkUniform(name);
  54452. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54453. color.toArray(arr, arr.length);
  54454. return arr;
  54455. }, []);
  54456. return this;
  54457. };
  54458. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54459. this._checkUniform(name);
  54460. this._colors4[name] = value;
  54461. return this;
  54462. };
  54463. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54464. this._checkUniform(name);
  54465. this._vectors2[name] = value;
  54466. return this;
  54467. };
  54468. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54469. this._checkUniform(name);
  54470. this._vectors3[name] = value;
  54471. return this;
  54472. };
  54473. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54474. this._checkUniform(name);
  54475. this._vectors4[name] = value;
  54476. return this;
  54477. };
  54478. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54479. this._checkUniform(name);
  54480. this._matrices[name] = value;
  54481. return this;
  54482. };
  54483. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54484. this._checkUniform(name);
  54485. this._matrices3x3[name] = value;
  54486. return this;
  54487. };
  54488. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54489. this._checkUniform(name);
  54490. this._matrices2x2[name] = value;
  54491. return this;
  54492. };
  54493. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54494. this._checkUniform(name);
  54495. this._vectors2Arrays[name] = value;
  54496. return this;
  54497. };
  54498. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54499. this._checkUniform(name);
  54500. this._vectors3Arrays[name] = value;
  54501. return this;
  54502. };
  54503. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54504. if (!mesh) {
  54505. return true;
  54506. }
  54507. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54508. return false;
  54509. }
  54510. return false;
  54511. };
  54512. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54513. var scene = this.getScene();
  54514. var engine = scene.getEngine();
  54515. if (!this.checkReadyOnEveryCall) {
  54516. if (this._renderId === scene.getRenderId()) {
  54517. if (this._checkCache(scene, mesh, useInstances)) {
  54518. return true;
  54519. }
  54520. }
  54521. }
  54522. // Instances
  54523. var defines = [];
  54524. var attribs = [];
  54525. var fallbacks = new BABYLON.EffectFallbacks();
  54526. if (useInstances) {
  54527. defines.push("#define INSTANCES");
  54528. }
  54529. for (var index = 0; index < this._options.defines.length; index++) {
  54530. defines.push(this._options.defines[index]);
  54531. }
  54532. for (var index = 0; index < this._options.attributes.length; index++) {
  54533. attribs.push(this._options.attributes[index]);
  54534. }
  54535. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54536. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54537. defines.push("#define VERTEXCOLOR");
  54538. }
  54539. // Bones
  54540. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54543. if (mesh.numBoneInfluencers > 4) {
  54544. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54545. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54546. }
  54547. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54548. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54549. fallbacks.addCPUSkinningFallback(0, mesh);
  54550. if (this._options.uniforms.indexOf("mBones") === -1) {
  54551. this._options.uniforms.push("mBones");
  54552. }
  54553. }
  54554. else {
  54555. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54556. }
  54557. // Textures
  54558. for (var name in this._textures) {
  54559. if (!this._textures[name].isReady()) {
  54560. return false;
  54561. }
  54562. }
  54563. // Alpha test
  54564. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54565. defines.push("#define ALPHATEST");
  54566. }
  54567. var previousEffect = this._effect;
  54568. var join = defines.join("\n");
  54569. this._effect = engine.createEffect(this._shaderPath, {
  54570. attributes: attribs,
  54571. uniformsNames: this._options.uniforms,
  54572. uniformBuffersNames: this._options.uniformBuffers,
  54573. samplers: this._options.samplers,
  54574. defines: join,
  54575. fallbacks: fallbacks,
  54576. onCompiled: this.onCompiled,
  54577. onError: this.onError
  54578. }, engine);
  54579. if (!this._effect.isReady()) {
  54580. return false;
  54581. }
  54582. if (previousEffect !== this._effect) {
  54583. scene.resetCachedMaterial();
  54584. }
  54585. this._renderId = scene.getRenderId();
  54586. return true;
  54587. };
  54588. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54589. var scene = this.getScene();
  54590. if (!this._effect) {
  54591. return;
  54592. }
  54593. if (this._options.uniforms.indexOf("world") !== -1) {
  54594. this._effect.setMatrix("world", world);
  54595. }
  54596. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54597. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54598. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54599. }
  54600. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54601. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54602. }
  54603. };
  54604. ShaderMaterial.prototype.bind = function (world, mesh) {
  54605. // Std values
  54606. this.bindOnlyWorldMatrix(world);
  54607. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54608. if (this._options.uniforms.indexOf("view") !== -1) {
  54609. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54610. }
  54611. if (this._options.uniforms.indexOf("projection") !== -1) {
  54612. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54613. }
  54614. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54615. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54616. }
  54617. // Bones
  54618. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54619. var name;
  54620. // Texture
  54621. for (name in this._textures) {
  54622. this._effect.setTexture(name, this._textures[name]);
  54623. }
  54624. // Texture arrays
  54625. for (name in this._textureArrays) {
  54626. this._effect.setTextureArray(name, this._textureArrays[name]);
  54627. }
  54628. // Int
  54629. for (name in this._ints) {
  54630. this._effect.setInt(name, this._ints[name]);
  54631. }
  54632. // Float
  54633. for (name in this._floats) {
  54634. this._effect.setFloat(name, this._floats[name]);
  54635. }
  54636. // Floats
  54637. for (name in this._floatsArrays) {
  54638. this._effect.setArray(name, this._floatsArrays[name]);
  54639. }
  54640. // Color3
  54641. for (name in this._colors3) {
  54642. this._effect.setColor3(name, this._colors3[name]);
  54643. }
  54644. for (name in this._colors3Arrays) {
  54645. this._effect.setArray3(name, this._colors3Arrays[name]);
  54646. }
  54647. // Color4
  54648. for (name in this._colors4) {
  54649. var color = this._colors4[name];
  54650. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54651. }
  54652. // Vector2
  54653. for (name in this._vectors2) {
  54654. this._effect.setVector2(name, this._vectors2[name]);
  54655. }
  54656. // Vector3
  54657. for (name in this._vectors3) {
  54658. this._effect.setVector3(name, this._vectors3[name]);
  54659. }
  54660. // Vector4
  54661. for (name in this._vectors4) {
  54662. this._effect.setVector4(name, this._vectors4[name]);
  54663. }
  54664. // Matrix
  54665. for (name in this._matrices) {
  54666. this._effect.setMatrix(name, this._matrices[name]);
  54667. }
  54668. // Matrix 3x3
  54669. for (name in this._matrices3x3) {
  54670. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54671. }
  54672. // Matrix 2x2
  54673. for (name in this._matrices2x2) {
  54674. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54675. }
  54676. // Vector2Array
  54677. for (name in this._vectors2Arrays) {
  54678. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54679. }
  54680. // Vector3Array
  54681. for (name in this._vectors3Arrays) {
  54682. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54683. }
  54684. }
  54685. this._afterBind(mesh);
  54686. };
  54687. ShaderMaterial.prototype.getActiveTextures = function () {
  54688. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54689. for (var name in this._textures) {
  54690. activeTextures.push(this._textures[name]);
  54691. }
  54692. for (var name in this._textureArrays) {
  54693. var array = this._textureArrays[name];
  54694. for (var index = 0; index < array.length; index++) {
  54695. activeTextures.push(array[index]);
  54696. }
  54697. }
  54698. return activeTextures;
  54699. };
  54700. ShaderMaterial.prototype.hasTexture = function (texture) {
  54701. if (_super.prototype.hasTexture.call(this, texture)) {
  54702. return true;
  54703. }
  54704. for (var name in this._textures) {
  54705. if (this._textures[name] === texture) {
  54706. return true;
  54707. }
  54708. }
  54709. for (var name in this._textureArrays) {
  54710. var array = this._textureArrays[name];
  54711. for (var index = 0; index < array.length; index++) {
  54712. if (array[index] === texture) {
  54713. return true;
  54714. }
  54715. }
  54716. }
  54717. return false;
  54718. };
  54719. ShaderMaterial.prototype.clone = function (name) {
  54720. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54721. return newShaderMaterial;
  54722. };
  54723. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54724. if (forceDisposeTextures) {
  54725. var name;
  54726. for (name in this._textures) {
  54727. this._textures[name].dispose();
  54728. }
  54729. for (name in this._textureArrays) {
  54730. var array = this._textureArrays[name];
  54731. for (var index = 0; index < array.length; index++) {
  54732. array[index].dispose();
  54733. }
  54734. }
  54735. }
  54736. this._textures = {};
  54737. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54738. };
  54739. ShaderMaterial.prototype.serialize = function () {
  54740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54741. serializationObject.customType = "BABYLON.ShaderMaterial";
  54742. serializationObject.options = this._options;
  54743. serializationObject.shaderPath = this._shaderPath;
  54744. var name;
  54745. // Texture
  54746. serializationObject.textures = {};
  54747. for (name in this._textures) {
  54748. serializationObject.textures[name] = this._textures[name].serialize();
  54749. }
  54750. // Texture arrays
  54751. serializationObject.textureArrays = {};
  54752. for (name in this._textureArrays) {
  54753. serializationObject.textureArrays[name] = [];
  54754. var array = this._textureArrays[name];
  54755. for (var index = 0; index < array.length; index++) {
  54756. serializationObject.textureArrays[name].push(array[index].serialize());
  54757. }
  54758. }
  54759. // Float
  54760. serializationObject.floats = {};
  54761. for (name in this._floats) {
  54762. serializationObject.floats[name] = this._floats[name];
  54763. }
  54764. // Float s
  54765. serializationObject.FloatArrays = {};
  54766. for (name in this._floatsArrays) {
  54767. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54768. }
  54769. // Color3
  54770. serializationObject.colors3 = {};
  54771. for (name in this._colors3) {
  54772. serializationObject.colors3[name] = this._colors3[name].asArray();
  54773. }
  54774. // Color3 array
  54775. serializationObject.colors3Arrays = {};
  54776. for (name in this._colors3Arrays) {
  54777. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54778. }
  54779. // Color4
  54780. serializationObject.colors4 = {};
  54781. for (name in this._colors4) {
  54782. serializationObject.colors4[name] = this._colors4[name].asArray();
  54783. }
  54784. // Vector2
  54785. serializationObject.vectors2 = {};
  54786. for (name in this._vectors2) {
  54787. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54788. }
  54789. // Vector3
  54790. serializationObject.vectors3 = {};
  54791. for (name in this._vectors3) {
  54792. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54793. }
  54794. // Vector4
  54795. serializationObject.vectors4 = {};
  54796. for (name in this._vectors4) {
  54797. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54798. }
  54799. // Matrix
  54800. serializationObject.matrices = {};
  54801. for (name in this._matrices) {
  54802. serializationObject.matrices[name] = this._matrices[name].asArray();
  54803. }
  54804. // Matrix 3x3
  54805. serializationObject.matrices3x3 = {};
  54806. for (name in this._matrices3x3) {
  54807. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54808. }
  54809. // Matrix 2x2
  54810. serializationObject.matrices2x2 = {};
  54811. for (name in this._matrices2x2) {
  54812. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54813. }
  54814. // Vector2Array
  54815. serializationObject.vectors2Arrays = {};
  54816. for (name in this._vectors2Arrays) {
  54817. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54818. }
  54819. // Vector3Array
  54820. serializationObject.vectors3Arrays = {};
  54821. for (name in this._vectors3Arrays) {
  54822. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54823. }
  54824. return serializationObject;
  54825. };
  54826. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54827. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54828. var name;
  54829. // Texture
  54830. for (name in source.textures) {
  54831. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54832. }
  54833. // Texture arrays
  54834. for (name in source.textureArrays) {
  54835. var array = source.textureArrays[name];
  54836. var textureArray = new Array();
  54837. for (var index = 0; index < array.length; index++) {
  54838. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54839. }
  54840. material.setTextureArray(name, textureArray);
  54841. }
  54842. // Float
  54843. for (name in source.floats) {
  54844. material.setFloat(name, source.floats[name]);
  54845. }
  54846. // Float s
  54847. for (name in source.floatsArrays) {
  54848. material.setFloats(name, source.floatsArrays[name]);
  54849. }
  54850. // Color3
  54851. for (name in source.colors3) {
  54852. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54853. }
  54854. // Color3 arrays
  54855. for (name in source.colors3Arrays) {
  54856. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54857. if (i % 3 === 0) {
  54858. arr.push([num]);
  54859. }
  54860. else {
  54861. arr[arr.length - 1].push(num);
  54862. }
  54863. return arr;
  54864. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54865. material.setColor3Array(name, colors);
  54866. }
  54867. // Color4
  54868. for (name in source.colors4) {
  54869. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54870. }
  54871. // Vector2
  54872. for (name in source.vectors2) {
  54873. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54874. }
  54875. // Vector3
  54876. for (name in source.vectors3) {
  54877. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54878. }
  54879. // Vector4
  54880. for (name in source.vectors4) {
  54881. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54882. }
  54883. // Matrix
  54884. for (name in source.matrices) {
  54885. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54886. }
  54887. // Matrix 3x3
  54888. for (name in source.matrices3x3) {
  54889. material.setMatrix3x3(name, source.matrices3x3[name]);
  54890. }
  54891. // Matrix 2x2
  54892. for (name in source.matrices2x2) {
  54893. material.setMatrix2x2(name, source.matrices2x2[name]);
  54894. }
  54895. // Vector2Array
  54896. for (name in source.vectors2Arrays) {
  54897. material.setArray2(name, source.vectors2Arrays[name]);
  54898. }
  54899. // Vector3Array
  54900. for (name in source.vectors3Arrays) {
  54901. material.setArray3(name, source.vectors3Arrays[name]);
  54902. }
  54903. return material;
  54904. };
  54905. return ShaderMaterial;
  54906. }(BABYLON.Material));
  54907. BABYLON.ShaderMaterial = ShaderMaterial;
  54908. })(BABYLON || (BABYLON = {}));
  54909. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54910. var BABYLON;
  54911. (function (BABYLON) {
  54912. var GroundMesh = /** @class */ (function (_super) {
  54913. __extends(GroundMesh, _super);
  54914. function GroundMesh(name, scene) {
  54915. var _this = _super.call(this, name, scene) || this;
  54916. _this.generateOctree = false;
  54917. return _this;
  54918. }
  54919. GroundMesh.prototype.getClassName = function () {
  54920. return "GroundMesh";
  54921. };
  54922. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54923. get: function () {
  54924. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54925. },
  54926. enumerable: true,
  54927. configurable: true
  54928. });
  54929. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54930. get: function () {
  54931. return this._subdivisionsX;
  54932. },
  54933. enumerable: true,
  54934. configurable: true
  54935. });
  54936. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54937. get: function () {
  54938. return this._subdivisionsY;
  54939. },
  54940. enumerable: true,
  54941. configurable: true
  54942. });
  54943. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54944. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54945. this._subdivisionsX = chunksCount;
  54946. this._subdivisionsY = chunksCount;
  54947. this.subdivide(chunksCount);
  54948. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54949. };
  54950. /**
  54951. * Returns a height (y) value in the Worl system :
  54952. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54953. * Returns the ground y position if (x, z) are outside the ground surface.
  54954. */
  54955. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54956. var world = this.getWorldMatrix();
  54957. var invMat = BABYLON.Tmp.Matrix[5];
  54958. world.invertToRef(invMat);
  54959. var tmpVect = BABYLON.Tmp.Vector3[8];
  54960. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54961. x = tmpVect.x;
  54962. z = tmpVect.z;
  54963. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54964. return this.position.y;
  54965. }
  54966. if (!this._heightQuads || this._heightQuads.length == 0) {
  54967. this._initHeightQuads();
  54968. this._computeHeightQuads();
  54969. }
  54970. var facet = this._getFacetAt(x, z);
  54971. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54972. // return y in the World system
  54973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54974. return tmpVect.y;
  54975. };
  54976. /**
  54977. * Returns a normalized vector (Vector3) orthogonal to the ground
  54978. * at the ground coordinates (x, z) expressed in the World system.
  54979. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54980. */
  54981. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54982. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54983. this.getNormalAtCoordinatesToRef(x, z, normal);
  54984. return normal;
  54985. };
  54986. /**
  54987. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54988. * at the ground coordinates (x, z) expressed in the World system.
  54989. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54990. * Returns the GroundMesh.
  54991. */
  54992. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54993. var world = this.getWorldMatrix();
  54994. var tmpMat = BABYLON.Tmp.Matrix[5];
  54995. world.invertToRef(tmpMat);
  54996. var tmpVect = BABYLON.Tmp.Vector3[8];
  54997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54998. x = tmpVect.x;
  54999. z = tmpVect.z;
  55000. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55001. return this;
  55002. }
  55003. if (!this._heightQuads || this._heightQuads.length == 0) {
  55004. this._initHeightQuads();
  55005. this._computeHeightQuads();
  55006. }
  55007. var facet = this._getFacetAt(x, z);
  55008. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55009. return this;
  55010. };
  55011. /**
  55012. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55013. * if the ground has been updated.
  55014. * This can be used in the render loop.
  55015. * Returns the GroundMesh.
  55016. */
  55017. GroundMesh.prototype.updateCoordinateHeights = function () {
  55018. if (!this._heightQuads || this._heightQuads.length == 0) {
  55019. this._initHeightQuads();
  55020. }
  55021. this._computeHeightQuads();
  55022. return this;
  55023. };
  55024. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55025. GroundMesh.prototype._getFacetAt = function (x, z) {
  55026. // retrieve col and row from x, z coordinates in the ground local system
  55027. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55028. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55029. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55030. var facet;
  55031. if (z < quad.slope.x * x + quad.slope.y) {
  55032. facet = quad.facet1;
  55033. }
  55034. else {
  55035. facet = quad.facet2;
  55036. }
  55037. return facet;
  55038. };
  55039. // Creates and populates the heightMap array with "facet" elements :
  55040. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55041. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55042. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55043. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55044. // Returns the GroundMesh.
  55045. GroundMesh.prototype._initHeightQuads = function () {
  55046. var subdivisionsX = this._subdivisionsX;
  55047. var subdivisionsY = this._subdivisionsY;
  55048. this._heightQuads = new Array();
  55049. for (var row = 0; row < subdivisionsY; row++) {
  55050. for (var col = 0; col < subdivisionsX; col++) {
  55051. 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) };
  55052. this._heightQuads[row * subdivisionsX + col] = quad;
  55053. }
  55054. }
  55055. return this;
  55056. };
  55057. // Compute each quad element values and update the the heightMap array :
  55058. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55059. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55060. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55061. // Returns the GroundMesh.
  55062. GroundMesh.prototype._computeHeightQuads = function () {
  55063. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55064. if (!positions) {
  55065. return this;
  55066. }
  55067. var v1 = BABYLON.Tmp.Vector3[3];
  55068. var v2 = BABYLON.Tmp.Vector3[2];
  55069. var v3 = BABYLON.Tmp.Vector3[1];
  55070. var v4 = BABYLON.Tmp.Vector3[0];
  55071. var v1v2 = BABYLON.Tmp.Vector3[4];
  55072. var v1v3 = BABYLON.Tmp.Vector3[5];
  55073. var v1v4 = BABYLON.Tmp.Vector3[6];
  55074. var norm1 = BABYLON.Tmp.Vector3[7];
  55075. var norm2 = BABYLON.Tmp.Vector3[8];
  55076. var i = 0;
  55077. var j = 0;
  55078. var k = 0;
  55079. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55080. var h = 0;
  55081. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55082. var d2 = 0;
  55083. var subdivisionsX = this._subdivisionsX;
  55084. var subdivisionsY = this._subdivisionsY;
  55085. for (var row = 0; row < subdivisionsY; row++) {
  55086. for (var col = 0; col < subdivisionsX; col++) {
  55087. i = col * 3;
  55088. j = row * (subdivisionsX + 1) * 3;
  55089. k = (row + 1) * (subdivisionsX + 1) * 3;
  55090. v1.x = positions[j + i];
  55091. v1.y = positions[j + i + 1];
  55092. v1.z = positions[j + i + 2];
  55093. v2.x = positions[j + i + 3];
  55094. v2.y = positions[j + i + 4];
  55095. v2.z = positions[j + i + 5];
  55096. v3.x = positions[k + i];
  55097. v3.y = positions[k + i + 1];
  55098. v3.z = positions[k + i + 2];
  55099. v4.x = positions[k + i + 3];
  55100. v4.y = positions[k + i + 4];
  55101. v4.z = positions[k + i + 5];
  55102. // 2D slope V1V4
  55103. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55104. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55105. // facet equations :
  55106. // we compute each facet normal vector
  55107. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55108. // we compute the value d by applying the equation to v1 which belongs to the plane
  55109. // then we store the facet equation in a Vector4
  55110. v2.subtractToRef(v1, v1v2);
  55111. v3.subtractToRef(v1, v1v3);
  55112. v4.subtractToRef(v1, v1v4);
  55113. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55114. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55115. norm1.normalize();
  55116. norm2.normalize();
  55117. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55118. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55119. var quad = this._heightQuads[row * subdivisionsX + col];
  55120. quad.slope.copyFromFloats(cd, h);
  55121. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55122. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55123. }
  55124. }
  55125. return this;
  55126. };
  55127. GroundMesh.prototype.serialize = function (serializationObject) {
  55128. _super.prototype.serialize.call(this, serializationObject);
  55129. serializationObject.subdivisionsX = this._subdivisionsX;
  55130. serializationObject.subdivisionsY = this._subdivisionsY;
  55131. serializationObject.minX = this._minX;
  55132. serializationObject.maxX = this._maxX;
  55133. serializationObject.minZ = this._minZ;
  55134. serializationObject.maxZ = this._maxZ;
  55135. serializationObject.width = this._width;
  55136. serializationObject.height = this._height;
  55137. };
  55138. GroundMesh.Parse = function (parsedMesh, scene) {
  55139. var result = new GroundMesh(parsedMesh.name, scene);
  55140. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55141. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55142. result._minX = parsedMesh.minX;
  55143. result._maxX = parsedMesh.maxX;
  55144. result._minZ = parsedMesh.minZ;
  55145. result._maxZ = parsedMesh.maxZ;
  55146. result._width = parsedMesh.width;
  55147. result._height = parsedMesh.height;
  55148. return result;
  55149. };
  55150. return GroundMesh;
  55151. }(BABYLON.Mesh));
  55152. BABYLON.GroundMesh = GroundMesh;
  55153. })(BABYLON || (BABYLON = {}));
  55154. //# sourceMappingURL=babylon.groundMesh.js.map
  55155. var BABYLON;
  55156. (function (BABYLON) {
  55157. /**
  55158. * Creates an instance based on a source mesh.
  55159. */
  55160. var InstancedMesh = /** @class */ (function (_super) {
  55161. __extends(InstancedMesh, _super);
  55162. function InstancedMesh(name, source) {
  55163. var _this = _super.call(this, name, source.getScene()) || this;
  55164. source.instances.push(_this);
  55165. _this._sourceMesh = source;
  55166. _this.position.copyFrom(source.position);
  55167. _this.rotation.copyFrom(source.rotation);
  55168. _this.scaling.copyFrom(source.scaling);
  55169. if (source.rotationQuaternion) {
  55170. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55171. }
  55172. _this.infiniteDistance = source.infiniteDistance;
  55173. _this.setPivotMatrix(source.getPivotMatrix());
  55174. _this.refreshBoundingInfo();
  55175. _this._syncSubMeshes();
  55176. return _this;
  55177. }
  55178. /**
  55179. * Returns the string "InstancedMesh".
  55180. */
  55181. InstancedMesh.prototype.getClassName = function () {
  55182. return "InstancedMesh";
  55183. };
  55184. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55185. // Methods
  55186. get: function () {
  55187. return this._sourceMesh.receiveShadows;
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. Object.defineProperty(InstancedMesh.prototype, "material", {
  55193. get: function () {
  55194. return this._sourceMesh.material;
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55200. get: function () {
  55201. return this._sourceMesh.visibility;
  55202. },
  55203. enumerable: true,
  55204. configurable: true
  55205. });
  55206. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55207. get: function () {
  55208. return this._sourceMesh.skeleton;
  55209. },
  55210. enumerable: true,
  55211. configurable: true
  55212. });
  55213. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55214. get: function () {
  55215. return this._sourceMesh.renderingGroupId;
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. /**
  55221. * Returns the total number of vertices (integer).
  55222. */
  55223. InstancedMesh.prototype.getTotalVertices = function () {
  55224. return this._sourceMesh.getTotalVertices();
  55225. };
  55226. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55227. get: function () {
  55228. return this._sourceMesh;
  55229. },
  55230. enumerable: true,
  55231. configurable: true
  55232. });
  55233. /**
  55234. * Is this node ready to be used/rendered
  55235. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55236. * @return {boolean} is it ready
  55237. */
  55238. InstancedMesh.prototype.isReady = function (completeCheck) {
  55239. if (completeCheck === void 0) { completeCheck = false; }
  55240. return this._sourceMesh.isReady(completeCheck, true);
  55241. };
  55242. /**
  55243. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55244. */
  55245. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55246. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55247. };
  55248. /**
  55249. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55250. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55251. * The `data` are either a numeric array either a Float32Array.
  55252. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55253. * 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).
  55254. * Note that a new underlying VertexBuffer object is created each call.
  55255. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55256. *
  55257. * Possible `kind` values :
  55258. * - BABYLON.VertexBuffer.PositionKind
  55259. * - BABYLON.VertexBuffer.UVKind
  55260. * - BABYLON.VertexBuffer.UV2Kind
  55261. * - BABYLON.VertexBuffer.UV3Kind
  55262. * - BABYLON.VertexBuffer.UV4Kind
  55263. * - BABYLON.VertexBuffer.UV5Kind
  55264. * - BABYLON.VertexBuffer.UV6Kind
  55265. * - BABYLON.VertexBuffer.ColorKind
  55266. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55267. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55268. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55269. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55270. *
  55271. * Returns the Mesh.
  55272. */
  55273. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55274. if (this.sourceMesh) {
  55275. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55276. }
  55277. return this.sourceMesh;
  55278. };
  55279. /**
  55280. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55281. * If the mesh has no geometry, it is simply returned as it is.
  55282. * The `data` are either a numeric array either a Float32Array.
  55283. * No new underlying VertexBuffer object is created.
  55284. * 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.
  55285. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55286. *
  55287. * Possible `kind` values :
  55288. * - BABYLON.VertexBuffer.PositionKind
  55289. * - BABYLON.VertexBuffer.UVKind
  55290. * - BABYLON.VertexBuffer.UV2Kind
  55291. * - BABYLON.VertexBuffer.UV3Kind
  55292. * - BABYLON.VertexBuffer.UV4Kind
  55293. * - BABYLON.VertexBuffer.UV5Kind
  55294. * - BABYLON.VertexBuffer.UV6Kind
  55295. * - BABYLON.VertexBuffer.ColorKind
  55296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55300. *
  55301. * Returns the Mesh.
  55302. */
  55303. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55304. if (this.sourceMesh) {
  55305. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55306. }
  55307. return this.sourceMesh;
  55308. };
  55309. /**
  55310. * Sets the mesh indices.
  55311. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55312. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55313. * This method creates a new index buffer each call.
  55314. * Returns the Mesh.
  55315. */
  55316. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55317. if (totalVertices === void 0) { totalVertices = null; }
  55318. if (this.sourceMesh) {
  55319. this.sourceMesh.setIndices(indices, totalVertices);
  55320. }
  55321. return this.sourceMesh;
  55322. };
  55323. /**
  55324. * Boolean : True if the mesh owns the requested kind of data.
  55325. */
  55326. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55327. return this._sourceMesh.isVerticesDataPresent(kind);
  55328. };
  55329. /**
  55330. * Returns an array of indices (IndicesArray).
  55331. */
  55332. InstancedMesh.prototype.getIndices = function () {
  55333. return this._sourceMesh.getIndices();
  55334. };
  55335. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55336. get: function () {
  55337. return this._sourceMesh._positions;
  55338. },
  55339. enumerable: true,
  55340. configurable: true
  55341. });
  55342. /**
  55343. * Sets a new updated BoundingInfo to the mesh.
  55344. * Returns the mesh.
  55345. */
  55346. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55347. var meshBB = this._sourceMesh.getBoundingInfo();
  55348. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55349. this._updateBoundingInfo();
  55350. return this;
  55351. };
  55352. InstancedMesh.prototype._preActivate = function () {
  55353. if (this._currentLOD) {
  55354. this._currentLOD._preActivate();
  55355. }
  55356. return this;
  55357. };
  55358. InstancedMesh.prototype._activate = function (renderId) {
  55359. if (this._currentLOD) {
  55360. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55361. }
  55362. return this;
  55363. };
  55364. /**
  55365. * Returns the current associated LOD AbstractMesh.
  55366. */
  55367. InstancedMesh.prototype.getLOD = function (camera) {
  55368. if (!camera) {
  55369. return this;
  55370. }
  55371. var boundingInfo = this.getBoundingInfo();
  55372. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55373. if (this._currentLOD === this.sourceMesh) {
  55374. return this;
  55375. }
  55376. return this._currentLOD;
  55377. };
  55378. InstancedMesh.prototype._syncSubMeshes = function () {
  55379. this.releaseSubMeshes();
  55380. if (this._sourceMesh.subMeshes) {
  55381. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55382. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55383. }
  55384. }
  55385. return this;
  55386. };
  55387. InstancedMesh.prototype._generatePointsArray = function () {
  55388. return this._sourceMesh._generatePointsArray();
  55389. };
  55390. /**
  55391. * Creates a new InstancedMesh from the current mesh.
  55392. * - name (string) : the cloned mesh name
  55393. * - newParent (optional Node) : the optional Node to parent the clone to.
  55394. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55395. *
  55396. * Returns the clone.
  55397. */
  55398. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55399. var result = this._sourceMesh.createInstance(name);
  55400. // Deep copy
  55401. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55402. // Bounding info
  55403. this.refreshBoundingInfo();
  55404. // Parent
  55405. if (newParent) {
  55406. result.parent = newParent;
  55407. }
  55408. if (!doNotCloneChildren) {
  55409. // Children
  55410. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55411. var mesh = this.getScene().meshes[index];
  55412. if (mesh.parent === this) {
  55413. mesh.clone(mesh.name, result);
  55414. }
  55415. }
  55416. }
  55417. result.computeWorldMatrix(true);
  55418. return result;
  55419. };
  55420. /**
  55421. * Disposes the InstancedMesh.
  55422. * Returns nothing.
  55423. */
  55424. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55425. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55426. // Remove from mesh
  55427. var index = this._sourceMesh.instances.indexOf(this);
  55428. this._sourceMesh.instances.splice(index, 1);
  55429. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55430. };
  55431. return InstancedMesh;
  55432. }(BABYLON.AbstractMesh));
  55433. BABYLON.InstancedMesh = InstancedMesh;
  55434. })(BABYLON || (BABYLON = {}));
  55435. //# sourceMappingURL=babylon.instancedMesh.js.map
  55436. var BABYLON;
  55437. (function (BABYLON) {
  55438. var LinesMesh = /** @class */ (function (_super) {
  55439. __extends(LinesMesh, _super);
  55440. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55441. if (scene === void 0) { scene = null; }
  55442. if (parent === void 0) { parent = null; }
  55443. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55444. _this.useVertexColor = useVertexColor;
  55445. _this.useVertexAlpha = useVertexAlpha;
  55446. _this.color = new BABYLON.Color3(1, 1, 1);
  55447. _this.alpha = 1;
  55448. if (source) {
  55449. _this.color = source.color.clone();
  55450. _this.alpha = source.alpha;
  55451. _this.useVertexColor = source.useVertexColor;
  55452. _this.useVertexAlpha = source.useVertexAlpha;
  55453. }
  55454. _this._intersectionThreshold = 0.1;
  55455. var defines = [];
  55456. var options = {
  55457. attributes: [BABYLON.VertexBuffer.PositionKind],
  55458. uniforms: ["world", "viewProjection"],
  55459. needAlphaBlending: true,
  55460. defines: defines
  55461. };
  55462. if (useVertexAlpha === false) {
  55463. options.needAlphaBlending = false;
  55464. }
  55465. if (!useVertexColor) {
  55466. options.uniforms.push("color");
  55467. }
  55468. else {
  55469. options.defines.push("#define VERTEXCOLOR");
  55470. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55471. }
  55472. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55473. return _this;
  55474. }
  55475. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55476. /**
  55477. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55478. * This margin is expressed in world space coordinates, so its value may vary.
  55479. * Default value is 0.1
  55480. * @returns the intersection Threshold value.
  55481. */
  55482. get: function () {
  55483. return this._intersectionThreshold;
  55484. },
  55485. /**
  55486. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55487. * This margin is expressed in world space coordinates, so its value may vary.
  55488. * @param value the new threshold to apply
  55489. */
  55490. set: function (value) {
  55491. if (this._intersectionThreshold === value) {
  55492. return;
  55493. }
  55494. this._intersectionThreshold = value;
  55495. if (this.geometry) {
  55496. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55497. }
  55498. },
  55499. enumerable: true,
  55500. configurable: true
  55501. });
  55502. /**
  55503. * Returns the string "LineMesh"
  55504. */
  55505. LinesMesh.prototype.getClassName = function () {
  55506. return "LinesMesh";
  55507. };
  55508. Object.defineProperty(LinesMesh.prototype, "material", {
  55509. get: function () {
  55510. return this._colorShader;
  55511. },
  55512. set: function (value) {
  55513. // Do nothing
  55514. },
  55515. enumerable: true,
  55516. configurable: true
  55517. });
  55518. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55519. get: function () {
  55520. return false;
  55521. },
  55522. enumerable: true,
  55523. configurable: true
  55524. });
  55525. LinesMesh.prototype.createInstance = function (name) {
  55526. throw new Error("LinesMeshes do not support createInstance.");
  55527. };
  55528. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55529. if (!this._geometry) {
  55530. return this;
  55531. }
  55532. // VBOs
  55533. this._geometry._bind(this._colorShader.getEffect());
  55534. // Color
  55535. if (!this.useVertexColor) {
  55536. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55537. }
  55538. return this;
  55539. };
  55540. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55541. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55542. return this;
  55543. }
  55544. var engine = this.getScene().getEngine();
  55545. // Draw order
  55546. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55547. return this;
  55548. };
  55549. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55550. this._colorShader.dispose();
  55551. _super.prototype.dispose.call(this, doNotRecurse);
  55552. };
  55553. /**
  55554. * Returns a new LineMesh object cloned from the current one.
  55555. */
  55556. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55557. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55558. };
  55559. return LinesMesh;
  55560. }(BABYLON.Mesh));
  55561. BABYLON.LinesMesh = LinesMesh;
  55562. })(BABYLON || (BABYLON = {}));
  55563. //# sourceMappingURL=babylon.linesMesh.js.map
  55564. var BABYLON;
  55565. (function (BABYLON) {
  55566. var MeshBuilder = /** @class */ (function () {
  55567. function MeshBuilder() {
  55568. }
  55569. MeshBuilder.updateSideOrientation = function (orientation) {
  55570. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55571. return BABYLON.Mesh.DOUBLESIDE;
  55572. }
  55573. if (orientation === undefined || orientation === null) {
  55574. return BABYLON.Mesh.FRONTSIDE;
  55575. }
  55576. return orientation;
  55577. };
  55578. /**
  55579. * Creates a box mesh.
  55580. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55581. * The parameter `size` sets the size (float) of each box side (default 1).
  55582. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55583. * 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).
  55584. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55585. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55586. * 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).
  55587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55589. */
  55590. MeshBuilder.CreateBox = function (name, options, scene) {
  55591. if (scene === void 0) { scene = null; }
  55592. var box = new BABYLON.Mesh(name, scene);
  55593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55594. box._originalBuilderSideOrientation = options.sideOrientation;
  55595. var vertexData = BABYLON.VertexData.CreateBox(options);
  55596. vertexData.applyToMesh(box, options.updatable);
  55597. return box;
  55598. };
  55599. /**
  55600. * Creates a sphere mesh.
  55601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55602. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55603. * 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`).
  55604. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55605. * 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
  55606. * 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).
  55607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55608. * 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).
  55609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55611. */
  55612. MeshBuilder.CreateSphere = function (name, options, scene) {
  55613. var sphere = new BABYLON.Mesh(name, scene);
  55614. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55615. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55616. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55617. vertexData.applyToMesh(sphere, options.updatable);
  55618. return sphere;
  55619. };
  55620. /**
  55621. * Creates a plane polygonal mesh. By default, this is a disc.
  55622. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55623. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55624. * 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.
  55625. * 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
  55626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55627. * 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).
  55628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55630. */
  55631. MeshBuilder.CreateDisc = function (name, options, scene) {
  55632. if (scene === void 0) { scene = null; }
  55633. var disc = new BABYLON.Mesh(name, scene);
  55634. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55635. disc._originalBuilderSideOrientation = options.sideOrientation;
  55636. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55637. vertexData.applyToMesh(disc, options.updatable);
  55638. return disc;
  55639. };
  55640. /**
  55641. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55642. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55643. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55644. * 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`).
  55645. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55646. * 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.
  55647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55648. * 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).
  55649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55651. */
  55652. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55653. var sphere = new BABYLON.Mesh(name, scene);
  55654. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55655. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55656. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55657. vertexData.applyToMesh(sphere, options.updatable);
  55658. return sphere;
  55659. };
  55660. ;
  55661. /**
  55662. * Creates a ribbon mesh.
  55663. * 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.
  55664. *
  55665. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55666. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55667. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55668. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55669. * 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.
  55670. * 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.
  55671. * 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
  55672. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55673. * 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).
  55674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55675. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55676. * 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.
  55677. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55678. * 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
  55679. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55680. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55682. */
  55683. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55684. if (scene === void 0) { scene = null; }
  55685. var pathArray = options.pathArray;
  55686. var closeArray = options.closeArray;
  55687. var closePath = options.closePath;
  55688. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55689. var instance = options.instance;
  55690. var updatable = options.updatable;
  55691. if (instance) {
  55692. // positionFunction : ribbon case
  55693. // only pathArray and sideOrientation parameters are taken into account for positions update
  55694. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55695. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55696. var positionFunction = function (positions) {
  55697. var minlg = pathArray[0].length;
  55698. var i = 0;
  55699. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55700. for (var si = 1; si <= ns; si++) {
  55701. for (var p = 0; p < pathArray.length; p++) {
  55702. var path = pathArray[p];
  55703. var l = path.length;
  55704. minlg = (minlg < l) ? minlg : l;
  55705. var j = 0;
  55706. while (j < minlg) {
  55707. positions[i] = path[j].x;
  55708. positions[i + 1] = path[j].y;
  55709. positions[i + 2] = path[j].z;
  55710. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55711. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55712. }
  55713. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55714. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55715. }
  55716. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55717. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55718. }
  55719. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55720. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55721. }
  55722. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55723. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55724. }
  55725. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55726. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55727. }
  55728. j++;
  55729. i += 3;
  55730. }
  55731. if (instance._closePath) {
  55732. positions[i] = path[0].x;
  55733. positions[i + 1] = path[0].y;
  55734. positions[i + 2] = path[0].z;
  55735. i += 3;
  55736. }
  55737. }
  55738. }
  55739. };
  55740. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55741. positionFunction(positions);
  55742. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55743. instance._boundingInfo.update(instance._worldMatrix);
  55744. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55745. if (options.colors) {
  55746. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55747. for (var c = 0; c < options.colors.length; c++) {
  55748. colors[c * 4] = options.colors[c].r;
  55749. colors[c * 4 + 1] = options.colors[c].g;
  55750. colors[c * 4 + 2] = options.colors[c].b;
  55751. colors[c * 4 + 3] = options.colors[c].a;
  55752. }
  55753. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55754. }
  55755. if (options.uvs) {
  55756. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55757. for (var i = 0; i < options.uvs.length; i++) {
  55758. uvs[i * 2] = options.uvs[i].x;
  55759. uvs[i * 2 + 1] = options.uvs[i].y;
  55760. }
  55761. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55762. }
  55763. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55764. var indices = instance.getIndices();
  55765. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55766. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55767. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55768. if (instance._closePath) {
  55769. var indexFirst = 0;
  55770. var indexLast = 0;
  55771. for (var p = 0; p < pathArray.length; p++) {
  55772. indexFirst = instance._idx[p] * 3;
  55773. if (p + 1 < pathArray.length) {
  55774. indexLast = (instance._idx[p + 1] - 1) * 3;
  55775. }
  55776. else {
  55777. indexLast = normals.length - 3;
  55778. }
  55779. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55780. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55781. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55782. normals[indexLast] = normals[indexFirst];
  55783. normals[indexLast + 1] = normals[indexFirst + 1];
  55784. normals[indexLast + 2] = normals[indexFirst + 2];
  55785. }
  55786. }
  55787. if (!(instance.areNormalsFrozen)) {
  55788. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55789. }
  55790. }
  55791. return instance;
  55792. }
  55793. else {
  55794. var ribbon = new BABYLON.Mesh(name, scene);
  55795. ribbon._originalBuilderSideOrientation = sideOrientation;
  55796. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55797. if (closePath) {
  55798. ribbon._idx = vertexData._idx;
  55799. }
  55800. ribbon._closePath = closePath;
  55801. ribbon._closeArray = closeArray;
  55802. vertexData.applyToMesh(ribbon, updatable);
  55803. return ribbon;
  55804. }
  55805. };
  55806. /**
  55807. * Creates a cylinder or a cone mesh.
  55808. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55809. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55810. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55811. * 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.
  55812. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55813. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55814. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55815. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55816. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55817. * 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).
  55818. * 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
  55819. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55820. * 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
  55821. * 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.
  55822. * If `enclose` is false, a ring surface is one element.
  55823. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55824. * 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
  55825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55826. * 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).
  55827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55829. */
  55830. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55831. var cylinder = new BABYLON.Mesh(name, scene);
  55832. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55833. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55834. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55835. vertexData.applyToMesh(cylinder, options.updatable);
  55836. return cylinder;
  55837. };
  55838. /**
  55839. * Creates a torus mesh.
  55840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55841. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55842. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55843. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55845. * 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).
  55846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55848. */
  55849. MeshBuilder.CreateTorus = function (name, options, scene) {
  55850. var torus = new BABYLON.Mesh(name, scene);
  55851. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55852. torus._originalBuilderSideOrientation = options.sideOrientation;
  55853. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55854. vertexData.applyToMesh(torus, options.updatable);
  55855. return torus;
  55856. };
  55857. /**
  55858. * Creates a torus knot mesh.
  55859. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55860. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55861. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55862. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55863. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55865. * 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).
  55866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55868. */
  55869. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55870. var torusKnot = new BABYLON.Mesh(name, scene);
  55871. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55872. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55873. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55874. vertexData.applyToMesh(torusKnot, options.updatable);
  55875. return torusKnot;
  55876. };
  55877. /**
  55878. * Creates a line system mesh.
  55879. * A line system is a pool of many lines gathered in a single mesh.
  55880. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55881. * 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.
  55882. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55883. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55884. * 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
  55885. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55886. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55887. * 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
  55888. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55890. */
  55891. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55892. var instance = options.instance;
  55893. var lines = options.lines;
  55894. var colors = options.colors;
  55895. if (instance) {
  55896. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55897. var vertexColor;
  55898. var lineColors;
  55899. if (colors) {
  55900. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55901. }
  55902. var i = 0;
  55903. var c = 0;
  55904. for (var l = 0; l < lines.length; l++) {
  55905. var points = lines[l];
  55906. for (var p = 0; p < points.length; p++) {
  55907. positions[i] = points[p].x;
  55908. positions[i + 1] = points[p].y;
  55909. positions[i + 2] = points[p].z;
  55910. if (colors && vertexColor) {
  55911. lineColors = colors[l];
  55912. vertexColor[c] = lineColors[p].r;
  55913. vertexColor[c + 1] = lineColors[p].g;
  55914. vertexColor[c + 2] = lineColors[p].b;
  55915. vertexColor[c + 3] = lineColors[p].a;
  55916. c += 4;
  55917. }
  55918. i += 3;
  55919. }
  55920. }
  55921. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55922. if (colors && vertexColor) {
  55923. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55924. }
  55925. return instance;
  55926. }
  55927. // line system creation
  55928. var useVertexColor = (colors) ? true : false;
  55929. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55930. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55931. vertexData.applyToMesh(lineSystem, options.updatable);
  55932. return lineSystem;
  55933. };
  55934. /**
  55935. * Creates a line mesh.
  55936. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55937. * 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.
  55938. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55939. * The parameter `points` is an array successive Vector3.
  55940. * 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
  55941. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55942. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55943. * When updating an instance, remember that only point positions can change, not the number of points.
  55944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55945. */
  55946. MeshBuilder.CreateLines = function (name, options, scene) {
  55947. if (scene === void 0) { scene = null; }
  55948. var colors = (options.colors) ? [options.colors] : null;
  55949. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55950. return lines;
  55951. };
  55952. /**
  55953. * Creates a dashed line mesh.
  55954. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55955. * 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.
  55956. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55957. * The parameter `points` is an array successive Vector3.
  55958. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55959. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55960. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55961. * 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
  55962. * When updating an instance, remember that only point positions can change, not the number of points.
  55963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55964. */
  55965. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55966. if (scene === void 0) { scene = null; }
  55967. var points = options.points;
  55968. var instance = options.instance;
  55969. var gapSize = options.gapSize || 1;
  55970. var dashSize = options.dashSize || 3;
  55971. if (instance) {
  55972. var positionFunction = function (positions) {
  55973. var curvect = BABYLON.Vector3.Zero();
  55974. var nbSeg = positions.length / 6;
  55975. var lg = 0;
  55976. var nb = 0;
  55977. var shft = 0;
  55978. var dashshft = 0;
  55979. var curshft = 0;
  55980. var p = 0;
  55981. var i = 0;
  55982. var j = 0;
  55983. for (i = 0; i < points.length - 1; i++) {
  55984. points[i + 1].subtractToRef(points[i], curvect);
  55985. lg += curvect.length();
  55986. }
  55987. shft = lg / nbSeg;
  55988. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55989. for (i = 0; i < points.length - 1; i++) {
  55990. points[i + 1].subtractToRef(points[i], curvect);
  55991. nb = Math.floor(curvect.length() / shft);
  55992. curvect.normalize();
  55993. j = 0;
  55994. while (j < nb && p < positions.length) {
  55995. curshft = shft * j;
  55996. positions[p] = points[i].x + curshft * curvect.x;
  55997. positions[p + 1] = points[i].y + curshft * curvect.y;
  55998. positions[p + 2] = points[i].z + curshft * curvect.z;
  55999. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56000. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56001. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56002. p += 6;
  56003. j++;
  56004. }
  56005. }
  56006. while (p < positions.length) {
  56007. positions[p] = points[i].x;
  56008. positions[p + 1] = points[i].y;
  56009. positions[p + 2] = points[i].z;
  56010. p += 3;
  56011. }
  56012. };
  56013. instance.updateMeshPositions(positionFunction, false);
  56014. return instance;
  56015. }
  56016. // dashed lines creation
  56017. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56018. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56019. vertexData.applyToMesh(dashedLines, options.updatable);
  56020. dashedLines.dashSize = dashSize;
  56021. dashedLines.gapSize = gapSize;
  56022. return dashedLines;
  56023. };
  56024. /**
  56025. * Creates an extruded shape mesh.
  56026. * 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.
  56027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56028. *
  56029. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56030. * 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
  56031. * extruded along the Z axis.
  56032. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56033. * 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.
  56034. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56035. * 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
  56036. * 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
  56037. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56038. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56039. * 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).
  56040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56041. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56043. */
  56044. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56045. if (scene === void 0) { scene = null; }
  56046. var path = options.path;
  56047. var shape = options.shape;
  56048. var scale = options.scale || 1;
  56049. var rotation = options.rotation || 0;
  56050. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56051. var updatable = options.updatable;
  56052. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56053. var instance = options.instance || null;
  56054. var invertUV = options.invertUV || false;
  56055. 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);
  56056. };
  56057. /**
  56058. * Creates an custom extruded shape mesh.
  56059. * 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.
  56060. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56061. *
  56062. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56063. * 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
  56064. * extruded along the Z axis.
  56065. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56066. * 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
  56067. * and the distance of this point from the begining of the path :
  56068. * ```javascript
  56069. * var rotationFunction = function(i, distance) {
  56070. * // do things
  56071. * return rotationValue; }
  56072. * ```
  56073. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56074. * 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
  56075. * and the distance of this point from the begining of the path :
  56076. * ```javascript
  56077. * var scaleFunction = function(i, distance) {
  56078. * // do things
  56079. * return scaleValue;}
  56080. * ```
  56081. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56082. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56083. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56084. * 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
  56085. * 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
  56086. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56088. * 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).
  56089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56090. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56092. */
  56093. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56094. var path = options.path;
  56095. var shape = options.shape;
  56096. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56097. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56098. var ribbonCloseArray = options.ribbonCloseArray || false;
  56099. var ribbonClosePath = options.ribbonClosePath || false;
  56100. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56101. var updatable = options.updatable;
  56102. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56103. var instance = options.instance;
  56104. var invertUV = options.invertUV || false;
  56105. 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);
  56106. };
  56107. /**
  56108. * Creates lathe mesh.
  56109. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56111. *
  56112. * 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
  56113. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56114. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56115. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56116. * 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.
  56117. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56118. * 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
  56119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56120. * 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).
  56121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56122. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56123. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56124. */
  56125. MeshBuilder.CreateLathe = function (name, options, scene) {
  56126. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56127. var closed = (options.closed === undefined) ? true : options.closed;
  56128. var shape = options.shape;
  56129. var radius = options.radius || 1;
  56130. var tessellation = options.tessellation || 64;
  56131. var updatable = options.updatable;
  56132. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56133. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56134. var pi2 = Math.PI * 2;
  56135. var paths = new Array();
  56136. var invertUV = options.invertUV || false;
  56137. var i = 0;
  56138. var p = 0;
  56139. var step = pi2 / tessellation * arc;
  56140. var rotated;
  56141. var path = new Array();
  56142. ;
  56143. for (i = 0; i <= tessellation; i++) {
  56144. var path = [];
  56145. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56146. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56147. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56148. }
  56149. for (p = 0; p < shape.length; p++) {
  56150. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56151. path.push(rotated);
  56152. }
  56153. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56154. 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));
  56155. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56156. }
  56157. paths.push(path);
  56158. }
  56159. // lathe ribbon
  56160. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56161. return lathe;
  56162. };
  56163. /**
  56164. * Creates a plane mesh.
  56165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56166. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56167. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56168. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56170. * 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).
  56171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreatePlane = function (name, options, scene) {
  56175. var plane = new BABYLON.Mesh(name, scene);
  56176. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56177. plane._originalBuilderSideOrientation = options.sideOrientation;
  56178. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56179. vertexData.applyToMesh(plane, options.updatable);
  56180. if (options.sourcePlane) {
  56181. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56182. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56183. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56184. plane.rotate(vectorProduct, product);
  56185. }
  56186. return plane;
  56187. };
  56188. /**
  56189. * Creates a ground mesh.
  56190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56191. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56192. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56194. */
  56195. MeshBuilder.CreateGround = function (name, options, scene) {
  56196. var ground = new BABYLON.GroundMesh(name, scene);
  56197. ground._setReady(false);
  56198. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56199. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56200. ground._width = options.width || 1;
  56201. ground._height = options.height || 1;
  56202. ground._maxX = ground._width / 2;
  56203. ground._maxZ = ground._height / 2;
  56204. ground._minX = -ground._maxX;
  56205. ground._minZ = -ground._maxZ;
  56206. var vertexData = BABYLON.VertexData.CreateGround(options);
  56207. vertexData.applyToMesh(ground, options.updatable);
  56208. ground._setReady(true);
  56209. return ground;
  56210. };
  56211. /**
  56212. * Creates a tiled ground mesh.
  56213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56214. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56215. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56216. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56217. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56218. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56219. * numbers of subdivisions on the ground width and height of each tile.
  56220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56221. */
  56222. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56223. var tiledGround = new BABYLON.Mesh(name, scene);
  56224. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56225. vertexData.applyToMesh(tiledGround, options.updatable);
  56226. return tiledGround;
  56227. };
  56228. /**
  56229. * Creates a ground mesh from a height map.
  56230. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56232. * The parameter `url` sets the URL of the height map image resource.
  56233. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56234. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56235. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56236. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56237. * 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.
  56238. * 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).
  56239. * This function is passed the newly built mesh :
  56240. * ```javascript
  56241. * function(mesh) { // do things
  56242. * return; }
  56243. * ```
  56244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56245. */
  56246. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56247. var width = options.width || 10.0;
  56248. var height = options.height || 10.0;
  56249. var subdivisions = options.subdivisions || 1 | 0;
  56250. var minHeight = options.minHeight || 0.0;
  56251. var maxHeight = options.maxHeight || 1.0;
  56252. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56253. var updatable = options.updatable;
  56254. var onReady = options.onReady;
  56255. var ground = new BABYLON.GroundMesh(name, scene);
  56256. ground._subdivisionsX = subdivisions;
  56257. ground._subdivisionsY = subdivisions;
  56258. ground._width = width;
  56259. ground._height = height;
  56260. ground._maxX = ground._width / 2.0;
  56261. ground._maxZ = ground._height / 2.0;
  56262. ground._minX = -ground._maxX;
  56263. ground._minZ = -ground._maxZ;
  56264. ground._setReady(false);
  56265. var onload = function (img) {
  56266. // Getting height map data
  56267. var canvas = document.createElement("canvas");
  56268. var context = canvas.getContext("2d");
  56269. if (!context) {
  56270. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56271. }
  56272. if (scene.isDisposed) {
  56273. return;
  56274. }
  56275. var bufferWidth = img.width;
  56276. var bufferHeight = img.height;
  56277. canvas.width = bufferWidth;
  56278. canvas.height = bufferHeight;
  56279. context.drawImage(img, 0, 0);
  56280. // Create VertexData from map data
  56281. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56282. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56283. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56284. width: width, height: height,
  56285. subdivisions: subdivisions,
  56286. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56287. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56288. });
  56289. vertexData.applyToMesh(ground, updatable);
  56290. ground._setReady(true);
  56291. //execute ready callback, if set
  56292. if (onReady) {
  56293. onReady(ground);
  56294. }
  56295. };
  56296. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56297. return ground;
  56298. };
  56299. /**
  56300. * Creates a polygon mesh.
  56301. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56302. * 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.
  56303. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56305. * 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).
  56306. * Remember you can only change the shape positions, not their number when updating a polygon.
  56307. */
  56308. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56309. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56310. var shape = options.shape;
  56311. var holes = options.holes || [];
  56312. var depth = options.depth || 0;
  56313. var contours = [];
  56314. var hole = [];
  56315. for (var i = 0; i < shape.length; i++) {
  56316. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56317. }
  56318. var epsilon = 0.00000001;
  56319. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56320. contours.pop();
  56321. }
  56322. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56323. for (var hNb = 0; hNb < holes.length; hNb++) {
  56324. hole = [];
  56325. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56326. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56327. }
  56328. polygonTriangulation.addHole(hole);
  56329. }
  56330. var polygon = polygonTriangulation.build(options.updatable, depth);
  56331. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56332. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56333. vertexData.applyToMesh(polygon, options.updatable);
  56334. return polygon;
  56335. };
  56336. ;
  56337. /**
  56338. * Creates an extruded polygon mesh, with depth in the Y direction.
  56339. * 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).
  56340. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56341. */
  56342. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56343. return MeshBuilder.CreatePolygon(name, options, scene);
  56344. };
  56345. ;
  56346. /**
  56347. * Creates a tube mesh.
  56348. * 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.
  56349. *
  56350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56351. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56352. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56353. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56354. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56355. * 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.
  56356. * It must return a radius value (positive float) :
  56357. * ```javascript
  56358. * var radiusFunction = function(i, distance) {
  56359. * // do things
  56360. * return radius; }
  56361. * ```
  56362. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56363. * 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
  56364. * 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
  56365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56366. * 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).
  56367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56368. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56370. */
  56371. MeshBuilder.CreateTube = function (name, options, scene) {
  56372. var path = options.path;
  56373. var instance = options.instance;
  56374. var radius = 1.0;
  56375. if (instance) {
  56376. radius = instance.radius;
  56377. }
  56378. if (options.radius !== undefined) {
  56379. radius = options.radius;
  56380. }
  56381. ;
  56382. var tessellation = options.tessellation || 64 | 0;
  56383. var radiusFunction = options.radiusFunction || null;
  56384. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56385. var invertUV = options.invertUV || false;
  56386. var updatable = options.updatable;
  56387. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56388. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56389. // tube geometry
  56390. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56391. var tangents = path3D.getTangents();
  56392. var normals = path3D.getNormals();
  56393. var distances = path3D.getDistances();
  56394. var pi2 = Math.PI * 2;
  56395. var step = pi2 / tessellation * arc;
  56396. var returnRadius = function () { return radius; };
  56397. var radiusFunctionFinal = radiusFunction || returnRadius;
  56398. var circlePath;
  56399. var rad;
  56400. var normal;
  56401. var rotated;
  56402. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56403. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56404. for (var i = 0; i < path.length; i++) {
  56405. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56406. circlePath = Array(); // current circle array
  56407. normal = normals[i]; // current normal
  56408. for (var t = 0; t < tessellation; t++) {
  56409. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56410. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56411. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56412. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56413. circlePath[t] = rotated;
  56414. }
  56415. circlePaths[index] = circlePath;
  56416. index++;
  56417. }
  56418. // cap
  56419. var capPath = function (nbPoints, pathIndex) {
  56420. var pointCap = Array();
  56421. for (var i = 0; i < nbPoints; i++) {
  56422. pointCap.push(path[pathIndex]);
  56423. }
  56424. return pointCap;
  56425. };
  56426. switch (cap) {
  56427. case BABYLON.Mesh.NO_CAP:
  56428. break;
  56429. case BABYLON.Mesh.CAP_START:
  56430. circlePaths[0] = capPath(tessellation, 0);
  56431. circlePaths[1] = circlePaths[2].slice(0);
  56432. break;
  56433. case BABYLON.Mesh.CAP_END:
  56434. circlePaths[index] = circlePaths[index - 1].slice(0);
  56435. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56436. break;
  56437. case BABYLON.Mesh.CAP_ALL:
  56438. circlePaths[0] = capPath(tessellation, 0);
  56439. circlePaths[1] = circlePaths[2].slice(0);
  56440. circlePaths[index] = circlePaths[index - 1].slice(0);
  56441. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56442. break;
  56443. default:
  56444. break;
  56445. }
  56446. return circlePaths;
  56447. };
  56448. var path3D;
  56449. var pathArray;
  56450. if (instance) {
  56451. var arc = options.arc || instance.arc;
  56452. path3D = (instance.path3D).update(path);
  56453. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56454. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56455. instance.path3D = path3D;
  56456. instance.pathArray = pathArray;
  56457. instance.arc = arc;
  56458. instance.radius = radius;
  56459. return instance;
  56460. }
  56461. // tube creation
  56462. path3D = new BABYLON.Path3D(path);
  56463. var newPathArray = new Array();
  56464. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56465. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56466. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56467. tube.pathArray = pathArray;
  56468. tube.path3D = path3D;
  56469. tube.tessellation = tessellation;
  56470. tube.cap = cap;
  56471. tube.arc = options.arc;
  56472. tube.radius = radius;
  56473. return tube;
  56474. };
  56475. /**
  56476. * Creates a polyhedron mesh.
  56477. *
  56478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56479. * 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
  56480. * to choose the wanted type.
  56481. * The parameter `size` (positive float, default 1) sets the polygon size.
  56482. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56483. * 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`.
  56484. * 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
  56485. * 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)`).
  56486. * 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
  56487. * 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.
  56488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56489. * 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).
  56490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56492. */
  56493. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56494. var polyhedron = new BABYLON.Mesh(name, scene);
  56495. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56496. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56497. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56498. vertexData.applyToMesh(polyhedron, options.updatable);
  56499. return polyhedron;
  56500. };
  56501. /**
  56502. * Creates a decal mesh.
  56503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56504. * 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.
  56505. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56506. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56507. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56508. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56509. */
  56510. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56511. var indices = sourceMesh.getIndices();
  56512. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56513. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56514. var position = options.position || BABYLON.Vector3.Zero();
  56515. var normal = options.normal || BABYLON.Vector3.Up();
  56516. var size = options.size || BABYLON.Vector3.One();
  56517. var angle = options.angle || 0;
  56518. // Getting correct rotation
  56519. if (!normal) {
  56520. var target = new BABYLON.Vector3(0, 0, 1);
  56521. var camera = sourceMesh.getScene().activeCamera;
  56522. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56523. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56524. }
  56525. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56526. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56527. var pitch = Math.atan2(normal.y, len);
  56528. // Matrix
  56529. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56530. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56531. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56532. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56533. var vertexData = new BABYLON.VertexData();
  56534. vertexData.indices = [];
  56535. vertexData.positions = [];
  56536. vertexData.normals = [];
  56537. vertexData.uvs = [];
  56538. var currentVertexDataIndex = 0;
  56539. var extractDecalVector3 = function (indexId) {
  56540. var result = new BABYLON.PositionNormalVertex();
  56541. if (!indices || !positions || !normals) {
  56542. return result;
  56543. }
  56544. var vertexId = indices[indexId];
  56545. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56546. // Send vector to decal local world
  56547. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56548. // Get normal
  56549. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56550. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56551. return result;
  56552. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56553. var clip = function (vertices, axis) {
  56554. if (vertices.length === 0) {
  56555. return vertices;
  56556. }
  56557. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56558. var clipVertices = function (v0, v1) {
  56559. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56560. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56561. };
  56562. var result = new Array();
  56563. for (var index = 0; index < vertices.length; index += 3) {
  56564. var v1Out;
  56565. var v2Out;
  56566. var v3Out;
  56567. var total = 0;
  56568. var nV1 = null;
  56569. var nV2 = null;
  56570. var nV3 = null;
  56571. var nV4 = null;
  56572. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56573. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56574. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56575. v1Out = d1 > 0;
  56576. v2Out = d2 > 0;
  56577. v3Out = d3 > 0;
  56578. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56579. switch (total) {
  56580. case 0:
  56581. result.push(vertices[index]);
  56582. result.push(vertices[index + 1]);
  56583. result.push(vertices[index + 2]);
  56584. break;
  56585. case 1:
  56586. if (v1Out) {
  56587. nV1 = vertices[index + 1];
  56588. nV2 = vertices[index + 2];
  56589. nV3 = clipVertices(vertices[index], nV1);
  56590. nV4 = clipVertices(vertices[index], nV2);
  56591. }
  56592. if (v2Out) {
  56593. nV1 = vertices[index];
  56594. nV2 = vertices[index + 2];
  56595. nV3 = clipVertices(vertices[index + 1], nV1);
  56596. nV4 = clipVertices(vertices[index + 1], nV2);
  56597. result.push(nV3);
  56598. result.push(nV2.clone());
  56599. result.push(nV1.clone());
  56600. result.push(nV2.clone());
  56601. result.push(nV3.clone());
  56602. result.push(nV4);
  56603. break;
  56604. }
  56605. if (v3Out) {
  56606. nV1 = vertices[index];
  56607. nV2 = vertices[index + 1];
  56608. nV3 = clipVertices(vertices[index + 2], nV1);
  56609. nV4 = clipVertices(vertices[index + 2], nV2);
  56610. }
  56611. if (nV1 && nV2 && nV3 && nV4) {
  56612. result.push(nV1.clone());
  56613. result.push(nV2.clone());
  56614. result.push(nV3);
  56615. result.push(nV4);
  56616. result.push(nV3.clone());
  56617. result.push(nV2.clone());
  56618. }
  56619. break;
  56620. case 2:
  56621. if (!v1Out) {
  56622. nV1 = vertices[index].clone();
  56623. nV2 = clipVertices(nV1, vertices[index + 1]);
  56624. nV3 = clipVertices(nV1, vertices[index + 2]);
  56625. result.push(nV1);
  56626. result.push(nV2);
  56627. result.push(nV3);
  56628. }
  56629. if (!v2Out) {
  56630. nV1 = vertices[index + 1].clone();
  56631. nV2 = clipVertices(nV1, vertices[index + 2]);
  56632. nV3 = clipVertices(nV1, vertices[index]);
  56633. result.push(nV1);
  56634. result.push(nV2);
  56635. result.push(nV3);
  56636. }
  56637. if (!v3Out) {
  56638. nV1 = vertices[index + 2].clone();
  56639. nV2 = clipVertices(nV1, vertices[index]);
  56640. nV3 = clipVertices(nV1, vertices[index + 1]);
  56641. result.push(nV1);
  56642. result.push(nV2);
  56643. result.push(nV3);
  56644. }
  56645. break;
  56646. case 3:
  56647. break;
  56648. }
  56649. }
  56650. return result;
  56651. };
  56652. for (var index = 0; index < indices.length; index += 3) {
  56653. var faceVertices = new Array();
  56654. faceVertices.push(extractDecalVector3(index));
  56655. faceVertices.push(extractDecalVector3(index + 1));
  56656. faceVertices.push(extractDecalVector3(index + 2));
  56657. // Clip
  56658. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56659. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56660. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56661. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56662. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56663. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56664. if (faceVertices.length === 0) {
  56665. continue;
  56666. }
  56667. // Add UVs and get back to world
  56668. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56669. var vertex = faceVertices[vIndex];
  56670. //TODO check for Int32Array | Uint32Array | Uint16Array
  56671. vertexData.indices.push(currentVertexDataIndex);
  56672. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56673. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56674. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56675. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56676. currentVertexDataIndex++;
  56677. }
  56678. }
  56679. // Return mesh
  56680. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56681. vertexData.applyToMesh(decal);
  56682. decal.position = position.clone();
  56683. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56684. return decal;
  56685. };
  56686. // Privates
  56687. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56688. // extrusion geometry
  56689. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56690. var tangents = path3D.getTangents();
  56691. var normals = path3D.getNormals();
  56692. var binormals = path3D.getBinormals();
  56693. var distances = path3D.getDistances();
  56694. var angle = 0;
  56695. var returnScale = function () { return scale !== null ? scale : 1; };
  56696. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56697. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56698. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56699. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56700. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56701. for (var i = 0; i < curve.length; i++) {
  56702. var shapePath = new Array();
  56703. var angleStep = rotate(i, distances[i]);
  56704. var scaleRatio = scl(i, distances[i]);
  56705. for (var p = 0; p < shape.length; p++) {
  56706. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56707. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56708. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56709. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56710. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56711. shapePath[p] = rotated;
  56712. }
  56713. shapePaths[index] = shapePath;
  56714. angle += angleStep;
  56715. index++;
  56716. }
  56717. // cap
  56718. var capPath = function (shapePath) {
  56719. var pointCap = Array();
  56720. var barycenter = BABYLON.Vector3.Zero();
  56721. var i;
  56722. for (i = 0; i < shapePath.length; i++) {
  56723. barycenter.addInPlace(shapePath[i]);
  56724. }
  56725. barycenter.scaleInPlace(1.0 / shapePath.length);
  56726. for (i = 0; i < shapePath.length; i++) {
  56727. pointCap.push(barycenter);
  56728. }
  56729. return pointCap;
  56730. };
  56731. switch (cap) {
  56732. case BABYLON.Mesh.NO_CAP:
  56733. break;
  56734. case BABYLON.Mesh.CAP_START:
  56735. shapePaths[0] = capPath(shapePaths[2]);
  56736. shapePaths[1] = shapePaths[2];
  56737. break;
  56738. case BABYLON.Mesh.CAP_END:
  56739. shapePaths[index] = shapePaths[index - 1];
  56740. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56741. break;
  56742. case BABYLON.Mesh.CAP_ALL:
  56743. shapePaths[0] = capPath(shapePaths[2]);
  56744. shapePaths[1] = shapePaths[2];
  56745. shapePaths[index] = shapePaths[index - 1];
  56746. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56747. break;
  56748. default:
  56749. break;
  56750. }
  56751. return shapePaths;
  56752. };
  56753. var path3D;
  56754. var pathArray;
  56755. if (instance) {
  56756. path3D = (instance.path3D).update(curve);
  56757. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56758. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56759. return instance;
  56760. }
  56761. // extruded shape creation
  56762. path3D = new BABYLON.Path3D(curve);
  56763. var newShapePaths = new Array();
  56764. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56765. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56766. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56767. extrudedGeneric.pathArray = pathArray;
  56768. extrudedGeneric.path3D = path3D;
  56769. extrudedGeneric.cap = cap;
  56770. return extrudedGeneric;
  56771. };
  56772. return MeshBuilder;
  56773. }());
  56774. BABYLON.MeshBuilder = MeshBuilder;
  56775. })(BABYLON || (BABYLON = {}));
  56776. //# sourceMappingURL=babylon.meshBuilder.js.map
  56777. var BABYLON;
  56778. (function (BABYLON) {
  56779. /**
  56780. * Draco compression (https://google.github.io/draco/)
  56781. */
  56782. var DracoCompression = /** @class */ (function () {
  56783. /**
  56784. * Constructor
  56785. * @param numWorkers The number of workers for async operations
  56786. */
  56787. function DracoCompression(numWorkers) {
  56788. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56789. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56790. if (!workerBlobUrl || !Worker) {
  56791. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56792. return;
  56793. }
  56794. var workers = new Array(numWorkers);
  56795. for (var i = 0; i < workers.length; i++) {
  56796. var worker = new Worker(workerBlobUrl);
  56797. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56798. workers[i] = worker;
  56799. }
  56800. this._workerPool = new BABYLON.WorkerPool(workers);
  56801. }
  56802. /**
  56803. * Stop all async operations and release resources.
  56804. */
  56805. DracoCompression.prototype.dispose = function () {
  56806. this._workerPool.dispose();
  56807. delete this._workerPool;
  56808. };
  56809. /**
  56810. * Decode Draco compressed mesh data to vertex data.
  56811. * @param data The array buffer view for the Draco compression data
  56812. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56813. * @returns A promise that resolves with the decoded vertex data
  56814. */
  56815. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56816. var _this = this;
  56817. return new Promise(function (resolve, reject) {
  56818. _this._workerPool.push(function (worker, onComplete) {
  56819. var vertexData = new BABYLON.VertexData();
  56820. var onError = function (error) {
  56821. worker.removeEventListener("error", onError);
  56822. worker.removeEventListener("message", onMessage);
  56823. reject(error);
  56824. onComplete();
  56825. };
  56826. var onMessage = function (message) {
  56827. if (message.data === "done") {
  56828. worker.removeEventListener("error", onError);
  56829. worker.removeEventListener("message", onMessage);
  56830. resolve(vertexData);
  56831. onComplete();
  56832. }
  56833. else if (message.data.id === "indices") {
  56834. vertexData.indices = message.data.value;
  56835. }
  56836. else {
  56837. vertexData.set(message.data.value, message.data.id);
  56838. }
  56839. };
  56840. worker.addEventListener("error", onError);
  56841. worker.addEventListener("message", onMessage);
  56842. var dataCopy = new Uint8Array(data.byteLength);
  56843. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56844. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56845. });
  56846. });
  56847. };
  56848. /**
  56849. * The worker function that gets converted to a blob url to pass into a worker.
  56850. */
  56851. DracoCompression._Worker = function () {
  56852. // self is actually a DedicatedWorkerGlobalScope
  56853. var _self = self;
  56854. var decodeMesh = function (data, attributes) {
  56855. var dracoModule = new DracoDecoderModule();
  56856. var buffer = new dracoModule.DecoderBuffer();
  56857. buffer.Init(data, data.byteLength);
  56858. var decoder = new dracoModule.Decoder();
  56859. var geometry;
  56860. var status;
  56861. try {
  56862. var type = decoder.GetEncodedGeometryType(buffer);
  56863. switch (type) {
  56864. case dracoModule.TRIANGULAR_MESH:
  56865. geometry = new dracoModule.Mesh();
  56866. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56867. break;
  56868. case dracoModule.POINT_CLOUD:
  56869. geometry = new dracoModule.PointCloud();
  56870. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56871. break;
  56872. default:
  56873. throw new Error("Invalid geometry type " + type);
  56874. }
  56875. if (!status.ok() || !geometry.ptr) {
  56876. throw new Error(status.error_msg());
  56877. }
  56878. var numPoints = geometry.num_points();
  56879. if (type === dracoModule.TRIANGULAR_MESH) {
  56880. var numFaces = geometry.num_faces();
  56881. var faceIndices = new dracoModule.DracoInt32Array();
  56882. try {
  56883. var indices = new Uint32Array(numFaces * 3);
  56884. for (var i = 0; i < numFaces; i++) {
  56885. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56886. var offset = i * 3;
  56887. indices[offset + 0] = faceIndices.GetValue(0);
  56888. indices[offset + 1] = faceIndices.GetValue(1);
  56889. indices[offset + 2] = faceIndices.GetValue(2);
  56890. }
  56891. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56892. }
  56893. finally {
  56894. dracoModule.destroy(faceIndices);
  56895. }
  56896. }
  56897. for (var kind in attributes) {
  56898. var uniqueId = attributes[kind];
  56899. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56900. var dracoData = new dracoModule.DracoFloat32Array();
  56901. try {
  56902. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56903. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56904. for (var i = 0; i < babylonData.length; i++) {
  56905. babylonData[i] = dracoData.GetValue(i);
  56906. }
  56907. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56908. }
  56909. finally {
  56910. dracoModule.destroy(dracoData);
  56911. }
  56912. }
  56913. }
  56914. finally {
  56915. if (geometry) {
  56916. dracoModule.destroy(geometry);
  56917. }
  56918. dracoModule.destroy(decoder);
  56919. dracoModule.destroy(buffer);
  56920. }
  56921. _self.postMessage("done");
  56922. };
  56923. _self.onmessage = function (event) {
  56924. switch (event.data.id) {
  56925. case "initDecoder": {
  56926. importScripts(event.data.url);
  56927. break;
  56928. }
  56929. case "decodeMesh": {
  56930. decodeMesh(event.data.data, event.data.attributes);
  56931. break;
  56932. }
  56933. }
  56934. };
  56935. };
  56936. DracoCompression._GetDefaultDecoderUrl = function () {
  56937. if (!BABYLON.Tools.IsWindowObjectExist) {
  56938. return null;
  56939. }
  56940. for (var i = 0; i < document.scripts.length; i++) {
  56941. if (document.scripts[i].type === "text/x-draco-decoder") {
  56942. return document.scripts[i].src;
  56943. }
  56944. }
  56945. return null;
  56946. };
  56947. /**
  56948. * Gets the url to the draco decoder if available.
  56949. */
  56950. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56951. return DracoCompression;
  56952. }());
  56953. BABYLON.DracoCompression = DracoCompression;
  56954. })(BABYLON || (BABYLON = {}));
  56955. //# sourceMappingURL=babylon.dracoCompression.js.map
  56956. var BABYLON;
  56957. (function (BABYLON) {
  56958. var AudioEngine = /** @class */ (function () {
  56959. function AudioEngine() {
  56960. this._audioContext = null;
  56961. this._audioContextInitialized = false;
  56962. this.canUseWebAudio = false;
  56963. this.WarnedWebAudioUnsupported = false;
  56964. this.unlocked = false;
  56965. this.isMP3supported = false;
  56966. this.isOGGsupported = false;
  56967. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56968. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56969. this.canUseWebAudio = true;
  56970. }
  56971. var audioElem = document.createElement('audio');
  56972. try {
  56973. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56974. this.isMP3supported = true;
  56975. }
  56976. }
  56977. catch (e) {
  56978. // protect error during capability check.
  56979. }
  56980. try {
  56981. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56982. this.isOGGsupported = true;
  56983. }
  56984. }
  56985. catch (e) {
  56986. // protect error during capability check.
  56987. }
  56988. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56989. this._unlockiOSaudio();
  56990. }
  56991. else {
  56992. this.unlocked = true;
  56993. }
  56994. }
  56995. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56996. get: function () {
  56997. if (!this._audioContextInitialized) {
  56998. this._initializeAudioContext();
  56999. }
  57000. return this._audioContext;
  57001. },
  57002. enumerable: true,
  57003. configurable: true
  57004. });
  57005. AudioEngine.prototype._unlockiOSaudio = function () {
  57006. var _this = this;
  57007. var unlockaudio = function () {
  57008. if (!_this.audioContext) {
  57009. return;
  57010. }
  57011. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57012. var source = _this.audioContext.createBufferSource();
  57013. source.buffer = buffer;
  57014. source.connect(_this.audioContext.destination);
  57015. source.start(0);
  57016. setTimeout(function () {
  57017. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57018. _this.unlocked = true;
  57019. window.removeEventListener('touchend', unlockaudio, false);
  57020. if (_this.onAudioUnlocked) {
  57021. _this.onAudioUnlocked();
  57022. }
  57023. }
  57024. }, 0);
  57025. };
  57026. window.addEventListener('touchend', unlockaudio, false);
  57027. };
  57028. AudioEngine.prototype._initializeAudioContext = function () {
  57029. try {
  57030. if (this.canUseWebAudio) {
  57031. this._audioContext = new AudioContext();
  57032. // create a global volume gain node
  57033. this.masterGain = this._audioContext.createGain();
  57034. this.masterGain.gain.value = 1;
  57035. this.masterGain.connect(this._audioContext.destination);
  57036. this._audioContextInitialized = true;
  57037. }
  57038. }
  57039. catch (e) {
  57040. this.canUseWebAudio = false;
  57041. BABYLON.Tools.Error("Web Audio: " + e.message);
  57042. }
  57043. };
  57044. AudioEngine.prototype.dispose = function () {
  57045. if (this.canUseWebAudio && this._audioContextInitialized) {
  57046. if (this._connectedAnalyser && this._audioContext) {
  57047. this._connectedAnalyser.stopDebugCanvas();
  57048. this._connectedAnalyser.dispose();
  57049. this.masterGain.disconnect();
  57050. this.masterGain.connect(this._audioContext.destination);
  57051. this._connectedAnalyser = null;
  57052. }
  57053. this.masterGain.gain.value = 1;
  57054. }
  57055. this.WarnedWebAudioUnsupported = false;
  57056. };
  57057. AudioEngine.prototype.getGlobalVolume = function () {
  57058. if (this.canUseWebAudio && this._audioContextInitialized) {
  57059. return this.masterGain.gain.value;
  57060. }
  57061. else {
  57062. return -1;
  57063. }
  57064. };
  57065. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57066. if (this.canUseWebAudio && this._audioContextInitialized) {
  57067. this.masterGain.gain.value = newVolume;
  57068. }
  57069. };
  57070. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57071. if (this._connectedAnalyser) {
  57072. this._connectedAnalyser.stopDebugCanvas();
  57073. }
  57074. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57075. this._connectedAnalyser = analyser;
  57076. this.masterGain.disconnect();
  57077. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57078. }
  57079. };
  57080. return AudioEngine;
  57081. }());
  57082. BABYLON.AudioEngine = AudioEngine;
  57083. })(BABYLON || (BABYLON = {}));
  57084. //# sourceMappingURL=babylon.audioEngine.js.map
  57085. var BABYLON;
  57086. (function (BABYLON) {
  57087. var Sound = /** @class */ (function () {
  57088. /**
  57089. * Create a sound and attach it to a scene
  57090. * @param name Name of your sound
  57091. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57092. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57093. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57094. */
  57095. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57096. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57097. var _this = this;
  57098. this.autoplay = false;
  57099. this.loop = false;
  57100. this.useCustomAttenuation = false;
  57101. this.spatialSound = false;
  57102. this.refDistance = 1;
  57103. this.rolloffFactor = 1;
  57104. this.maxDistance = 100;
  57105. this.distanceModel = "linear";
  57106. this._panningModel = "equalpower";
  57107. this._playbackRate = 1;
  57108. this._streaming = false;
  57109. this._startTime = 0;
  57110. this._startOffset = 0;
  57111. this._position = BABYLON.Vector3.Zero();
  57112. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57113. this._volume = 1;
  57114. this._isReadyToPlay = false;
  57115. this.isPlaying = false;
  57116. this.isPaused = false;
  57117. this._isDirectional = false;
  57118. // Used if you'd like to create a directional sound.
  57119. // If not set, the sound will be omnidirectional
  57120. this._coneInnerAngle = 360;
  57121. this._coneOuterAngle = 360;
  57122. this._coneOuterGain = 0;
  57123. this._isOutputConnected = false;
  57124. this._urlType = "Unknown";
  57125. this.name = name;
  57126. this._scene = scene;
  57127. this._readyToPlayCallback = readyToPlayCallback;
  57128. // Default custom attenuation function is a linear attenuation
  57129. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57130. if (currentDistance < maxDistance) {
  57131. return currentVolume * (1 - currentDistance / maxDistance);
  57132. }
  57133. else {
  57134. return 0;
  57135. }
  57136. };
  57137. if (options) {
  57138. this.autoplay = options.autoplay || false;
  57139. this.loop = options.loop || false;
  57140. // if volume === 0, we need another way to check this option
  57141. if (options.volume !== undefined) {
  57142. this._volume = options.volume;
  57143. }
  57144. this.spatialSound = options.spatialSound || false;
  57145. this.maxDistance = options.maxDistance || 100;
  57146. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57147. this.rolloffFactor = options.rolloffFactor || 1;
  57148. this.refDistance = options.refDistance || 1;
  57149. this.distanceModel = options.distanceModel || "linear";
  57150. this._playbackRate = options.playbackRate || 1;
  57151. this._streaming = options.streaming || false;
  57152. }
  57153. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57154. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57155. this._soundGain.gain.value = this._volume;
  57156. this._inputAudioNode = this._soundGain;
  57157. this._ouputAudioNode = this._soundGain;
  57158. if (this.spatialSound) {
  57159. this._createSpatialParameters();
  57160. }
  57161. this._scene.mainSoundTrack.AddSound(this);
  57162. var validParameter = true;
  57163. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57164. if (urlOrArrayBuffer) {
  57165. if (typeof (urlOrArrayBuffer) === "string")
  57166. this._urlType = "String";
  57167. if (Array.isArray(urlOrArrayBuffer))
  57168. this._urlType = "Array";
  57169. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57170. this._urlType = "ArrayBuffer";
  57171. var urls = [];
  57172. var codecSupportedFound = false;
  57173. switch (this._urlType) {
  57174. case "ArrayBuffer":
  57175. if (urlOrArrayBuffer.byteLength > 0) {
  57176. codecSupportedFound = true;
  57177. this._soundLoaded(urlOrArrayBuffer);
  57178. }
  57179. break;
  57180. case "String":
  57181. urls.push(urlOrArrayBuffer);
  57182. case "Array":
  57183. if (urls.length === 0)
  57184. urls = urlOrArrayBuffer;
  57185. // If we found a supported format, we load it immediately and stop the loop
  57186. for (var i = 0; i < urls.length; i++) {
  57187. var url = urls[i];
  57188. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57189. codecSupportedFound = true;
  57190. }
  57191. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57192. codecSupportedFound = true;
  57193. }
  57194. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57195. codecSupportedFound = true;
  57196. }
  57197. if (url.indexOf("blob:") !== -1) {
  57198. codecSupportedFound = true;
  57199. }
  57200. if (codecSupportedFound) {
  57201. // Loading sound using XHR2
  57202. if (!this._streaming) {
  57203. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57204. }
  57205. else {
  57206. this._htmlAudioElement = new Audio(url);
  57207. this._htmlAudioElement.controls = false;
  57208. this._htmlAudioElement.loop = this.loop;
  57209. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57210. this._htmlAudioElement.preload = "auto";
  57211. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57212. _this._isReadyToPlay = true;
  57213. if (_this.autoplay) {
  57214. _this.play();
  57215. }
  57216. if (_this._readyToPlayCallback) {
  57217. _this._readyToPlayCallback();
  57218. }
  57219. });
  57220. document.body.appendChild(this._htmlAudioElement);
  57221. }
  57222. break;
  57223. }
  57224. }
  57225. break;
  57226. default:
  57227. validParameter = false;
  57228. break;
  57229. }
  57230. if (!validParameter) {
  57231. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57232. }
  57233. else {
  57234. if (!codecSupportedFound) {
  57235. this._isReadyToPlay = true;
  57236. // Simulating a ready to play event to avoid breaking code path
  57237. if (this._readyToPlayCallback) {
  57238. window.setTimeout(function () {
  57239. if (_this._readyToPlayCallback) {
  57240. _this._readyToPlayCallback();
  57241. }
  57242. }, 1000);
  57243. }
  57244. }
  57245. }
  57246. }
  57247. }
  57248. else {
  57249. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57250. this._scene.mainSoundTrack.AddSound(this);
  57251. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57252. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57253. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57254. }
  57255. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57256. if (this._readyToPlayCallback) {
  57257. window.setTimeout(function () {
  57258. if (_this._readyToPlayCallback) {
  57259. _this._readyToPlayCallback();
  57260. }
  57261. }, 1000);
  57262. }
  57263. }
  57264. }
  57265. Sound.prototype.dispose = function () {
  57266. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57267. if (this.isPlaying) {
  57268. this.stop();
  57269. }
  57270. this._isReadyToPlay = false;
  57271. if (this.soundTrackId === -1) {
  57272. this._scene.mainSoundTrack.RemoveSound(this);
  57273. }
  57274. else {
  57275. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57276. }
  57277. if (this._soundGain) {
  57278. this._soundGain.disconnect();
  57279. this._soundGain = null;
  57280. }
  57281. if (this._soundPanner) {
  57282. this._soundPanner.disconnect();
  57283. this._soundPanner = null;
  57284. }
  57285. if (this._soundSource) {
  57286. this._soundSource.disconnect();
  57287. this._soundSource = null;
  57288. }
  57289. this._audioBuffer = null;
  57290. if (this._htmlAudioElement) {
  57291. this._htmlAudioElement.pause();
  57292. this._htmlAudioElement.src = "";
  57293. document.body.removeChild(this._htmlAudioElement);
  57294. }
  57295. if (this._connectedMesh && this._registerFunc) {
  57296. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57297. this._connectedMesh = null;
  57298. }
  57299. }
  57300. };
  57301. Sound.prototype.isReady = function () {
  57302. return this._isReadyToPlay;
  57303. };
  57304. Sound.prototype._soundLoaded = function (audioData) {
  57305. var _this = this;
  57306. if (!BABYLON.Engine.audioEngine.audioContext) {
  57307. return;
  57308. }
  57309. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57310. _this._audioBuffer = buffer;
  57311. _this._isReadyToPlay = true;
  57312. if (_this.autoplay) {
  57313. _this.play();
  57314. }
  57315. if (_this._readyToPlayCallback) {
  57316. _this._readyToPlayCallback();
  57317. }
  57318. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57319. };
  57320. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57321. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57322. this._audioBuffer = audioBuffer;
  57323. this._isReadyToPlay = true;
  57324. }
  57325. };
  57326. Sound.prototype.updateOptions = function (options) {
  57327. if (options) {
  57328. this.loop = options.loop || this.loop;
  57329. this.maxDistance = options.maxDistance || this.maxDistance;
  57330. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57331. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57332. this.refDistance = options.refDistance || this.refDistance;
  57333. this.distanceModel = options.distanceModel || this.distanceModel;
  57334. this._playbackRate = options.playbackRate || this._playbackRate;
  57335. this._updateSpatialParameters();
  57336. if (this.isPlaying) {
  57337. if (this._streaming) {
  57338. this._htmlAudioElement.playbackRate = this._playbackRate;
  57339. }
  57340. else {
  57341. if (this._soundSource) {
  57342. this._soundSource.playbackRate.value = this._playbackRate;
  57343. }
  57344. }
  57345. }
  57346. }
  57347. };
  57348. Sound.prototype._createSpatialParameters = function () {
  57349. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57350. if (this._scene.headphone) {
  57351. this._panningModel = "HRTF";
  57352. }
  57353. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57354. this._updateSpatialParameters();
  57355. this._soundPanner.connect(this._ouputAudioNode);
  57356. this._inputAudioNode = this._soundPanner;
  57357. }
  57358. };
  57359. Sound.prototype._updateSpatialParameters = function () {
  57360. if (this.spatialSound && this._soundPanner) {
  57361. if (this.useCustomAttenuation) {
  57362. // Tricks to disable in a way embedded Web Audio attenuation
  57363. this._soundPanner.distanceModel = "linear";
  57364. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57365. this._soundPanner.refDistance = 1;
  57366. this._soundPanner.rolloffFactor = 1;
  57367. this._soundPanner.panningModel = this._panningModel;
  57368. }
  57369. else {
  57370. this._soundPanner.distanceModel = this.distanceModel;
  57371. this._soundPanner.maxDistance = this.maxDistance;
  57372. this._soundPanner.refDistance = this.refDistance;
  57373. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57374. this._soundPanner.panningModel = this._panningModel;
  57375. }
  57376. }
  57377. };
  57378. Sound.prototype.switchPanningModelToHRTF = function () {
  57379. this._panningModel = "HRTF";
  57380. this._switchPanningModel();
  57381. };
  57382. Sound.prototype.switchPanningModelToEqualPower = function () {
  57383. this._panningModel = "equalpower";
  57384. this._switchPanningModel();
  57385. };
  57386. Sound.prototype._switchPanningModel = function () {
  57387. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57388. this._soundPanner.panningModel = this._panningModel;
  57389. }
  57390. };
  57391. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57392. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57393. if (this._isOutputConnected) {
  57394. this._ouputAudioNode.disconnect();
  57395. }
  57396. this._ouputAudioNode.connect(soundTrackAudioNode);
  57397. this._isOutputConnected = true;
  57398. }
  57399. };
  57400. /**
  57401. * Transform this sound into a directional source
  57402. * @param coneInnerAngle Size of the inner cone in degree
  57403. * @param coneOuterAngle Size of the outer cone in degree
  57404. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57405. */
  57406. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57407. if (coneOuterAngle < coneInnerAngle) {
  57408. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57409. return;
  57410. }
  57411. this._coneInnerAngle = coneInnerAngle;
  57412. this._coneOuterAngle = coneOuterAngle;
  57413. this._coneOuterGain = coneOuterGain;
  57414. this._isDirectional = true;
  57415. if (this.isPlaying && this.loop) {
  57416. this.stop();
  57417. this.play();
  57418. }
  57419. };
  57420. Sound.prototype.setPosition = function (newPosition) {
  57421. this._position = newPosition;
  57422. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57423. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57424. }
  57425. };
  57426. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57427. this._localDirection = newLocalDirection;
  57428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57429. this._updateDirection();
  57430. }
  57431. };
  57432. Sound.prototype._updateDirection = function () {
  57433. if (!this._connectedMesh || !this._soundPanner) {
  57434. return;
  57435. }
  57436. var mat = this._connectedMesh.getWorldMatrix();
  57437. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57438. direction.normalize();
  57439. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57440. };
  57441. Sound.prototype.updateDistanceFromListener = function () {
  57442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57443. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57444. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57445. }
  57446. };
  57447. Sound.prototype.setAttenuationFunction = function (callback) {
  57448. this._customAttenuationFunction = callback;
  57449. };
  57450. /**
  57451. * Play the sound
  57452. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57453. * @param offset (optional) Start the sound setting it at a specific time
  57454. */
  57455. Sound.prototype.play = function (time, offset) {
  57456. var _this = this;
  57457. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57458. try {
  57459. if (this._startOffset < 0) {
  57460. time = -this._startOffset;
  57461. this._startOffset = 0;
  57462. }
  57463. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57464. if (!this._soundSource || !this._streamingSource) {
  57465. if (this.spatialSound && this._soundPanner) {
  57466. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57467. if (this._isDirectional) {
  57468. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57469. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57470. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57471. if (this._connectedMesh) {
  57472. this._updateDirection();
  57473. }
  57474. else {
  57475. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57476. }
  57477. }
  57478. }
  57479. }
  57480. if (this._streaming) {
  57481. if (!this._streamingSource) {
  57482. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57483. this._htmlAudioElement.onended = function () { _this._onended(); };
  57484. this._htmlAudioElement.playbackRate = this._playbackRate;
  57485. }
  57486. this._streamingSource.disconnect();
  57487. this._streamingSource.connect(this._inputAudioNode);
  57488. this._htmlAudioElement.play();
  57489. }
  57490. else {
  57491. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57492. this._soundSource.buffer = this._audioBuffer;
  57493. this._soundSource.connect(this._inputAudioNode);
  57494. this._soundSource.loop = this.loop;
  57495. this._soundSource.playbackRate.value = this._playbackRate;
  57496. this._soundSource.onended = function () { _this._onended(); };
  57497. if (this._soundSource.buffer) {
  57498. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57499. }
  57500. }
  57501. this._startTime = startTime;
  57502. this.isPlaying = true;
  57503. this.isPaused = false;
  57504. }
  57505. catch (ex) {
  57506. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57507. }
  57508. }
  57509. };
  57510. Sound.prototype._onended = function () {
  57511. this.isPlaying = false;
  57512. if (this.onended) {
  57513. this.onended();
  57514. }
  57515. };
  57516. /**
  57517. * Stop the sound
  57518. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57519. */
  57520. Sound.prototype.stop = function (time) {
  57521. if (this.isPlaying) {
  57522. if (this._streaming) {
  57523. this._htmlAudioElement.pause();
  57524. // Test needed for Firefox or it will generate an Invalid State Error
  57525. if (this._htmlAudioElement.currentTime > 0) {
  57526. this._htmlAudioElement.currentTime = 0;
  57527. }
  57528. }
  57529. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57530. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57531. this._soundSource.stop(stopTime);
  57532. this._soundSource.onended = function () { };
  57533. if (!this.isPaused) {
  57534. this._startOffset = 0;
  57535. }
  57536. }
  57537. this.isPlaying = false;
  57538. }
  57539. };
  57540. Sound.prototype.pause = function () {
  57541. if (this.isPlaying) {
  57542. this.isPaused = true;
  57543. if (this._streaming) {
  57544. this._htmlAudioElement.pause();
  57545. }
  57546. else if (BABYLON.Engine.audioEngine.audioContext) {
  57547. this.stop(0);
  57548. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57549. }
  57550. }
  57551. };
  57552. Sound.prototype.setVolume = function (newVolume, time) {
  57553. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57554. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57555. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57556. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57557. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57558. }
  57559. else {
  57560. this._soundGain.gain.value = newVolume;
  57561. }
  57562. }
  57563. this._volume = newVolume;
  57564. };
  57565. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57566. this._playbackRate = newPlaybackRate;
  57567. if (this.isPlaying) {
  57568. if (this._streaming) {
  57569. this._htmlAudioElement.playbackRate = this._playbackRate;
  57570. }
  57571. else if (this._soundSource) {
  57572. this._soundSource.playbackRate.value = this._playbackRate;
  57573. }
  57574. }
  57575. };
  57576. Sound.prototype.getVolume = function () {
  57577. return this._volume;
  57578. };
  57579. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57580. var _this = this;
  57581. if (this._connectedMesh && this._registerFunc) {
  57582. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57583. this._registerFunc = null;
  57584. }
  57585. this._connectedMesh = meshToConnectTo;
  57586. if (!this.spatialSound) {
  57587. this.spatialSound = true;
  57588. this._createSpatialParameters();
  57589. if (this.isPlaying && this.loop) {
  57590. this.stop();
  57591. this.play();
  57592. }
  57593. }
  57594. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57595. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57596. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57597. };
  57598. Sound.prototype.detachFromMesh = function () {
  57599. if (this._connectedMesh && this._registerFunc) {
  57600. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57601. this._registerFunc = null;
  57602. this._connectedMesh = null;
  57603. }
  57604. };
  57605. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57606. if (!node.getBoundingInfo) {
  57607. return;
  57608. }
  57609. var mesh = node;
  57610. var boundingInfo = mesh.getBoundingInfo();
  57611. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57612. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57613. this._updateDirection();
  57614. }
  57615. };
  57616. Sound.prototype.clone = function () {
  57617. var _this = this;
  57618. if (!this._streaming) {
  57619. var setBufferAndRun = function () {
  57620. if (_this._isReadyToPlay) {
  57621. clonedSound._audioBuffer = _this.getAudioBuffer();
  57622. clonedSound._isReadyToPlay = true;
  57623. if (clonedSound.autoplay) {
  57624. clonedSound.play();
  57625. }
  57626. }
  57627. else {
  57628. window.setTimeout(setBufferAndRun, 300);
  57629. }
  57630. };
  57631. var currentOptions = {
  57632. autoplay: this.autoplay, loop: this.loop,
  57633. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57634. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57635. refDistance: this.refDistance, distanceModel: this.distanceModel
  57636. };
  57637. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57638. if (this.useCustomAttenuation) {
  57639. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57640. }
  57641. clonedSound.setPosition(this._position);
  57642. clonedSound.setPlaybackRate(this._playbackRate);
  57643. setBufferAndRun();
  57644. return clonedSound;
  57645. }
  57646. else {
  57647. return null;
  57648. }
  57649. };
  57650. Sound.prototype.getAudioBuffer = function () {
  57651. return this._audioBuffer;
  57652. };
  57653. Sound.prototype.serialize = function () {
  57654. var serializationObject = {
  57655. name: this.name,
  57656. url: this.name,
  57657. autoplay: this.autoplay,
  57658. loop: this.loop,
  57659. volume: this._volume,
  57660. spatialSound: this.spatialSound,
  57661. maxDistance: this.maxDistance,
  57662. rolloffFactor: this.rolloffFactor,
  57663. refDistance: this.refDistance,
  57664. distanceModel: this.distanceModel,
  57665. playbackRate: this._playbackRate,
  57666. panningModel: this._panningModel,
  57667. soundTrackId: this.soundTrackId
  57668. };
  57669. if (this.spatialSound) {
  57670. if (this._connectedMesh)
  57671. serializationObject.connectedMeshId = this._connectedMesh.id;
  57672. serializationObject.position = this._position.asArray();
  57673. serializationObject.refDistance = this.refDistance;
  57674. serializationObject.distanceModel = this.distanceModel;
  57675. serializationObject.isDirectional = this._isDirectional;
  57676. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57677. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57678. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57679. serializationObject.coneOuterGain = this._coneOuterGain;
  57680. }
  57681. return serializationObject;
  57682. };
  57683. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57684. var soundName = parsedSound.name;
  57685. var soundUrl;
  57686. if (parsedSound.url) {
  57687. soundUrl = rootUrl + parsedSound.url;
  57688. }
  57689. else {
  57690. soundUrl = rootUrl + soundName;
  57691. }
  57692. var options = {
  57693. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57694. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57695. rolloffFactor: parsedSound.rolloffFactor,
  57696. refDistance: parsedSound.refDistance,
  57697. distanceModel: parsedSound.distanceModel,
  57698. playbackRate: parsedSound.playbackRate
  57699. };
  57700. var newSound;
  57701. if (!sourceSound) {
  57702. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57703. scene._addPendingData(newSound);
  57704. }
  57705. else {
  57706. var setBufferAndRun = function () {
  57707. if (sourceSound._isReadyToPlay) {
  57708. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57709. newSound._isReadyToPlay = true;
  57710. if (newSound.autoplay) {
  57711. newSound.play();
  57712. }
  57713. }
  57714. else {
  57715. window.setTimeout(setBufferAndRun, 300);
  57716. }
  57717. };
  57718. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57719. setBufferAndRun();
  57720. }
  57721. if (parsedSound.position) {
  57722. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57723. newSound.setPosition(soundPosition);
  57724. }
  57725. if (parsedSound.isDirectional) {
  57726. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57727. if (parsedSound.localDirectionToMesh) {
  57728. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57729. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57730. }
  57731. }
  57732. if (parsedSound.connectedMeshId) {
  57733. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57734. if (connectedMesh) {
  57735. newSound.attachToMesh(connectedMesh);
  57736. }
  57737. }
  57738. return newSound;
  57739. };
  57740. return Sound;
  57741. }());
  57742. BABYLON.Sound = Sound;
  57743. })(BABYLON || (BABYLON = {}));
  57744. //# sourceMappingURL=babylon.sound.js.map
  57745. var BABYLON;
  57746. (function (BABYLON) {
  57747. var SoundTrack = /** @class */ (function () {
  57748. function SoundTrack(scene, options) {
  57749. this.id = -1;
  57750. this._isMainTrack = false;
  57751. this._isInitialized = false;
  57752. this._scene = scene;
  57753. this.soundCollection = new Array();
  57754. this._options = options;
  57755. if (!this._isMainTrack) {
  57756. this._scene.soundTracks.push(this);
  57757. this.id = this._scene.soundTracks.length - 1;
  57758. }
  57759. }
  57760. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57761. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57762. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57763. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57764. if (this._options) {
  57765. if (this._options.volume) {
  57766. this._outputAudioNode.gain.value = this._options.volume;
  57767. }
  57768. if (this._options.mainTrack) {
  57769. this._isMainTrack = this._options.mainTrack;
  57770. }
  57771. }
  57772. this._isInitialized = true;
  57773. }
  57774. };
  57775. SoundTrack.prototype.dispose = function () {
  57776. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57777. if (this._connectedAnalyser) {
  57778. this._connectedAnalyser.stopDebugCanvas();
  57779. }
  57780. while (this.soundCollection.length) {
  57781. this.soundCollection[0].dispose();
  57782. }
  57783. if (this._outputAudioNode) {
  57784. this._outputAudioNode.disconnect();
  57785. }
  57786. this._outputAudioNode = null;
  57787. }
  57788. };
  57789. SoundTrack.prototype.AddSound = function (sound) {
  57790. if (!this._isInitialized) {
  57791. this._initializeSoundTrackAudioGraph();
  57792. }
  57793. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57794. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57795. }
  57796. if (sound.soundTrackId) {
  57797. if (sound.soundTrackId === -1) {
  57798. this._scene.mainSoundTrack.RemoveSound(sound);
  57799. }
  57800. else {
  57801. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57802. }
  57803. }
  57804. this.soundCollection.push(sound);
  57805. sound.soundTrackId = this.id;
  57806. };
  57807. SoundTrack.prototype.RemoveSound = function (sound) {
  57808. var index = this.soundCollection.indexOf(sound);
  57809. if (index !== -1) {
  57810. this.soundCollection.splice(index, 1);
  57811. }
  57812. };
  57813. SoundTrack.prototype.setVolume = function (newVolume) {
  57814. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57815. this._outputAudioNode.gain.value = newVolume;
  57816. }
  57817. };
  57818. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57819. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57820. for (var i = 0; i < this.soundCollection.length; i++) {
  57821. this.soundCollection[i].switchPanningModelToHRTF();
  57822. }
  57823. }
  57824. };
  57825. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57826. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57827. for (var i = 0; i < this.soundCollection.length; i++) {
  57828. this.soundCollection[i].switchPanningModelToEqualPower();
  57829. }
  57830. }
  57831. };
  57832. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57833. if (this._connectedAnalyser) {
  57834. this._connectedAnalyser.stopDebugCanvas();
  57835. }
  57836. this._connectedAnalyser = analyser;
  57837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57838. this._outputAudioNode.disconnect();
  57839. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57840. }
  57841. };
  57842. return SoundTrack;
  57843. }());
  57844. BABYLON.SoundTrack = SoundTrack;
  57845. })(BABYLON || (BABYLON = {}));
  57846. //# sourceMappingURL=babylon.soundtrack.js.map
  57847. var BABYLON;
  57848. (function (BABYLON) {
  57849. var Analyser = /** @class */ (function () {
  57850. function Analyser(scene) {
  57851. this.SMOOTHING = 0.75;
  57852. this.FFT_SIZE = 512;
  57853. this.BARGRAPHAMPLITUDE = 256;
  57854. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57855. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57856. this._scene = scene;
  57857. this._audioEngine = BABYLON.Engine.audioEngine;
  57858. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57859. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57860. this._webAudioAnalyser.minDecibels = -140;
  57861. this._webAudioAnalyser.maxDecibels = 0;
  57862. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57863. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57864. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57865. }
  57866. }
  57867. Analyser.prototype.getFrequencyBinCount = function () {
  57868. if (this._audioEngine.canUseWebAudio) {
  57869. return this._webAudioAnalyser.frequencyBinCount;
  57870. }
  57871. else {
  57872. return 0;
  57873. }
  57874. };
  57875. Analyser.prototype.getByteFrequencyData = function () {
  57876. if (this._audioEngine.canUseWebAudio) {
  57877. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57878. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57879. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57880. }
  57881. return this._byteFreqs;
  57882. };
  57883. Analyser.prototype.getByteTimeDomainData = function () {
  57884. if (this._audioEngine.canUseWebAudio) {
  57885. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57886. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57887. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57888. }
  57889. return this._byteTime;
  57890. };
  57891. Analyser.prototype.getFloatFrequencyData = function () {
  57892. if (this._audioEngine.canUseWebAudio) {
  57893. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57894. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57895. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57896. }
  57897. return this._floatFreqs;
  57898. };
  57899. Analyser.prototype.drawDebugCanvas = function () {
  57900. var _this = this;
  57901. if (this._audioEngine.canUseWebAudio) {
  57902. if (!this._debugCanvas) {
  57903. this._debugCanvas = document.createElement("canvas");
  57904. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57905. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57906. this._debugCanvas.style.position = "absolute";
  57907. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57908. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57909. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57910. document.body.appendChild(this._debugCanvas);
  57911. this._registerFunc = function () {
  57912. _this.drawDebugCanvas();
  57913. };
  57914. this._scene.registerBeforeRender(this._registerFunc);
  57915. }
  57916. if (this._registerFunc && this._debugCanvasContext) {
  57917. var workingArray = this.getByteFrequencyData();
  57918. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57919. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57920. // Draw the frequency domain chart.
  57921. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57922. var value = workingArray[i];
  57923. var percent = value / this.BARGRAPHAMPLITUDE;
  57924. var height = this.DEBUGCANVASSIZE.height * percent;
  57925. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57926. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57927. var hue = i / this.getFrequencyBinCount() * 360;
  57928. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57929. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57930. }
  57931. }
  57932. }
  57933. };
  57934. Analyser.prototype.stopDebugCanvas = function () {
  57935. if (this._debugCanvas) {
  57936. if (this._registerFunc) {
  57937. this._scene.unregisterBeforeRender(this._registerFunc);
  57938. this._registerFunc = null;
  57939. }
  57940. document.body.removeChild(this._debugCanvas);
  57941. this._debugCanvas = null;
  57942. this._debugCanvasContext = null;
  57943. }
  57944. };
  57945. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57946. if (this._audioEngine.canUseWebAudio) {
  57947. inputAudioNode.connect(this._webAudioAnalyser);
  57948. this._webAudioAnalyser.connect(outputAudioNode);
  57949. }
  57950. };
  57951. Analyser.prototype.dispose = function () {
  57952. if (this._audioEngine.canUseWebAudio) {
  57953. this._webAudioAnalyser.disconnect();
  57954. }
  57955. };
  57956. return Analyser;
  57957. }());
  57958. BABYLON.Analyser = Analyser;
  57959. })(BABYLON || (BABYLON = {}));
  57960. //# sourceMappingURL=babylon.analyser.js.map
  57961. var BABYLON;
  57962. (function (BABYLON) {
  57963. var CubeTexture = /** @class */ (function (_super) {
  57964. __extends(CubeTexture, _super);
  57965. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57966. if (extensions === void 0) { extensions = null; }
  57967. if (noMipmap === void 0) { noMipmap = false; }
  57968. if (files === void 0) { files = null; }
  57969. if (onLoad === void 0) { onLoad = null; }
  57970. if (onError === void 0) { onError = null; }
  57971. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57972. if (prefiltered === void 0) { prefiltered = false; }
  57973. if (forcedExtension === void 0) { forcedExtension = null; }
  57974. var _this = _super.call(this, scene) || this;
  57975. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57976. /**
  57977. * Gets or sets the center of the bounding box associated with the cube texture
  57978. * It must define where the camera used to render the texture was set
  57979. */
  57980. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57981. _this.name = rootUrl;
  57982. _this.url = rootUrl;
  57983. _this._noMipmap = noMipmap;
  57984. _this.hasAlpha = false;
  57985. _this._format = format;
  57986. _this._prefiltered = prefiltered;
  57987. _this.isCube = true;
  57988. _this._textureMatrix = BABYLON.Matrix.Identity();
  57989. if (prefiltered) {
  57990. _this.gammaSpace = false;
  57991. }
  57992. if (!rootUrl && !files) {
  57993. return _this;
  57994. }
  57995. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57996. var lastDot = rootUrl.lastIndexOf(".");
  57997. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57998. var isDDS = (extension === ".dds");
  57999. if (!files) {
  58000. if (!isDDS && !extensions) {
  58001. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58002. }
  58003. files = [];
  58004. if (extensions) {
  58005. for (var index = 0; index < extensions.length; index++) {
  58006. files.push(rootUrl + extensions[index]);
  58007. }
  58008. }
  58009. }
  58010. _this._files = files;
  58011. if (!_this._texture) {
  58012. if (!scene.useDelayedTextureLoading) {
  58013. if (prefiltered) {
  58014. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58015. }
  58016. else {
  58017. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58018. }
  58019. }
  58020. else {
  58021. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58022. }
  58023. }
  58024. else if (onLoad) {
  58025. if (_this._texture.isReady) {
  58026. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58027. }
  58028. else {
  58029. _this._texture.onLoadedObservable.add(onLoad);
  58030. }
  58031. }
  58032. return _this;
  58033. }
  58034. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58035. get: function () {
  58036. return this._boundingBoxSize;
  58037. },
  58038. /**
  58039. * Gets or sets the size of the bounding box associated with the cube texture
  58040. * When defined, the cubemap will switch to local mode
  58041. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58042. * @example https://www.babylonjs-playground.com/#RNASML
  58043. */
  58044. set: function (value) {
  58045. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58046. return;
  58047. }
  58048. this._boundingBoxSize = value;
  58049. var scene = this.getScene();
  58050. if (scene) {
  58051. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58052. }
  58053. },
  58054. enumerable: true,
  58055. configurable: true
  58056. });
  58057. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58058. var rootUrlKey = "";
  58059. files.forEach(function (url) { return rootUrlKey += url; });
  58060. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58061. };
  58062. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58063. if (forcedExtension === void 0) { forcedExtension = null; }
  58064. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58065. };
  58066. // Methods
  58067. CubeTexture.prototype.delayLoad = function () {
  58068. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58069. return;
  58070. }
  58071. var scene = this.getScene();
  58072. if (!scene) {
  58073. return;
  58074. }
  58075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58076. this._texture = this._getFromCache(this.url, this._noMipmap);
  58077. if (!this._texture) {
  58078. if (this._prefiltered) {
  58079. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58080. }
  58081. else {
  58082. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58083. }
  58084. }
  58085. };
  58086. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58087. return this._textureMatrix;
  58088. };
  58089. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58090. this._textureMatrix = value;
  58091. };
  58092. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58093. var texture = BABYLON.SerializationHelper.Parse(function () {
  58094. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58095. }, parsedTexture, scene);
  58096. // Local Cubemaps
  58097. if (parsedTexture.boundingBoxPosition) {
  58098. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58099. }
  58100. if (parsedTexture.boundingBoxSize) {
  58101. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58102. }
  58103. // Animations
  58104. if (parsedTexture.animations) {
  58105. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58106. var parsedAnimation = parsedTexture.animations[animationIndex];
  58107. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58108. }
  58109. }
  58110. return texture;
  58111. };
  58112. CubeTexture.prototype.clone = function () {
  58113. var _this = this;
  58114. return BABYLON.SerializationHelper.Clone(function () {
  58115. var scene = _this.getScene();
  58116. if (!scene) {
  58117. return _this;
  58118. }
  58119. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58120. }, this);
  58121. };
  58122. return CubeTexture;
  58123. }(BABYLON.BaseTexture));
  58124. BABYLON.CubeTexture = CubeTexture;
  58125. })(BABYLON || (BABYLON = {}));
  58126. //# sourceMappingURL=babylon.cubeTexture.js.map
  58127. var BABYLON;
  58128. (function (BABYLON) {
  58129. var RenderTargetTexture = /** @class */ (function (_super) {
  58130. __extends(RenderTargetTexture, _super);
  58131. /**
  58132. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58133. * or used a shadow, depth texture...
  58134. * @param name The friendly name of the texture
  58135. * @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)
  58136. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58137. * @param generateMipMaps True if mip maps need to be generated after render.
  58138. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58139. * @param type The type of the buffer in the RTT (int, half float, float...)
  58140. * @param isCube True if a cube texture needs to be created
  58141. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58142. * @param generateDepthBuffer True to generate a depth buffer
  58143. * @param generateStencilBuffer True to generate a stencil buffer
  58144. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58145. */
  58146. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58147. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58148. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58149. if (isCube === void 0) { isCube = false; }
  58150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58151. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58152. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58153. if (isMulti === void 0) { isMulti = false; }
  58154. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58155. _this.isCube = isCube;
  58156. /**
  58157. * Use this list to define the list of mesh you want to render.
  58158. */
  58159. _this.renderList = new Array();
  58160. _this.renderParticles = true;
  58161. _this.renderSprites = false;
  58162. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58163. _this.ignoreCameraViewport = false;
  58164. // Events
  58165. /**
  58166. * An event triggered when the texture is unbind.
  58167. * @type {BABYLON.Observable}
  58168. */
  58169. _this.onBeforeBindObservable = new BABYLON.Observable();
  58170. /**
  58171. * An event triggered when the texture is unbind.
  58172. * @type {BABYLON.Observable}
  58173. */
  58174. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58175. /**
  58176. * An event triggered before rendering the texture
  58177. * @type {BABYLON.Observable}
  58178. */
  58179. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58180. /**
  58181. * An event triggered after rendering the texture
  58182. * @type {BABYLON.Observable}
  58183. */
  58184. _this.onAfterRenderObservable = new BABYLON.Observable();
  58185. /**
  58186. * An event triggered after the texture clear
  58187. * @type {BABYLON.Observable}
  58188. */
  58189. _this.onClearObservable = new BABYLON.Observable();
  58190. _this._currentRefreshId = -1;
  58191. _this._refreshRate = 1;
  58192. _this._samples = 1;
  58193. /**
  58194. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58195. * It must define where the camera used to render the texture is set
  58196. */
  58197. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58198. scene = _this.getScene();
  58199. if (!scene) {
  58200. return _this;
  58201. }
  58202. _this._engine = scene.getEngine();
  58203. _this.name = name;
  58204. _this.isRenderTarget = true;
  58205. _this._initialSizeParameter = size;
  58206. _this._processSizeParameter(size);
  58207. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58208. });
  58209. _this._generateMipMaps = generateMipMaps ? true : false;
  58210. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58211. // Rendering groups
  58212. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58213. if (isMulti) {
  58214. return _this;
  58215. }
  58216. _this._renderTargetOptions = {
  58217. generateMipMaps: generateMipMaps,
  58218. type: type,
  58219. samplingMode: samplingMode,
  58220. generateDepthBuffer: generateDepthBuffer,
  58221. generateStencilBuffer: generateStencilBuffer
  58222. };
  58223. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58224. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58225. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58226. }
  58227. if (isCube) {
  58228. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58229. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58230. _this._textureMatrix = BABYLON.Matrix.Identity();
  58231. }
  58232. else {
  58233. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58234. }
  58235. return _this;
  58236. }
  58237. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58238. get: function () {
  58239. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58240. },
  58241. enumerable: true,
  58242. configurable: true
  58243. });
  58244. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58245. get: function () {
  58246. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58247. },
  58248. enumerable: true,
  58249. configurable: true
  58250. });
  58251. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58252. get: function () {
  58253. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58254. },
  58255. enumerable: true,
  58256. configurable: true
  58257. });
  58258. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58259. set: function (callback) {
  58260. if (this._onAfterUnbindObserver) {
  58261. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58262. }
  58263. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58264. },
  58265. enumerable: true,
  58266. configurable: true
  58267. });
  58268. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58269. set: function (callback) {
  58270. if (this._onBeforeRenderObserver) {
  58271. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58272. }
  58273. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58274. },
  58275. enumerable: true,
  58276. configurable: true
  58277. });
  58278. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58279. set: function (callback) {
  58280. if (this._onAfterRenderObserver) {
  58281. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58282. }
  58283. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58284. },
  58285. enumerable: true,
  58286. configurable: true
  58287. });
  58288. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58289. set: function (callback) {
  58290. if (this._onClearObserver) {
  58291. this.onClearObservable.remove(this._onClearObserver);
  58292. }
  58293. this._onClearObserver = this.onClearObservable.add(callback);
  58294. },
  58295. enumerable: true,
  58296. configurable: true
  58297. });
  58298. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58299. get: function () {
  58300. return this._renderTargetOptions;
  58301. },
  58302. enumerable: true,
  58303. configurable: true
  58304. });
  58305. RenderTargetTexture.prototype._onRatioRescale = function () {
  58306. if (this._sizeRatio) {
  58307. this.resize(this._initialSizeParameter);
  58308. }
  58309. };
  58310. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58311. get: function () {
  58312. return this._boundingBoxSize;
  58313. },
  58314. /**
  58315. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58316. * When defined, the cubemap will switch to local mode
  58317. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58318. * @example https://www.babylonjs-playground.com/#RNASML
  58319. */
  58320. set: function (value) {
  58321. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58322. return;
  58323. }
  58324. this._boundingBoxSize = value;
  58325. var scene = this.getScene();
  58326. if (scene) {
  58327. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58328. }
  58329. },
  58330. enumerable: true,
  58331. configurable: true
  58332. });
  58333. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58334. if (size.ratio) {
  58335. this._sizeRatio = size.ratio;
  58336. this._size = {
  58337. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58338. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58339. };
  58340. }
  58341. else {
  58342. this._size = size;
  58343. }
  58344. };
  58345. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58346. get: function () {
  58347. return this._samples;
  58348. },
  58349. set: function (value) {
  58350. if (this._samples === value) {
  58351. return;
  58352. }
  58353. var scene = this.getScene();
  58354. if (!scene) {
  58355. return;
  58356. }
  58357. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58358. },
  58359. enumerable: true,
  58360. configurable: true
  58361. });
  58362. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58363. this._currentRefreshId = -1;
  58364. };
  58365. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58366. get: function () {
  58367. return this._refreshRate;
  58368. },
  58369. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58370. set: function (value) {
  58371. this._refreshRate = value;
  58372. this.resetRefreshCounter();
  58373. },
  58374. enumerable: true,
  58375. configurable: true
  58376. });
  58377. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58378. if (!this._postProcessManager) {
  58379. var scene = this.getScene();
  58380. if (!scene) {
  58381. return;
  58382. }
  58383. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58384. this._postProcesses = new Array();
  58385. }
  58386. this._postProcesses.push(postProcess);
  58387. this._postProcesses[0].autoClear = false;
  58388. };
  58389. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58390. if (!this._postProcesses) {
  58391. return;
  58392. }
  58393. if (dispose) {
  58394. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58395. var postProcess = _a[_i];
  58396. postProcess.dispose();
  58397. }
  58398. }
  58399. this._postProcesses = [];
  58400. };
  58401. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58402. if (!this._postProcesses) {
  58403. return;
  58404. }
  58405. var index = this._postProcesses.indexOf(postProcess);
  58406. if (index === -1) {
  58407. return;
  58408. }
  58409. this._postProcesses.splice(index, 1);
  58410. if (this._postProcesses.length > 0) {
  58411. this._postProcesses[0].autoClear = false;
  58412. }
  58413. };
  58414. RenderTargetTexture.prototype._shouldRender = function () {
  58415. if (this._currentRefreshId === -1) {
  58416. this._currentRefreshId = 1;
  58417. return true;
  58418. }
  58419. if (this.refreshRate === this._currentRefreshId) {
  58420. this._currentRefreshId = 1;
  58421. return true;
  58422. }
  58423. this._currentRefreshId++;
  58424. return false;
  58425. };
  58426. RenderTargetTexture.prototype.getRenderSize = function () {
  58427. if (this._size.width) {
  58428. return this._size.width;
  58429. }
  58430. return this._size;
  58431. };
  58432. RenderTargetTexture.prototype.getRenderWidth = function () {
  58433. if (this._size.width) {
  58434. return this._size.width;
  58435. }
  58436. return this._size;
  58437. };
  58438. RenderTargetTexture.prototype.getRenderHeight = function () {
  58439. if (this._size.width) {
  58440. return this._size.height;
  58441. }
  58442. return this._size;
  58443. };
  58444. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58445. get: function () {
  58446. return true;
  58447. },
  58448. enumerable: true,
  58449. configurable: true
  58450. });
  58451. RenderTargetTexture.prototype.scale = function (ratio) {
  58452. var newSize = this.getRenderSize() * ratio;
  58453. this.resize(newSize);
  58454. };
  58455. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58456. if (this.isCube) {
  58457. return this._textureMatrix;
  58458. }
  58459. return _super.prototype.getReflectionTextureMatrix.call(this);
  58460. };
  58461. RenderTargetTexture.prototype.resize = function (size) {
  58462. this.releaseInternalTexture();
  58463. var scene = this.getScene();
  58464. if (!scene) {
  58465. return;
  58466. }
  58467. this._processSizeParameter(size);
  58468. if (this.isCube) {
  58469. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58470. }
  58471. else {
  58472. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58473. }
  58474. };
  58475. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58476. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58477. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58478. var scene = this.getScene();
  58479. if (!scene) {
  58480. return;
  58481. }
  58482. var engine = scene.getEngine();
  58483. if (this.useCameraPostProcesses !== undefined) {
  58484. useCameraPostProcess = this.useCameraPostProcesses;
  58485. }
  58486. if (this._waitingRenderList) {
  58487. this.renderList = [];
  58488. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58489. var id = this._waitingRenderList[index];
  58490. var mesh_1 = scene.getMeshByID(id);
  58491. if (mesh_1) {
  58492. this.renderList.push(mesh_1);
  58493. }
  58494. }
  58495. delete this._waitingRenderList;
  58496. }
  58497. // Is predicate defined?
  58498. if (this.renderListPredicate) {
  58499. if (this.renderList) {
  58500. this.renderList.splice(0); // Clear previous renderList
  58501. }
  58502. else {
  58503. this.renderList = [];
  58504. }
  58505. var scene = this.getScene();
  58506. if (!scene) {
  58507. return;
  58508. }
  58509. var sceneMeshes = scene.meshes;
  58510. for (var index = 0; index < sceneMeshes.length; index++) {
  58511. var mesh = sceneMeshes[index];
  58512. if (this.renderListPredicate(mesh)) {
  58513. this.renderList.push(mesh);
  58514. }
  58515. }
  58516. }
  58517. this.onBeforeBindObservable.notifyObservers(this);
  58518. // Set custom projection.
  58519. // Needs to be before binding to prevent changing the aspect ratio.
  58520. var camera;
  58521. if (this.activeCamera) {
  58522. camera = this.activeCamera;
  58523. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58524. if (this.activeCamera !== scene.activeCamera) {
  58525. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58526. }
  58527. }
  58528. else {
  58529. camera = scene.activeCamera;
  58530. if (camera) {
  58531. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58532. }
  58533. }
  58534. // Prepare renderingManager
  58535. this._renderingManager.reset();
  58536. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58537. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58538. var sceneRenderId = scene.getRenderId();
  58539. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58540. var mesh = currentRenderList[meshIndex];
  58541. if (mesh) {
  58542. if (!mesh.isReady()) {
  58543. // Reset _currentRefreshId
  58544. this.resetRefreshCounter();
  58545. continue;
  58546. }
  58547. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58548. var isMasked = void 0;
  58549. if (!this.renderList && camera) {
  58550. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58551. }
  58552. else {
  58553. isMasked = false;
  58554. }
  58555. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58556. mesh._activate(sceneRenderId);
  58557. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58558. var subMesh = mesh.subMeshes[subIndex];
  58559. scene._activeIndices.addCount(subMesh.indexCount, false);
  58560. this._renderingManager.dispatch(subMesh, mesh);
  58561. }
  58562. }
  58563. }
  58564. }
  58565. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58566. var particleSystem = scene.particleSystems[particleIndex];
  58567. var emitter = particleSystem.emitter;
  58568. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58569. continue;
  58570. }
  58571. if (currentRenderList.indexOf(emitter) >= 0) {
  58572. this._renderingManager.dispatchParticles(particleSystem);
  58573. }
  58574. }
  58575. if (this.isCube) {
  58576. for (var face = 0; face < 6; face++) {
  58577. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58578. scene.incrementRenderId();
  58579. scene.resetCachedMaterial();
  58580. }
  58581. }
  58582. else {
  58583. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58584. }
  58585. this.onAfterUnbindObservable.notifyObservers(this);
  58586. if (scene.activeCamera) {
  58587. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58588. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58589. }
  58590. engine.setViewport(scene.activeCamera.viewport);
  58591. }
  58592. scene.resetCachedMaterial();
  58593. };
  58594. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58595. var minimum = 128;
  58596. var x = renderDimension * scale;
  58597. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58598. // Ensure we don't exceed the render dimension (while staying POT)
  58599. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58600. };
  58601. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58602. var _this = this;
  58603. if (!this._texture) {
  58604. return;
  58605. }
  58606. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58607. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58608. });
  58609. };
  58610. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58611. var scene = this.getScene();
  58612. if (!scene) {
  58613. return;
  58614. }
  58615. var engine = scene.getEngine();
  58616. if (!this._texture) {
  58617. return;
  58618. }
  58619. // Bind
  58620. if (this._postProcessManager) {
  58621. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58622. }
  58623. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58624. if (this._texture) {
  58625. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58626. }
  58627. }
  58628. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58629. // Clear
  58630. if (this.onClearObservable.hasObservers()) {
  58631. this.onClearObservable.notifyObservers(engine);
  58632. }
  58633. else {
  58634. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58635. }
  58636. if (!this._doNotChangeAspectRatio) {
  58637. scene.updateTransformMatrix(true);
  58638. }
  58639. // Render
  58640. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58641. if (this._postProcessManager) {
  58642. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58643. }
  58644. else if (useCameraPostProcess) {
  58645. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58646. }
  58647. if (!this._doNotChangeAspectRatio) {
  58648. scene.updateTransformMatrix(true);
  58649. }
  58650. // Dump ?
  58651. if (dumpForDebug) {
  58652. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58653. }
  58654. // Unbind
  58655. if (!this.isCube || faceIndex === 5) {
  58656. if (this.isCube) {
  58657. if (faceIndex === 5) {
  58658. engine.generateMipMapsForCubemap(this._texture);
  58659. }
  58660. }
  58661. this.unbindFrameBuffer(engine, faceIndex);
  58662. }
  58663. else {
  58664. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58665. }
  58666. };
  58667. /**
  58668. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58669. * This allowed control for front to back rendering or reversly depending of the special needs.
  58670. *
  58671. * @param renderingGroupId The rendering group id corresponding to its index
  58672. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58673. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58674. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58675. */
  58676. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58677. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58678. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58679. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58680. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58681. };
  58682. /**
  58683. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58684. *
  58685. * @param renderingGroupId The rendering group id corresponding to its index
  58686. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58687. */
  58688. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58689. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58690. };
  58691. RenderTargetTexture.prototype.clone = function () {
  58692. var textureSize = this.getSize();
  58693. 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);
  58694. // Base texture
  58695. newTexture.hasAlpha = this.hasAlpha;
  58696. newTexture.level = this.level;
  58697. // RenderTarget Texture
  58698. newTexture.coordinatesMode = this.coordinatesMode;
  58699. if (this.renderList) {
  58700. newTexture.renderList = this.renderList.slice(0);
  58701. }
  58702. return newTexture;
  58703. };
  58704. RenderTargetTexture.prototype.serialize = function () {
  58705. if (!this.name) {
  58706. return null;
  58707. }
  58708. var serializationObject = _super.prototype.serialize.call(this);
  58709. serializationObject.renderTargetSize = this.getRenderSize();
  58710. serializationObject.renderList = [];
  58711. if (this.renderList) {
  58712. for (var index = 0; index < this.renderList.length; index++) {
  58713. serializationObject.renderList.push(this.renderList[index].id);
  58714. }
  58715. }
  58716. return serializationObject;
  58717. };
  58718. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58719. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58720. var objBuffer = this.getInternalTexture();
  58721. var scene = this.getScene();
  58722. if (objBuffer && scene) {
  58723. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58724. }
  58725. };
  58726. RenderTargetTexture.prototype.dispose = function () {
  58727. if (this._postProcessManager) {
  58728. this._postProcessManager.dispose();
  58729. this._postProcessManager = null;
  58730. }
  58731. this.clearPostProcesses(true);
  58732. if (this._resizeObserver) {
  58733. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58734. this._resizeObserver = null;
  58735. }
  58736. this.renderList = null;
  58737. // Remove from custom render targets
  58738. var scene = this.getScene();
  58739. if (!scene) {
  58740. return;
  58741. }
  58742. var index = scene.customRenderTargets.indexOf(this);
  58743. if (index >= 0) {
  58744. scene.customRenderTargets.splice(index, 1);
  58745. }
  58746. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58747. var camera = _a[_i];
  58748. index = camera.customRenderTargets.indexOf(this);
  58749. if (index >= 0) {
  58750. camera.customRenderTargets.splice(index, 1);
  58751. }
  58752. }
  58753. _super.prototype.dispose.call(this);
  58754. };
  58755. RenderTargetTexture.prototype._rebuild = function () {
  58756. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58757. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58758. }
  58759. if (this._postProcessManager) {
  58760. this._postProcessManager._rebuild();
  58761. }
  58762. };
  58763. /**
  58764. * Clear the info related to rendering groups preventing retention point in material dispose.
  58765. */
  58766. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58767. if (this._renderingManager) {
  58768. this._renderingManager.freeRenderingGroups();
  58769. }
  58770. };
  58771. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58772. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58773. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58774. return RenderTargetTexture;
  58775. }(BABYLON.Texture));
  58776. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58777. })(BABYLON || (BABYLON = {}));
  58778. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58779. var BABYLON;
  58780. (function (BABYLON) {
  58781. ;
  58782. var MultiRenderTarget = /** @class */ (function (_super) {
  58783. __extends(MultiRenderTarget, _super);
  58784. function MultiRenderTarget(name, size, count, scene, options) {
  58785. var _this = this;
  58786. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58787. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58788. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58789. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58790. _this._engine = scene.getEngine();
  58791. if (!_this.isSupported) {
  58792. _this.dispose();
  58793. return;
  58794. }
  58795. var types = [];
  58796. var samplingModes = [];
  58797. for (var i = 0; i < count; i++) {
  58798. if (options && options.types && options.types[i] !== undefined) {
  58799. types.push(options.types[i]);
  58800. }
  58801. else {
  58802. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58803. }
  58804. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58805. samplingModes.push(options.samplingModes[i]);
  58806. }
  58807. else {
  58808. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58809. }
  58810. }
  58811. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58812. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58813. _this._size = size;
  58814. _this._multiRenderTargetOptions = {
  58815. samplingModes: samplingModes,
  58816. generateMipMaps: generateMipMaps,
  58817. generateDepthBuffer: generateDepthBuffer,
  58818. generateStencilBuffer: generateStencilBuffer,
  58819. generateDepthTexture: generateDepthTexture,
  58820. types: types,
  58821. textureCount: count
  58822. };
  58823. _this._createInternalTextures();
  58824. _this._createTextures();
  58825. return _this;
  58826. }
  58827. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58828. get: function () {
  58829. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58835. get: function () {
  58836. return this._textures;
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58842. get: function () {
  58843. return this._textures[this._textures.length - 1];
  58844. },
  58845. enumerable: true,
  58846. configurable: true
  58847. });
  58848. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58849. set: function (wrap) {
  58850. if (this._textures) {
  58851. for (var i = 0; i < this._textures.length; i++) {
  58852. this._textures[i].wrapU = wrap;
  58853. }
  58854. }
  58855. },
  58856. enumerable: true,
  58857. configurable: true
  58858. });
  58859. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58860. set: function (wrap) {
  58861. if (this._textures) {
  58862. for (var i = 0; i < this._textures.length; i++) {
  58863. this._textures[i].wrapV = wrap;
  58864. }
  58865. }
  58866. },
  58867. enumerable: true,
  58868. configurable: true
  58869. });
  58870. MultiRenderTarget.prototype._rebuild = function () {
  58871. this.releaseInternalTextures();
  58872. this._createInternalTextures();
  58873. for (var i = 0; i < this._internalTextures.length; i++) {
  58874. var texture = this._textures[i];
  58875. texture._texture = this._internalTextures[i];
  58876. }
  58877. // Keeps references to frame buffer and stencil/depth buffer
  58878. this._texture = this._internalTextures[0];
  58879. };
  58880. MultiRenderTarget.prototype._createInternalTextures = function () {
  58881. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58882. };
  58883. MultiRenderTarget.prototype._createTextures = function () {
  58884. this._textures = [];
  58885. for (var i = 0; i < this._internalTextures.length; i++) {
  58886. var texture = new BABYLON.Texture(null, this.getScene());
  58887. texture._texture = this._internalTextures[i];
  58888. this._textures.push(texture);
  58889. }
  58890. // Keeps references to frame buffer and stencil/depth buffer
  58891. this._texture = this._internalTextures[0];
  58892. };
  58893. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58894. get: function () {
  58895. return this._samples;
  58896. },
  58897. set: function (value) {
  58898. if (this._samples === value) {
  58899. return;
  58900. }
  58901. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58902. },
  58903. enumerable: true,
  58904. configurable: true
  58905. });
  58906. MultiRenderTarget.prototype.resize = function (size) {
  58907. this.releaseInternalTextures();
  58908. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58909. this._createInternalTextures();
  58910. };
  58911. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58912. var _this = this;
  58913. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58914. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58915. });
  58916. };
  58917. MultiRenderTarget.prototype.dispose = function () {
  58918. this.releaseInternalTextures();
  58919. _super.prototype.dispose.call(this);
  58920. };
  58921. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58922. if (!this._internalTextures) {
  58923. return;
  58924. }
  58925. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58926. if (this._internalTextures[i] !== undefined) {
  58927. this._internalTextures[i].dispose();
  58928. this._internalTextures.splice(i, 1);
  58929. }
  58930. }
  58931. };
  58932. return MultiRenderTarget;
  58933. }(BABYLON.RenderTargetTexture));
  58934. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58935. })(BABYLON || (BABYLON = {}));
  58936. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58937. var BABYLON;
  58938. (function (BABYLON) {
  58939. var MirrorTexture = /** @class */ (function (_super) {
  58940. __extends(MirrorTexture, _super);
  58941. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58942. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58944. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58945. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58946. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58947. _this._transformMatrix = BABYLON.Matrix.Zero();
  58948. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58949. _this._adaptiveBlurKernel = 0;
  58950. _this._blurKernelX = 0;
  58951. _this._blurKernelY = 0;
  58952. _this._blurRatio = 1.0;
  58953. _this.ignoreCameraViewport = true;
  58954. _this.onBeforeRenderObservable.add(function () {
  58955. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58956. _this._savedViewMatrix = scene.getViewMatrix();
  58957. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58958. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58959. scene.clipPlane = _this.mirrorPlane;
  58960. scene.getEngine().cullBackFaces = false;
  58961. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58962. });
  58963. _this.onAfterRenderObservable.add(function () {
  58964. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58965. scene.getEngine().cullBackFaces = true;
  58966. scene._mirroredCameraPosition = null;
  58967. delete scene.clipPlane;
  58968. });
  58969. return _this;
  58970. }
  58971. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58972. get: function () {
  58973. return this._blurRatio;
  58974. },
  58975. set: function (value) {
  58976. if (this._blurRatio === value) {
  58977. return;
  58978. }
  58979. this._blurRatio = value;
  58980. this._preparePostProcesses();
  58981. },
  58982. enumerable: true,
  58983. configurable: true
  58984. });
  58985. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58986. set: function (value) {
  58987. this._adaptiveBlurKernel = value;
  58988. this._autoComputeBlurKernel();
  58989. },
  58990. enumerable: true,
  58991. configurable: true
  58992. });
  58993. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58994. set: function (value) {
  58995. this.blurKernelX = value;
  58996. this.blurKernelY = value;
  58997. },
  58998. enumerable: true,
  58999. configurable: true
  59000. });
  59001. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59002. get: function () {
  59003. return this._blurKernelX;
  59004. },
  59005. set: function (value) {
  59006. if (this._blurKernelX === value) {
  59007. return;
  59008. }
  59009. this._blurKernelX = value;
  59010. this._preparePostProcesses();
  59011. },
  59012. enumerable: true,
  59013. configurable: true
  59014. });
  59015. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59016. get: function () {
  59017. return this._blurKernelY;
  59018. },
  59019. set: function (value) {
  59020. if (this._blurKernelY === value) {
  59021. return;
  59022. }
  59023. this._blurKernelY = value;
  59024. this._preparePostProcesses();
  59025. },
  59026. enumerable: true,
  59027. configurable: true
  59028. });
  59029. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59030. var engine = this.getScene().getEngine();
  59031. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59032. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59033. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59034. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59035. };
  59036. MirrorTexture.prototype._onRatioRescale = function () {
  59037. if (this._sizeRatio) {
  59038. this.resize(this._initialSizeParameter);
  59039. if (!this._adaptiveBlurKernel) {
  59040. this._preparePostProcesses();
  59041. }
  59042. }
  59043. if (this._adaptiveBlurKernel) {
  59044. this._autoComputeBlurKernel();
  59045. }
  59046. };
  59047. MirrorTexture.prototype._preparePostProcesses = function () {
  59048. this.clearPostProcesses(true);
  59049. if (this._blurKernelX && this._blurKernelY) {
  59050. var engine = this.getScene().getEngine();
  59051. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59052. 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);
  59053. this._blurX.autoClear = false;
  59054. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59055. this._blurX.inputTexture = this._texture;
  59056. }
  59057. else {
  59058. this._blurX.alwaysForcePOT = true;
  59059. }
  59060. 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);
  59061. this._blurY.autoClear = false;
  59062. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59063. this.addPostProcess(this._blurX);
  59064. this.addPostProcess(this._blurY);
  59065. }
  59066. else {
  59067. if (this._blurY) {
  59068. this.removePostProcess(this._blurY);
  59069. this._blurY.dispose();
  59070. this._blurY = null;
  59071. }
  59072. if (this._blurX) {
  59073. this.removePostProcess(this._blurX);
  59074. this._blurX.dispose();
  59075. this._blurX = null;
  59076. }
  59077. }
  59078. };
  59079. MirrorTexture.prototype.clone = function () {
  59080. var scene = this.getScene();
  59081. if (!scene) {
  59082. return this;
  59083. }
  59084. var textureSize = this.getSize();
  59085. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59086. // Base texture
  59087. newTexture.hasAlpha = this.hasAlpha;
  59088. newTexture.level = this.level;
  59089. // Mirror Texture
  59090. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59091. if (this.renderList) {
  59092. newTexture.renderList = this.renderList.slice(0);
  59093. }
  59094. return newTexture;
  59095. };
  59096. MirrorTexture.prototype.serialize = function () {
  59097. if (!this.name) {
  59098. return null;
  59099. }
  59100. var serializationObject = _super.prototype.serialize.call(this);
  59101. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59102. return serializationObject;
  59103. };
  59104. return MirrorTexture;
  59105. }(BABYLON.RenderTargetTexture));
  59106. BABYLON.MirrorTexture = MirrorTexture;
  59107. })(BABYLON || (BABYLON = {}));
  59108. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59109. var BABYLON;
  59110. (function (BABYLON) {
  59111. /**
  59112. * Creates a refraction texture used by refraction channel of the standard material.
  59113. * @param name the texture name
  59114. * @param size size of the underlying texture
  59115. * @param scene root scene
  59116. */
  59117. var RefractionTexture = /** @class */ (function (_super) {
  59118. __extends(RefractionTexture, _super);
  59119. function RefractionTexture(name, size, scene, generateMipMaps) {
  59120. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59121. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59122. _this.depth = 2.0;
  59123. _this.onBeforeRenderObservable.add(function () {
  59124. scene.clipPlane = _this.refractionPlane;
  59125. });
  59126. _this.onAfterRenderObservable.add(function () {
  59127. delete scene.clipPlane;
  59128. });
  59129. return _this;
  59130. }
  59131. RefractionTexture.prototype.clone = function () {
  59132. var scene = this.getScene();
  59133. if (!scene) {
  59134. return this;
  59135. }
  59136. var textureSize = this.getSize();
  59137. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59138. // Base texture
  59139. newTexture.hasAlpha = this.hasAlpha;
  59140. newTexture.level = this.level;
  59141. // Refraction Texture
  59142. newTexture.refractionPlane = this.refractionPlane.clone();
  59143. if (this.renderList) {
  59144. newTexture.renderList = this.renderList.slice(0);
  59145. }
  59146. newTexture.depth = this.depth;
  59147. return newTexture;
  59148. };
  59149. RefractionTexture.prototype.serialize = function () {
  59150. if (!this.name) {
  59151. return null;
  59152. }
  59153. var serializationObject = _super.prototype.serialize.call(this);
  59154. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59155. serializationObject.depth = this.depth;
  59156. return serializationObject;
  59157. };
  59158. return RefractionTexture;
  59159. }(BABYLON.RenderTargetTexture));
  59160. BABYLON.RefractionTexture = RefractionTexture;
  59161. })(BABYLON || (BABYLON = {}));
  59162. //# sourceMappingURL=babylon.refractionTexture.js.map
  59163. var BABYLON;
  59164. (function (BABYLON) {
  59165. var DynamicTexture = /** @class */ (function (_super) {
  59166. __extends(DynamicTexture, _super);
  59167. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59168. if (scene === void 0) { scene = null; }
  59169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59170. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59171. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59172. _this.name = name;
  59173. _this._engine = _this.getScene().getEngine();
  59174. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59175. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59176. _this._generateMipMaps = generateMipMaps;
  59177. if (options.getContext) {
  59178. _this._canvas = options;
  59179. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59180. }
  59181. else {
  59182. _this._canvas = document.createElement("canvas");
  59183. if (options.width) {
  59184. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59185. }
  59186. else {
  59187. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59188. }
  59189. }
  59190. var textureSize = _this.getSize();
  59191. _this._canvas.width = textureSize.width;
  59192. _this._canvas.height = textureSize.height;
  59193. _this._context = _this._canvas.getContext("2d");
  59194. return _this;
  59195. }
  59196. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59197. get: function () {
  59198. return true;
  59199. },
  59200. enumerable: true,
  59201. configurable: true
  59202. });
  59203. DynamicTexture.prototype._recreate = function (textureSize) {
  59204. this._canvas.width = textureSize.width;
  59205. this._canvas.height = textureSize.height;
  59206. this.releaseInternalTexture();
  59207. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59208. };
  59209. DynamicTexture.prototype.scale = function (ratio) {
  59210. var textureSize = this.getSize();
  59211. textureSize.width *= ratio;
  59212. textureSize.height *= ratio;
  59213. this._recreate(textureSize);
  59214. };
  59215. DynamicTexture.prototype.scaleTo = function (width, height) {
  59216. var textureSize = this.getSize();
  59217. textureSize.width = width;
  59218. textureSize.height = height;
  59219. this._recreate(textureSize);
  59220. };
  59221. DynamicTexture.prototype.getContext = function () {
  59222. return this._context;
  59223. };
  59224. DynamicTexture.prototype.clear = function () {
  59225. var size = this.getSize();
  59226. this._context.fillRect(0, 0, size.width, size.height);
  59227. };
  59228. DynamicTexture.prototype.update = function (invertY) {
  59229. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59230. };
  59231. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59232. if (update === void 0) { update = true; }
  59233. var size = this.getSize();
  59234. if (clearColor) {
  59235. this._context.fillStyle = clearColor;
  59236. this._context.fillRect(0, 0, size.width, size.height);
  59237. }
  59238. this._context.font = font;
  59239. if (x === null || x === undefined) {
  59240. var textSize = this._context.measureText(text);
  59241. x = (size.width - textSize.width) / 2;
  59242. }
  59243. if (y === null || y === undefined) {
  59244. var fontSize = parseInt((font.replace(/\D/g, '')));
  59245. ;
  59246. y = (size.height / 2) + (fontSize / 3.65);
  59247. }
  59248. this._context.fillStyle = color;
  59249. this._context.fillText(text, x, y);
  59250. if (update) {
  59251. this.update(invertY);
  59252. }
  59253. };
  59254. DynamicTexture.prototype.clone = function () {
  59255. var scene = this.getScene();
  59256. if (!scene) {
  59257. return this;
  59258. }
  59259. var textureSize = this.getSize();
  59260. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59261. // Base texture
  59262. newTexture.hasAlpha = this.hasAlpha;
  59263. newTexture.level = this.level;
  59264. // Dynamic Texture
  59265. newTexture.wrapU = this.wrapU;
  59266. newTexture.wrapV = this.wrapV;
  59267. return newTexture;
  59268. };
  59269. DynamicTexture.prototype._rebuild = function () {
  59270. this.update();
  59271. };
  59272. return DynamicTexture;
  59273. }(BABYLON.Texture));
  59274. BABYLON.DynamicTexture = DynamicTexture;
  59275. })(BABYLON || (BABYLON = {}));
  59276. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59277. var BABYLON;
  59278. (function (BABYLON) {
  59279. var VideoTexture = /** @class */ (function (_super) {
  59280. __extends(VideoTexture, _super);
  59281. /**
  59282. * Creates a video texture.
  59283. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59284. * @param {string | null} name optional name, will detect from video source, if not defined
  59285. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59286. * @param {BABYLON.Scene} scene is obviously the current scene.
  59287. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59288. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59289. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59290. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59291. */
  59292. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59293. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59294. if (invertY === void 0) { invertY = false; }
  59295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59296. if (settings === void 0) { settings = {
  59297. autoPlay: true,
  59298. loop: true,
  59299. autoUpdateTexture: true,
  59300. }; }
  59301. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59302. _this._createInternalTexture = function () {
  59303. if (_this._texture != null) {
  59304. return;
  59305. }
  59306. if (!_this._engine.needPOTTextures ||
  59307. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59308. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59309. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59310. }
  59311. else {
  59312. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59313. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59314. _this._generateMipMaps = false;
  59315. }
  59316. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59317. _this._texture.isReady = true;
  59318. _this._updateInternalTexture();
  59319. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59320. _this.onLoadObservable.notifyObservers(_this);
  59321. }
  59322. };
  59323. _this.reset = function () {
  59324. if (_this._texture == null) {
  59325. return;
  59326. }
  59327. _this._texture.dispose();
  59328. _this._texture = null;
  59329. };
  59330. _this._updateInternalTexture = function (e) {
  59331. if (_this._texture == null || !_this._texture.isReady) {
  59332. return;
  59333. }
  59334. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59335. return;
  59336. }
  59337. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59338. };
  59339. _this._engine = _this.getScene().getEngine();
  59340. _this._generateMipMaps = generateMipMaps;
  59341. _this._samplingMode = samplingMode;
  59342. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59343. _this.name = name || _this._getName(src);
  59344. _this.video = _this._getVideo(src);
  59345. if (settings.autoPlay !== undefined) {
  59346. _this.video.autoplay = settings.autoPlay;
  59347. }
  59348. if (settings.loop !== undefined) {
  59349. _this.video.loop = settings.loop;
  59350. }
  59351. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59352. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59353. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59354. _this.video.addEventListener("emptied", _this.reset);
  59355. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59356. _this._createInternalTexture();
  59357. }
  59358. return _this;
  59359. }
  59360. VideoTexture.prototype._getName = function (src) {
  59361. if (src instanceof HTMLVideoElement) {
  59362. return src.currentSrc;
  59363. }
  59364. if (typeof src === "object") {
  59365. return src.toString();
  59366. }
  59367. return src;
  59368. };
  59369. ;
  59370. VideoTexture.prototype._getVideo = function (src) {
  59371. if (src instanceof HTMLVideoElement) {
  59372. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59373. return src;
  59374. }
  59375. var video = document.createElement("video");
  59376. if (typeof src === "string") {
  59377. BABYLON.Tools.SetCorsBehavior(src, video);
  59378. video.src = src;
  59379. }
  59380. else {
  59381. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59382. src.forEach(function (url) {
  59383. var source = document.createElement("source");
  59384. source.src = url;
  59385. video.appendChild(source);
  59386. });
  59387. }
  59388. return video;
  59389. };
  59390. ;
  59391. /**
  59392. * Internal method to initiate `update`.
  59393. */
  59394. VideoTexture.prototype._rebuild = function () {
  59395. this.update();
  59396. };
  59397. /**
  59398. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59399. */
  59400. VideoTexture.prototype.update = function () {
  59401. if (!this.autoUpdateTexture) {
  59402. // Expecting user to call `updateTexture` manually
  59403. return;
  59404. }
  59405. this.updateTexture(true);
  59406. };
  59407. /**
  59408. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59409. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59410. */
  59411. VideoTexture.prototype.updateTexture = function (isVisible) {
  59412. if (!isVisible) {
  59413. return;
  59414. }
  59415. if (this.video.paused) {
  59416. return;
  59417. }
  59418. this._updateInternalTexture();
  59419. };
  59420. /**
  59421. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59422. * @param url New url.
  59423. */
  59424. VideoTexture.prototype.updateURL = function (url) {
  59425. this.video.src = url;
  59426. };
  59427. VideoTexture.prototype.dispose = function () {
  59428. _super.prototype.dispose.call(this);
  59429. this.video.removeEventListener("canplay", this._createInternalTexture);
  59430. this.video.removeEventListener("paused", this._updateInternalTexture);
  59431. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59432. this.video.removeEventListener("emptied", this.reset);
  59433. this.video.pause();
  59434. };
  59435. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59436. var video = document.createElement("video");
  59437. var constraintsDeviceId;
  59438. if (constraints && constraints.deviceId) {
  59439. constraintsDeviceId = {
  59440. exact: constraints.deviceId,
  59441. };
  59442. }
  59443. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59444. if (navigator.mediaDevices) {
  59445. navigator.mediaDevices.getUserMedia({ video: constraints })
  59446. .then(function (stream) {
  59447. if (video.mozSrcObject !== undefined) {
  59448. // hack for Firefox < 19
  59449. video.mozSrcObject = stream;
  59450. }
  59451. else {
  59452. video.srcObject = stream;
  59453. }
  59454. var onPlaying = function () {
  59455. if (onReady) {
  59456. onReady(new VideoTexture("video", video, scene, true, true));
  59457. }
  59458. video.removeEventListener("playing", onPlaying);
  59459. };
  59460. video.addEventListener("playing", onPlaying);
  59461. video.play();
  59462. })
  59463. .catch(function (err) {
  59464. BABYLON.Tools.Error(err.name);
  59465. });
  59466. }
  59467. else {
  59468. navigator.getUserMedia =
  59469. navigator.getUserMedia ||
  59470. navigator.webkitGetUserMedia ||
  59471. navigator.mozGetUserMedia ||
  59472. navigator.msGetUserMedia;
  59473. if (navigator.getUserMedia) {
  59474. navigator.getUserMedia({
  59475. video: {
  59476. deviceId: constraintsDeviceId,
  59477. width: {
  59478. min: (constraints && constraints.minWidth) || 256,
  59479. max: (constraints && constraints.maxWidth) || 640,
  59480. },
  59481. height: {
  59482. min: (constraints && constraints.minHeight) || 256,
  59483. max: (constraints && constraints.maxHeight) || 480,
  59484. },
  59485. },
  59486. }, function (stream) {
  59487. if (video.mozSrcObject !== undefined) {
  59488. // hack for Firefox < 19
  59489. video.mozSrcObject = stream;
  59490. }
  59491. else {
  59492. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59493. }
  59494. video.play();
  59495. if (onReady) {
  59496. onReady(new VideoTexture("video", video, scene, true, true));
  59497. }
  59498. }, function (e) {
  59499. BABYLON.Tools.Error(e.name);
  59500. });
  59501. }
  59502. }
  59503. };
  59504. return VideoTexture;
  59505. }(BABYLON.Texture));
  59506. BABYLON.VideoTexture = VideoTexture;
  59507. })(BABYLON || (BABYLON = {}));
  59508. //# sourceMappingURL=babylon.videoTexture.js.map
  59509. var BABYLON;
  59510. (function (BABYLON) {
  59511. var RawTexture = /** @class */ (function (_super) {
  59512. __extends(RawTexture, _super);
  59513. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59515. if (invertY === void 0) { invertY = false; }
  59516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59517. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59518. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59519. _this.format = format;
  59520. _this._engine = scene.getEngine();
  59521. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59522. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59523. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59524. return _this;
  59525. }
  59526. RawTexture.prototype.update = function (data) {
  59527. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59528. };
  59529. // Statics
  59530. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59531. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59532. if (invertY === void 0) { invertY = false; }
  59533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59534. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59535. };
  59536. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59538. if (invertY === void 0) { invertY = false; }
  59539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59540. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59541. };
  59542. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59544. if (invertY === void 0) { invertY = false; }
  59545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59546. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59547. };
  59548. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59550. if (invertY === void 0) { invertY = false; }
  59551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59552. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59553. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59554. };
  59555. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59556. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59557. if (invertY === void 0) { invertY = false; }
  59558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59559. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59560. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59561. };
  59562. return RawTexture;
  59563. }(BABYLON.Texture));
  59564. BABYLON.RawTexture = RawTexture;
  59565. })(BABYLON || (BABYLON = {}));
  59566. //# sourceMappingURL=babylon.rawTexture.js.map
  59567. var BABYLON;
  59568. (function (BABYLON) {
  59569. /**
  59570. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59571. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59572. */
  59573. var PostProcess = /** @class */ (function () {
  59574. /**
  59575. * Creates a new instance of @see PostProcess
  59576. * @param name The name of the PostProcess.
  59577. * @param fragmentUrl The url of the fragment shader to be used.
  59578. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59579. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59580. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59581. * @param camera The camera to apply the render pass to.
  59582. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59583. * @param engine The engine which the post process will be applied. (default: current engine)
  59584. * @param reusable If the post process can be reused on the same frame. (default: false)
  59585. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59586. * @param textureType Type of textures used when performing the post process. (default: 0)
  59587. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59588. * @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
  59589. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59590. */
  59591. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59593. if (defines === void 0) { defines = null; }
  59594. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59595. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59596. if (blockCompilation === void 0) { blockCompilation = false; }
  59597. this.name = name;
  59598. /**
  59599. * Width of the texture to apply the post process on
  59600. */
  59601. this.width = -1;
  59602. /**
  59603. * Height of the texture to apply the post process on
  59604. */
  59605. this.height = -1;
  59606. /**
  59607. * If the buffer needs to be cleared before applying the post process. (default: true)
  59608. * Should be set to false if shader will overwrite all previous pixels.
  59609. */
  59610. this.autoClear = true;
  59611. /**
  59612. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59613. */
  59614. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59615. /**
  59616. * Animations to be used for the post processing
  59617. */
  59618. this.animations = new Array();
  59619. /**
  59620. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59621. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59622. */
  59623. this.enablePixelPerfectMode = false;
  59624. /**
  59625. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59626. */
  59627. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59628. /**
  59629. * Force textures to be a power of two (default: false)
  59630. */
  59631. this.alwaysForcePOT = false;
  59632. /**
  59633. * Number of sample textures (default: 1)
  59634. */
  59635. this.samples = 1;
  59636. /**
  59637. * Modify the scale of the post process to be the same as the viewport (default: false)
  59638. */
  59639. this.adaptScaleToCurrentViewport = false;
  59640. this._reusable = false;
  59641. /**
  59642. * Smart array of input and output textures for the post process.
  59643. */
  59644. this._textures = new BABYLON.SmartArray(2);
  59645. /**
  59646. * The index in _textures that corresponds to the output texture.
  59647. */
  59648. this._currentRenderTextureInd = 0;
  59649. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59650. this._texelSize = BABYLON.Vector2.Zero();
  59651. // Events
  59652. /**
  59653. * An event triggered when the postprocess is activated.
  59654. * @type {BABYLON.Observable}
  59655. */
  59656. this.onActivateObservable = new BABYLON.Observable();
  59657. /**
  59658. * An event triggered when the postprocess changes its size.
  59659. * @type {BABYLON.Observable}
  59660. */
  59661. this.onSizeChangedObservable = new BABYLON.Observable();
  59662. /**
  59663. * An event triggered when the postprocess applies its effect.
  59664. * @type {BABYLON.Observable}
  59665. */
  59666. this.onApplyObservable = new BABYLON.Observable();
  59667. /**
  59668. * An event triggered before rendering the postprocess
  59669. * @type {BABYLON.Observable}
  59670. */
  59671. this.onBeforeRenderObservable = new BABYLON.Observable();
  59672. /**
  59673. * An event triggered after rendering the postprocess
  59674. * @type {BABYLON.Observable}
  59675. */
  59676. this.onAfterRenderObservable = new BABYLON.Observable();
  59677. if (camera != null) {
  59678. this._camera = camera;
  59679. this._scene = camera.getScene();
  59680. camera.attachPostProcess(this);
  59681. this._engine = this._scene.getEngine();
  59682. this._scene.postProcesses.push(this);
  59683. }
  59684. else if (engine) {
  59685. this._engine = engine;
  59686. this._engine.postProcesses.push(this);
  59687. }
  59688. this._options = options;
  59689. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59690. this._reusable = reusable || false;
  59691. this._textureType = textureType;
  59692. this._samplers = samplers || [];
  59693. this._samplers.push("textureSampler");
  59694. this._fragmentUrl = fragmentUrl;
  59695. this._vertexUrl = vertexUrl;
  59696. this._parameters = parameters || [];
  59697. this._parameters.push("scale");
  59698. this._indexParameters = indexParameters;
  59699. if (!blockCompilation) {
  59700. this.updateEffect(defines);
  59701. }
  59702. }
  59703. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59704. /**
  59705. * A function that is added to the onActivateObservable
  59706. */
  59707. set: function (callback) {
  59708. if (this._onActivateObserver) {
  59709. this.onActivateObservable.remove(this._onActivateObserver);
  59710. }
  59711. if (callback) {
  59712. this._onActivateObserver = this.onActivateObservable.add(callback);
  59713. }
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59719. /**
  59720. * A function that is added to the onSizeChangedObservable
  59721. */
  59722. set: function (callback) {
  59723. if (this._onSizeChangedObserver) {
  59724. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59725. }
  59726. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59727. },
  59728. enumerable: true,
  59729. configurable: true
  59730. });
  59731. Object.defineProperty(PostProcess.prototype, "onApply", {
  59732. /**
  59733. * A function that is added to the onApplyObservable
  59734. */
  59735. set: function (callback) {
  59736. if (this._onApplyObserver) {
  59737. this.onApplyObservable.remove(this._onApplyObserver);
  59738. }
  59739. this._onApplyObserver = this.onApplyObservable.add(callback);
  59740. },
  59741. enumerable: true,
  59742. configurable: true
  59743. });
  59744. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59745. /**
  59746. * A function that is added to the onBeforeRenderObservable
  59747. */
  59748. set: function (callback) {
  59749. if (this._onBeforeRenderObserver) {
  59750. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59751. }
  59752. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59753. },
  59754. enumerable: true,
  59755. configurable: true
  59756. });
  59757. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59758. /**
  59759. * A function that is added to the onAfterRenderObservable
  59760. */
  59761. set: function (callback) {
  59762. if (this._onAfterRenderObserver) {
  59763. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59764. }
  59765. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59771. /**
  59772. * 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
  59773. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59774. */
  59775. get: function () {
  59776. return this._textures.data[this._currentRenderTextureInd];
  59777. },
  59778. set: function (value) {
  59779. this._forcedOutputTexture = value;
  59780. },
  59781. enumerable: true,
  59782. configurable: true
  59783. });
  59784. /**
  59785. * Gets the camera which post process is applied to.
  59786. * @returns The camera the post process is applied to.
  59787. */
  59788. PostProcess.prototype.getCamera = function () {
  59789. return this._camera;
  59790. };
  59791. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59792. /**
  59793. * Gets the texel size of the postprocess.
  59794. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59795. */
  59796. get: function () {
  59797. if (this._shareOutputWithPostProcess) {
  59798. return this._shareOutputWithPostProcess.texelSize;
  59799. }
  59800. if (this._forcedOutputTexture) {
  59801. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59802. }
  59803. return this._texelSize;
  59804. },
  59805. enumerable: true,
  59806. configurable: true
  59807. });
  59808. /**
  59809. * Gets the engine which this post process belongs to.
  59810. * @returns The engine the post process was enabled with.
  59811. */
  59812. PostProcess.prototype.getEngine = function () {
  59813. return this._engine;
  59814. };
  59815. /**
  59816. * The effect that is created when initializing the post process.
  59817. * @returns The created effect corrisponding the the postprocess.
  59818. */
  59819. PostProcess.prototype.getEffect = function () {
  59820. return this._effect;
  59821. };
  59822. /**
  59823. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59824. * @param postProcess The post process to share the output with.
  59825. * @returns This post process.
  59826. */
  59827. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59828. this._disposeTextures();
  59829. this._shareOutputWithPostProcess = postProcess;
  59830. return this;
  59831. };
  59832. /**
  59833. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59834. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59835. */
  59836. PostProcess.prototype.useOwnOutput = function () {
  59837. if (this._textures.length == 0) {
  59838. this._textures = new BABYLON.SmartArray(2);
  59839. }
  59840. this._shareOutputWithPostProcess = null;
  59841. };
  59842. /**
  59843. * Updates the effect with the current post process compile time values and recompiles the shader.
  59844. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59845. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59846. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59847. * @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
  59848. * @param onCompiled Called when the shader has been compiled.
  59849. * @param onError Called if there is an error when compiling a shader.
  59850. */
  59851. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59852. if (defines === void 0) { defines = null; }
  59853. if (uniforms === void 0) { uniforms = null; }
  59854. if (samplers === void 0) { samplers = null; }
  59855. 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);
  59856. };
  59857. /**
  59858. * The post process is reusable if it can be used multiple times within one frame.
  59859. * @returns If the post process is reusable
  59860. */
  59861. PostProcess.prototype.isReusable = function () {
  59862. return this._reusable;
  59863. };
  59864. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59865. PostProcess.prototype.markTextureDirty = function () {
  59866. this.width = -1;
  59867. };
  59868. /**
  59869. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59870. * 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.
  59871. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59872. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59873. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59874. */
  59875. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59876. var _this = this;
  59877. if (sourceTexture === void 0) { sourceTexture = null; }
  59878. camera = camera || this._camera;
  59879. var scene = camera.getScene();
  59880. var engine = scene.getEngine();
  59881. var maxSize = engine.getCaps().maxTextureSize;
  59882. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59883. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59884. // 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
  59885. var webVRCamera = camera.parent;
  59886. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59887. requiredWidth /= 2;
  59888. }
  59889. var desiredWidth = (this._options.width || requiredWidth);
  59890. var desiredHeight = this._options.height || requiredHeight;
  59891. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59892. if (this.adaptScaleToCurrentViewport) {
  59893. var currentViewport = engine.currentViewport;
  59894. if (currentViewport) {
  59895. desiredWidth *= currentViewport.width;
  59896. desiredHeight *= currentViewport.height;
  59897. }
  59898. }
  59899. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59900. if (!this._options.width) {
  59901. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59902. }
  59903. if (!this._options.height) {
  59904. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59905. }
  59906. }
  59907. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59908. if (this._textures.length > 0) {
  59909. for (var i = 0; i < this._textures.length; i++) {
  59910. this._engine._releaseTexture(this._textures.data[i]);
  59911. }
  59912. this._textures.reset();
  59913. }
  59914. this.width = desiredWidth;
  59915. this.height = desiredHeight;
  59916. var textureSize = { width: this.width, height: this.height };
  59917. var textureOptions = {
  59918. generateMipMaps: false,
  59919. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59920. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59921. samplingMode: this.renderTargetSamplingMode,
  59922. type: this._textureType
  59923. };
  59924. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59925. if (this._reusable) {
  59926. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59927. }
  59928. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59929. this.onSizeChangedObservable.notifyObservers(this);
  59930. }
  59931. this._textures.forEach(function (texture) {
  59932. if (texture.samples !== _this.samples) {
  59933. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59934. }
  59935. });
  59936. }
  59937. var target;
  59938. if (this._shareOutputWithPostProcess) {
  59939. target = this._shareOutputWithPostProcess.inputTexture;
  59940. }
  59941. else if (this._forcedOutputTexture) {
  59942. target = this._forcedOutputTexture;
  59943. this.width = this._forcedOutputTexture.width;
  59944. this.height = this._forcedOutputTexture.height;
  59945. }
  59946. else {
  59947. target = this.inputTexture;
  59948. }
  59949. // Bind the input of this post process to be used as the output of the previous post process.
  59950. if (this.enablePixelPerfectMode) {
  59951. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59952. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59953. }
  59954. else {
  59955. this._scaleRatio.copyFromFloats(1, 1);
  59956. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59957. }
  59958. this.onActivateObservable.notifyObservers(camera);
  59959. // Clear
  59960. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59961. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59962. }
  59963. if (this._reusable) {
  59964. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59965. }
  59966. };
  59967. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59968. /**
  59969. * If the post process is supported.
  59970. */
  59971. get: function () {
  59972. return this._effect.isSupported;
  59973. },
  59974. enumerable: true,
  59975. configurable: true
  59976. });
  59977. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59978. /**
  59979. * The aspect ratio of the output texture.
  59980. */
  59981. get: function () {
  59982. if (this._shareOutputWithPostProcess) {
  59983. return this._shareOutputWithPostProcess.aspectRatio;
  59984. }
  59985. if (this._forcedOutputTexture) {
  59986. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59987. }
  59988. return this.width / this.height;
  59989. },
  59990. enumerable: true,
  59991. configurable: true
  59992. });
  59993. /**
  59994. * Get a value indicating if the post-process is ready to be used
  59995. * @returns true if the post-process is ready (shader is compiled)
  59996. */
  59997. PostProcess.prototype.isReady = function () {
  59998. return this._effect && this._effect.isReady();
  59999. };
  60000. /**
  60001. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60002. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60003. */
  60004. PostProcess.prototype.apply = function () {
  60005. // Check
  60006. if (!this._effect || !this._effect.isReady())
  60007. return null;
  60008. // States
  60009. this._engine.enableEffect(this._effect);
  60010. this._engine.setState(false);
  60011. this._engine.setDepthBuffer(false);
  60012. this._engine.setDepthWrite(false);
  60013. // Alpha
  60014. this._engine.setAlphaMode(this.alphaMode);
  60015. if (this.alphaConstants) {
  60016. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60017. }
  60018. // Bind the output texture of the preivous post process as the input to this post process.
  60019. var source;
  60020. if (this._shareOutputWithPostProcess) {
  60021. source = this._shareOutputWithPostProcess.inputTexture;
  60022. }
  60023. else if (this._forcedOutputTexture) {
  60024. source = this._forcedOutputTexture;
  60025. }
  60026. else {
  60027. source = this.inputTexture;
  60028. }
  60029. this._effect._bindTexture("textureSampler", source);
  60030. // Parameters
  60031. this._effect.setVector2("scale", this._scaleRatio);
  60032. this.onApplyObservable.notifyObservers(this._effect);
  60033. return this._effect;
  60034. };
  60035. PostProcess.prototype._disposeTextures = function () {
  60036. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60037. return;
  60038. }
  60039. if (this._textures.length > 0) {
  60040. for (var i = 0; i < this._textures.length; i++) {
  60041. this._engine._releaseTexture(this._textures.data[i]);
  60042. }
  60043. }
  60044. this._textures.dispose();
  60045. };
  60046. /**
  60047. * Disposes the post process.
  60048. * @param camera The camera to dispose the post process on.
  60049. */
  60050. PostProcess.prototype.dispose = function (camera) {
  60051. camera = camera || this._camera;
  60052. this._disposeTextures();
  60053. if (this._scene) {
  60054. var index_1 = this._scene.postProcesses.indexOf(this);
  60055. if (index_1 !== -1) {
  60056. this._scene.postProcesses.splice(index_1, 1);
  60057. }
  60058. }
  60059. else {
  60060. var index_2 = this._engine.postProcesses.indexOf(this);
  60061. if (index_2 !== -1) {
  60062. this._engine.postProcesses.splice(index_2, 1);
  60063. }
  60064. }
  60065. if (!camera) {
  60066. return;
  60067. }
  60068. camera.detachPostProcess(this);
  60069. var index = camera._postProcesses.indexOf(this);
  60070. if (index === 0 && camera._postProcesses.length > 0) {
  60071. this._camera._postProcesses[0].markTextureDirty();
  60072. }
  60073. this.onActivateObservable.clear();
  60074. this.onAfterRenderObservable.clear();
  60075. this.onApplyObservable.clear();
  60076. this.onBeforeRenderObservable.clear();
  60077. this.onSizeChangedObservable.clear();
  60078. };
  60079. return PostProcess;
  60080. }());
  60081. BABYLON.PostProcess = PostProcess;
  60082. })(BABYLON || (BABYLON = {}));
  60083. //# sourceMappingURL=babylon.postProcess.js.map
  60084. var BABYLON;
  60085. (function (BABYLON) {
  60086. var PassPostProcess = /** @class */ (function (_super) {
  60087. __extends(PassPostProcess, _super);
  60088. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60089. if (camera === void 0) { camera = null; }
  60090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60091. if (blockCompilation === void 0) { blockCompilation = false; }
  60092. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60093. }
  60094. return PassPostProcess;
  60095. }(BABYLON.PostProcess));
  60096. BABYLON.PassPostProcess = PassPostProcess;
  60097. })(BABYLON || (BABYLON = {}));
  60098. //# sourceMappingURL=babylon.passPostProcess.js.map
  60099. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60100. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60101. s = arguments[i];
  60102. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60103. t[p] = s[p];
  60104. }
  60105. return t;
  60106. };
  60107. var BABYLON;
  60108. (function (BABYLON) {
  60109. /**
  60110. * Default implementation of @see IShadowGenerator.
  60111. * This is the main object responsible of generating shadows in the framework.
  60112. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60113. */
  60114. var ShadowGenerator = /** @class */ (function () {
  60115. /**
  60116. * Creates a ShadowGenerator object.
  60117. * A ShadowGenerator is the required tool to use the shadows.
  60118. * Each light casting shadows needs to use its own ShadowGenerator.
  60119. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60120. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60121. * @param light The light object generating the shadows.
  60122. * @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.
  60123. */
  60124. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60125. this._bias = 0.00005;
  60126. this._blurBoxOffset = 1;
  60127. this._blurScale = 2;
  60128. this._blurKernel = 1;
  60129. this._useKernelBlur = false;
  60130. this._filter = ShadowGenerator.FILTER_NONE;
  60131. this._darkness = 0;
  60132. this._transparencyShadow = false;
  60133. /**
  60134. * Controls the extent to which the shadows fade out at the edge of the frustum
  60135. * Used only by directionals and spots
  60136. */
  60137. this.frustumEdgeFalloff = 0;
  60138. /**
  60139. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60140. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60141. * It might on the other hand introduce peter panning.
  60142. */
  60143. this.forceBackFacesOnly = false;
  60144. this._lightDirection = BABYLON.Vector3.Zero();
  60145. this._viewMatrix = BABYLON.Matrix.Zero();
  60146. this._projectionMatrix = BABYLON.Matrix.Zero();
  60147. this._transformMatrix = BABYLON.Matrix.Zero();
  60148. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60149. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60150. this._currentFaceIndex = 0;
  60151. this._currentFaceIndexCache = 0;
  60152. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60153. this._mapSize = mapSize;
  60154. this._light = light;
  60155. this._scene = light.getScene();
  60156. light._shadowGenerator = this;
  60157. // Texture type fallback from float to int if not supported.
  60158. var caps = this._scene.getEngine().getCaps();
  60159. if (!useFullFloatFirst) {
  60160. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60161. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60162. }
  60163. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60164. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60165. }
  60166. else {
  60167. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60168. }
  60169. }
  60170. else {
  60171. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60172. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60173. }
  60174. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60175. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60176. }
  60177. else {
  60178. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60179. }
  60180. }
  60181. this._initializeGenerator();
  60182. }
  60183. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60184. /**
  60185. * Shadow generator mode None: no filtering applied.
  60186. */
  60187. get: function () {
  60188. return ShadowGenerator._FILTER_NONE;
  60189. },
  60190. enumerable: true,
  60191. configurable: true
  60192. });
  60193. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60194. /**
  60195. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60196. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60197. */
  60198. get: function () {
  60199. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60205. /**
  60206. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60207. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60208. */
  60209. get: function () {
  60210. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60211. },
  60212. enumerable: true,
  60213. configurable: true
  60214. });
  60215. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60216. /**
  60217. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60218. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60219. */
  60220. get: function () {
  60221. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60222. },
  60223. enumerable: true,
  60224. configurable: true
  60225. });
  60226. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60227. /**
  60228. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60229. * edge artifacts on steep falloff.
  60230. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60231. */
  60232. get: function () {
  60233. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60234. },
  60235. enumerable: true,
  60236. configurable: true
  60237. });
  60238. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60239. /**
  60240. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60241. * edge artifacts on steep falloff.
  60242. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60243. */
  60244. get: function () {
  60245. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60246. },
  60247. enumerable: true,
  60248. configurable: true
  60249. });
  60250. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60251. /**
  60252. * Gets the bias: offset applied on the depth preventing acnea.
  60253. */
  60254. get: function () {
  60255. return this._bias;
  60256. },
  60257. /**
  60258. * Sets the bias: offset applied on the depth preventing acnea.
  60259. */
  60260. set: function (bias) {
  60261. this._bias = bias;
  60262. },
  60263. enumerable: true,
  60264. configurable: true
  60265. });
  60266. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60267. /**
  60268. * Gets the blur box offset: offset applied during the blur pass.
  60269. * Only usefull if useKernelBlur = false
  60270. */
  60271. get: function () {
  60272. return this._blurBoxOffset;
  60273. },
  60274. /**
  60275. * Sets the blur box offset: offset applied during the blur pass.
  60276. * Only usefull if useKernelBlur = false
  60277. */
  60278. set: function (value) {
  60279. if (this._blurBoxOffset === value) {
  60280. return;
  60281. }
  60282. this._blurBoxOffset = value;
  60283. this._disposeBlurPostProcesses();
  60284. },
  60285. enumerable: true,
  60286. configurable: true
  60287. });
  60288. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60289. /**
  60290. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60291. * 2 means half of the size.
  60292. */
  60293. get: function () {
  60294. return this._blurScale;
  60295. },
  60296. /**
  60297. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60298. * 2 means half of the size.
  60299. */
  60300. set: function (value) {
  60301. if (this._blurScale === value) {
  60302. return;
  60303. }
  60304. this._blurScale = value;
  60305. this._disposeBlurPostProcesses();
  60306. },
  60307. enumerable: true,
  60308. configurable: true
  60309. });
  60310. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60311. /**
  60312. * Gets the blur kernel: kernel size of the blur pass.
  60313. * Only usefull if useKernelBlur = true
  60314. */
  60315. get: function () {
  60316. return this._blurKernel;
  60317. },
  60318. /**
  60319. * Sets the blur kernel: kernel size of the blur pass.
  60320. * Only usefull if useKernelBlur = true
  60321. */
  60322. set: function (value) {
  60323. if (this._blurKernel === value) {
  60324. return;
  60325. }
  60326. this._blurKernel = value;
  60327. this._disposeBlurPostProcesses();
  60328. },
  60329. enumerable: true,
  60330. configurable: true
  60331. });
  60332. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60333. /**
  60334. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60335. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60336. */
  60337. get: function () {
  60338. return this._useKernelBlur;
  60339. },
  60340. /**
  60341. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60342. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60343. */
  60344. set: function (value) {
  60345. if (this._useKernelBlur === value) {
  60346. return;
  60347. }
  60348. this._useKernelBlur = value;
  60349. this._disposeBlurPostProcesses();
  60350. },
  60351. enumerable: true,
  60352. configurable: true
  60353. });
  60354. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60355. /**
  60356. * Gets the depth scale used in ESM mode.
  60357. */
  60358. get: function () {
  60359. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60360. },
  60361. /**
  60362. * Sets the depth scale used in ESM mode.
  60363. * This can override the scale stored on the light.
  60364. */
  60365. set: function (value) {
  60366. this._depthScale = value;
  60367. },
  60368. enumerable: true,
  60369. configurable: true
  60370. });
  60371. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60372. /**
  60373. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60374. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60375. */
  60376. get: function () {
  60377. return this._filter;
  60378. },
  60379. /**
  60380. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60381. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60382. */
  60383. set: function (value) {
  60384. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60385. if (this._light.needCube()) {
  60386. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60387. this.useExponentialShadowMap = true;
  60388. return;
  60389. }
  60390. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60391. this.useCloseExponentialShadowMap = true;
  60392. return;
  60393. }
  60394. }
  60395. if (this._filter === value) {
  60396. return;
  60397. }
  60398. this._filter = value;
  60399. this._disposeBlurPostProcesses();
  60400. this._applyFilterValues();
  60401. this._light._markMeshesAsLightDirty();
  60402. },
  60403. enumerable: true,
  60404. configurable: true
  60405. });
  60406. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60407. /**
  60408. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60409. */
  60410. get: function () {
  60411. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60412. },
  60413. /**
  60414. * Sets the current filter to Poisson Sampling aka PCF.
  60415. */
  60416. set: function (value) {
  60417. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60418. return;
  60419. }
  60420. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60421. },
  60422. enumerable: true,
  60423. configurable: true
  60424. });
  60425. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60426. /**
  60427. * Gets if the current filter is set to VSM.
  60428. * DEPRECATED. Should use useExponentialShadowMap instead.
  60429. */
  60430. get: function () {
  60431. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60432. return this.useExponentialShadowMap;
  60433. },
  60434. /**
  60435. * Sets the current filter is to VSM.
  60436. * DEPRECATED. Should use useExponentialShadowMap instead.
  60437. */
  60438. set: function (value) {
  60439. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60440. this.useExponentialShadowMap = value;
  60441. },
  60442. enumerable: true,
  60443. configurable: true
  60444. });
  60445. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60446. /**
  60447. * Gets if the current filter is set to blurred VSM.
  60448. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60449. */
  60450. get: function () {
  60451. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60452. return this.useBlurExponentialShadowMap;
  60453. },
  60454. /**
  60455. * Sets the current filter is to blurred VSM.
  60456. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60457. */
  60458. set: function (value) {
  60459. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60460. this.useBlurExponentialShadowMap = value;
  60461. },
  60462. enumerable: true,
  60463. configurable: true
  60464. });
  60465. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60466. /**
  60467. * Gets if the current filter is set to ESM.
  60468. */
  60469. get: function () {
  60470. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60471. },
  60472. /**
  60473. * Sets the current filter is to ESM.
  60474. */
  60475. set: function (value) {
  60476. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60477. return;
  60478. }
  60479. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60485. /**
  60486. * Gets if the current filter is set to filtered ESM.
  60487. */
  60488. get: function () {
  60489. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60490. },
  60491. /**
  60492. * Gets if the current filter is set to filtered ESM.
  60493. */
  60494. set: function (value) {
  60495. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60496. return;
  60497. }
  60498. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60499. },
  60500. enumerable: true,
  60501. configurable: true
  60502. });
  60503. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60504. /**
  60505. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60506. * exponential to prevent steep falloff artifacts).
  60507. */
  60508. get: function () {
  60509. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60510. },
  60511. /**
  60512. * Sets the current filter to "close ESM" (using the inverse of the
  60513. * exponential to prevent steep falloff artifacts).
  60514. */
  60515. set: function (value) {
  60516. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60517. return;
  60518. }
  60519. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60520. },
  60521. enumerable: true,
  60522. configurable: true
  60523. });
  60524. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60525. /**
  60526. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60527. * exponential to prevent steep falloff artifacts).
  60528. */
  60529. get: function () {
  60530. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60531. },
  60532. /**
  60533. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60534. * exponential to prevent steep falloff artifacts).
  60535. */
  60536. set: function (value) {
  60537. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60538. return;
  60539. }
  60540. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60541. },
  60542. enumerable: true,
  60543. configurable: true
  60544. });
  60545. /**
  60546. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60547. * 0 means strongest and 1 would means no shadow.
  60548. * @returns the darkness.
  60549. */
  60550. ShadowGenerator.prototype.getDarkness = function () {
  60551. return this._darkness;
  60552. };
  60553. /**
  60554. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60555. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60556. * @returns the shadow generator allowing fluent coding.
  60557. */
  60558. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60559. if (darkness >= 1.0)
  60560. this._darkness = 1.0;
  60561. else if (darkness <= 0.0)
  60562. this._darkness = 0.0;
  60563. else
  60564. this._darkness = darkness;
  60565. return this;
  60566. };
  60567. /**
  60568. * Sets the ability to have transparent shadow (boolean).
  60569. * @param transparent True if transparent else False
  60570. * @returns the shadow generator allowing fluent coding
  60571. */
  60572. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60573. this._transparencyShadow = transparent;
  60574. return this;
  60575. };
  60576. /**
  60577. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60578. * @returns The render target texture if present otherwise, null
  60579. */
  60580. ShadowGenerator.prototype.getShadowMap = function () {
  60581. return this._shadowMap;
  60582. };
  60583. /**
  60584. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60585. * @returns The render target texture if the shadow map is present otherwise, null
  60586. */
  60587. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60588. if (this._shadowMap2) {
  60589. return this._shadowMap2;
  60590. }
  60591. return this._shadowMap;
  60592. };
  60593. /**
  60594. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60595. * @param mesh Mesh to add
  60596. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60597. * @returns the Shadow Generator itself
  60598. */
  60599. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60600. if (includeDescendants === void 0) { includeDescendants = true; }
  60601. if (!this._shadowMap) {
  60602. return this;
  60603. }
  60604. if (!this._shadowMap.renderList) {
  60605. this._shadowMap.renderList = [];
  60606. }
  60607. this._shadowMap.renderList.push(mesh);
  60608. if (includeDescendants) {
  60609. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60610. }
  60611. return this;
  60612. var _a;
  60613. };
  60614. /**
  60615. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60616. * @param mesh Mesh to remove
  60617. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60618. * @returns the Shadow Generator itself
  60619. */
  60620. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60621. if (includeDescendants === void 0) { includeDescendants = true; }
  60622. if (!this._shadowMap || !this._shadowMap.renderList) {
  60623. return this;
  60624. }
  60625. var index = this._shadowMap.renderList.indexOf(mesh);
  60626. if (index !== -1) {
  60627. this._shadowMap.renderList.splice(index, 1);
  60628. }
  60629. if (includeDescendants) {
  60630. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60631. var child = _a[_i];
  60632. this.removeShadowCaster(child);
  60633. }
  60634. }
  60635. return this;
  60636. };
  60637. /**
  60638. * Returns the associated light object.
  60639. * @returns the light generating the shadow
  60640. */
  60641. ShadowGenerator.prototype.getLight = function () {
  60642. return this._light;
  60643. };
  60644. ShadowGenerator.prototype._initializeGenerator = function () {
  60645. this._light._markMeshesAsLightDirty();
  60646. this._initializeShadowMap();
  60647. };
  60648. ShadowGenerator.prototype._initializeShadowMap = function () {
  60649. var _this = this;
  60650. // Render target
  60651. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60652. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60653. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60654. this._shadowMap.anisotropicFilteringLevel = 1;
  60655. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60656. this._shadowMap.renderParticles = false;
  60657. this._shadowMap.ignoreCameraViewport = true;
  60658. // Record Face Index before render.
  60659. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60660. _this._currentFaceIndex = faceIndex;
  60661. });
  60662. // Custom render function.
  60663. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60664. // Blur if required afer render.
  60665. this._shadowMap.onAfterUnbindObservable.add(function () {
  60666. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60667. return;
  60668. }
  60669. var shadowMap = _this.getShadowMapForRendering();
  60670. if (shadowMap) {
  60671. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60672. }
  60673. });
  60674. // Clear according to the chosen filter.
  60675. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60676. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60677. this._shadowMap.onClearObservable.add(function (engine) {
  60678. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60679. engine.clear(zero, true, true, true);
  60680. }
  60681. else {
  60682. engine.clear(one, true, true, true);
  60683. }
  60684. });
  60685. };
  60686. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60687. var _this = this;
  60688. var engine = this._scene.getEngine();
  60689. var targetSize = this._mapSize / this.blurScale;
  60690. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60691. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60692. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60693. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60694. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60695. }
  60696. if (this.useKernelBlur) {
  60697. 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);
  60698. this._kernelBlurXPostprocess.width = targetSize;
  60699. this._kernelBlurXPostprocess.height = targetSize;
  60700. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60701. effect.setTexture("textureSampler", _this._shadowMap);
  60702. });
  60703. 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);
  60704. this._kernelBlurXPostprocess.autoClear = false;
  60705. this._kernelBlurYPostprocess.autoClear = false;
  60706. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60707. this._kernelBlurXPostprocess.packedFloat = true;
  60708. this._kernelBlurYPostprocess.packedFloat = true;
  60709. }
  60710. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60711. }
  60712. else {
  60713. 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);
  60714. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60715. effect.setFloat2("screenSize", targetSize, targetSize);
  60716. effect.setTexture("textureSampler", _this._shadowMap);
  60717. });
  60718. this._boxBlurPostprocess.autoClear = false;
  60719. this._blurPostProcesses = [this._boxBlurPostprocess];
  60720. }
  60721. };
  60722. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60723. var index;
  60724. var engine = this._scene.getEngine();
  60725. if (depthOnlySubMeshes.length) {
  60726. engine.setColorWrite(false);
  60727. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60728. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60729. }
  60730. engine.setColorWrite(true);
  60731. }
  60732. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60733. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60734. }
  60735. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60736. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60737. }
  60738. if (this._transparencyShadow) {
  60739. for (index = 0; index < transparentSubMeshes.length; index++) {
  60740. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60741. }
  60742. }
  60743. };
  60744. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60745. var _this = this;
  60746. var mesh = subMesh.getRenderingMesh();
  60747. var scene = this._scene;
  60748. var engine = scene.getEngine();
  60749. var material = subMesh.getMaterial();
  60750. if (!material) {
  60751. return;
  60752. }
  60753. // Culling
  60754. engine.setState(material.backFaceCulling);
  60755. // Managing instances
  60756. var batch = mesh._getInstancesRenderList(subMesh._id);
  60757. if (batch.mustReturn) {
  60758. return;
  60759. }
  60760. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60761. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60762. engine.enableEffect(this._effect);
  60763. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60764. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60765. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60766. this._effect.setVector3("lightPosition", this.getLight().position);
  60767. if (scene.activeCamera) {
  60768. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60769. }
  60770. // Alpha test
  60771. if (material && material.needAlphaTesting()) {
  60772. var alphaTexture = material.getAlphaTestTexture();
  60773. if (alphaTexture) {
  60774. this._effect.setTexture("diffuseSampler", alphaTexture);
  60775. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60776. }
  60777. }
  60778. // Bones
  60779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60780. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60781. }
  60782. if (this.forceBackFacesOnly) {
  60783. engine.setState(true, 0, false, true);
  60784. }
  60785. // Draw
  60786. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60787. if (this.forceBackFacesOnly) {
  60788. engine.setState(true, 0, false, false);
  60789. }
  60790. }
  60791. else {
  60792. // Need to reset refresh rate of the shadowMap
  60793. if (this._shadowMap) {
  60794. this._shadowMap.resetRefreshCounter();
  60795. }
  60796. }
  60797. };
  60798. ShadowGenerator.prototype._applyFilterValues = function () {
  60799. if (!this._shadowMap) {
  60800. return;
  60801. }
  60802. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60803. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60804. }
  60805. else {
  60806. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60807. }
  60808. };
  60809. /**
  60810. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60811. * @param onCompiled Callback triggered at the and of the effects compilation
  60812. * @param options Sets of optional options forcing the compilation with different modes
  60813. */
  60814. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60815. var _this = this;
  60816. var localOptions = __assign({ useInstances: false }, options);
  60817. var shadowMap = this.getShadowMap();
  60818. if (!shadowMap) {
  60819. if (onCompiled) {
  60820. onCompiled(this);
  60821. }
  60822. return;
  60823. }
  60824. var renderList = shadowMap.renderList;
  60825. if (!renderList) {
  60826. if (onCompiled) {
  60827. onCompiled(this);
  60828. }
  60829. return;
  60830. }
  60831. var subMeshes = new Array();
  60832. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60833. var mesh = renderList_1[_i];
  60834. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60835. }
  60836. if (subMeshes.length === 0) {
  60837. if (onCompiled) {
  60838. onCompiled(this);
  60839. }
  60840. return;
  60841. }
  60842. var currentIndex = 0;
  60843. var checkReady = function () {
  60844. if (!_this._scene || !_this._scene.getEngine()) {
  60845. return;
  60846. }
  60847. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60848. currentIndex++;
  60849. if (currentIndex >= subMeshes.length) {
  60850. if (onCompiled) {
  60851. onCompiled(_this);
  60852. }
  60853. return;
  60854. }
  60855. }
  60856. setTimeout(checkReady, 16);
  60857. };
  60858. checkReady();
  60859. };
  60860. /**
  60861. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60862. * @param options Sets of optional options forcing the compilation with different modes
  60863. * @returns A promise that resolves when the compilation completes
  60864. */
  60865. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60866. var _this = this;
  60867. return new Promise(function (resolve) {
  60868. _this.forceCompilation(function () {
  60869. resolve();
  60870. }, options);
  60871. });
  60872. };
  60873. /**
  60874. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60875. * @param subMesh The submesh we want to render in the shadow map
  60876. * @param useInstances Defines wether will draw in the map using instances
  60877. * @returns true if ready otherwise, false
  60878. */
  60879. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60880. var defines = [];
  60881. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60882. defines.push("#define FLOAT");
  60883. }
  60884. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60885. defines.push("#define ESM");
  60886. }
  60887. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60888. var mesh = subMesh.getMesh();
  60889. var material = subMesh.getMaterial();
  60890. // Alpha test
  60891. if (material && material.needAlphaTesting()) {
  60892. var alphaTexture = material.getAlphaTestTexture();
  60893. if (alphaTexture) {
  60894. defines.push("#define ALPHATEST");
  60895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60896. attribs.push(BABYLON.VertexBuffer.UVKind);
  60897. defines.push("#define UV1");
  60898. }
  60899. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60900. if (alphaTexture.coordinatesIndex === 1) {
  60901. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60902. defines.push("#define UV2");
  60903. }
  60904. }
  60905. }
  60906. }
  60907. // Bones
  60908. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60909. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60910. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60911. if (mesh.numBoneInfluencers > 4) {
  60912. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60913. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60914. }
  60915. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60916. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60917. }
  60918. else {
  60919. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60920. }
  60921. // Instances
  60922. if (useInstances) {
  60923. defines.push("#define INSTANCES");
  60924. attribs.push("world0");
  60925. attribs.push("world1");
  60926. attribs.push("world2");
  60927. attribs.push("world3");
  60928. }
  60929. // Get correct effect
  60930. var join = defines.join("\n");
  60931. if (this._cachedDefines !== join) {
  60932. this._cachedDefines = join;
  60933. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60934. }
  60935. if (!this._effect.isReady()) {
  60936. return false;
  60937. }
  60938. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60939. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60940. this._initializeBlurRTTAndPostProcesses();
  60941. }
  60942. }
  60943. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60944. return false;
  60945. }
  60946. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60947. return false;
  60948. }
  60949. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60950. return false;
  60951. }
  60952. return true;
  60953. };
  60954. /**
  60955. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60956. * @param defines Defines of the material we want to update
  60957. * @param lightIndex Index of the light in the enabled light list of the material
  60958. */
  60959. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60960. var scene = this._scene;
  60961. var light = this._light;
  60962. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60963. return;
  60964. }
  60965. defines["SHADOW" + lightIndex] = true;
  60966. if (this.usePoissonSampling) {
  60967. defines["SHADOWPCF" + lightIndex] = true;
  60968. }
  60969. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60970. defines["SHADOWESM" + lightIndex] = true;
  60971. }
  60972. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60973. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60974. }
  60975. if (light.needCube()) {
  60976. defines["SHADOWCUBE" + lightIndex] = true;
  60977. }
  60978. };
  60979. /**
  60980. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60981. * defined in the generator but impacting the effect).
  60982. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60983. * @param effect The effect we are binfing the information for
  60984. */
  60985. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60986. var light = this._light;
  60987. var scene = this._scene;
  60988. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60989. return;
  60990. }
  60991. var camera = scene.activeCamera;
  60992. if (!camera) {
  60993. return;
  60994. }
  60995. var shadowMap = this.getShadowMap();
  60996. if (!shadowMap) {
  60997. return;
  60998. }
  60999. if (!light.needCube()) {
  61000. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61001. }
  61002. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61003. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61004. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61005. };
  61006. /**
  61007. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61008. * (eq to shadow prjection matrix * light transform matrix)
  61009. * @returns The transform matrix used to create the shadow map
  61010. */
  61011. ShadowGenerator.prototype.getTransformMatrix = function () {
  61012. var scene = this._scene;
  61013. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61014. return this._transformMatrix;
  61015. }
  61016. this._currentRenderID = scene.getRenderId();
  61017. this._currentFaceIndexCache = this._currentFaceIndex;
  61018. var lightPosition = this._light.position;
  61019. if (this._light.computeTransformedInformation()) {
  61020. lightPosition = this._light.transformedPosition;
  61021. }
  61022. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61023. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61024. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61025. }
  61026. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61027. this._cachedPosition.copyFrom(lightPosition);
  61028. this._cachedDirection.copyFrom(this._lightDirection);
  61029. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61030. var shadowMap = this.getShadowMap();
  61031. if (shadowMap) {
  61032. var renderList = shadowMap.renderList;
  61033. if (renderList) {
  61034. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61035. }
  61036. }
  61037. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61038. }
  61039. return this._transformMatrix;
  61040. };
  61041. /**
  61042. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61043. * Cube and 2D textures for instance.
  61044. */
  61045. ShadowGenerator.prototype.recreateShadowMap = function () {
  61046. var shadowMap = this._shadowMap;
  61047. if (!shadowMap) {
  61048. return;
  61049. }
  61050. // Track render list.
  61051. var renderList = shadowMap.renderList;
  61052. // Clean up existing data.
  61053. this._disposeRTTandPostProcesses();
  61054. // Reinitializes.
  61055. this._initializeGenerator();
  61056. // Reaffect the filter to ensure a correct fallback if necessary.
  61057. this.filter = this.filter;
  61058. // Reaffect the filter.
  61059. this._applyFilterValues();
  61060. // Reaffect Render List.
  61061. this._shadowMap.renderList = renderList;
  61062. };
  61063. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61064. if (this._shadowMap2) {
  61065. this._shadowMap2.dispose();
  61066. this._shadowMap2 = null;
  61067. }
  61068. if (this._boxBlurPostprocess) {
  61069. this._boxBlurPostprocess.dispose();
  61070. this._boxBlurPostprocess = null;
  61071. }
  61072. if (this._kernelBlurXPostprocess) {
  61073. this._kernelBlurXPostprocess.dispose();
  61074. this._kernelBlurXPostprocess = null;
  61075. }
  61076. if (this._kernelBlurYPostprocess) {
  61077. this._kernelBlurYPostprocess.dispose();
  61078. this._kernelBlurYPostprocess = null;
  61079. }
  61080. this._blurPostProcesses = [];
  61081. };
  61082. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61083. if (this._shadowMap) {
  61084. this._shadowMap.dispose();
  61085. this._shadowMap = null;
  61086. }
  61087. this._disposeBlurPostProcesses();
  61088. };
  61089. /**
  61090. * Disposes the ShadowGenerator.
  61091. * Returns nothing.
  61092. */
  61093. ShadowGenerator.prototype.dispose = function () {
  61094. this._disposeRTTandPostProcesses();
  61095. if (this._light) {
  61096. this._light._shadowGenerator = null;
  61097. this._light._markMeshesAsLightDirty();
  61098. }
  61099. };
  61100. /**
  61101. * Serializes the shadow generator setup to a json object.
  61102. * @returns The serialized JSON object
  61103. */
  61104. ShadowGenerator.prototype.serialize = function () {
  61105. var serializationObject = {};
  61106. var shadowMap = this.getShadowMap();
  61107. if (!shadowMap) {
  61108. return serializationObject;
  61109. }
  61110. serializationObject.lightId = this._light.id;
  61111. serializationObject.mapSize = shadowMap.getRenderSize();
  61112. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61113. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61114. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61115. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61116. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61117. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61118. serializationObject.depthScale = this.depthScale;
  61119. serializationObject.darkness = this.getDarkness();
  61120. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61121. serializationObject.blurKernel = this.blurKernel;
  61122. serializationObject.blurScale = this.blurScale;
  61123. serializationObject.useKernelBlur = this.useKernelBlur;
  61124. serializationObject.transparencyShadow = this._transparencyShadow;
  61125. serializationObject.renderList = [];
  61126. if (shadowMap.renderList) {
  61127. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61128. var mesh = shadowMap.renderList[meshIndex];
  61129. serializationObject.renderList.push(mesh.id);
  61130. }
  61131. }
  61132. return serializationObject;
  61133. };
  61134. /**
  61135. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61136. * @param parsedShadowGenerator The JSON object to parse
  61137. * @param scene The scene to create the shadow map for
  61138. * @returns The parsed shadow generator
  61139. */
  61140. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61141. //casting to point light, as light is missing the position attr and typescript complains.
  61142. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61143. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61144. var shadowMap = shadowGenerator.getShadowMap();
  61145. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61146. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61147. meshes.forEach(function (mesh) {
  61148. if (!shadowMap) {
  61149. return;
  61150. }
  61151. if (!shadowMap.renderList) {
  61152. shadowMap.renderList = [];
  61153. }
  61154. shadowMap.renderList.push(mesh);
  61155. });
  61156. }
  61157. if (parsedShadowGenerator.usePoissonSampling) {
  61158. shadowGenerator.usePoissonSampling = true;
  61159. }
  61160. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61161. shadowGenerator.useExponentialShadowMap = true;
  61162. }
  61163. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61164. shadowGenerator.useBlurExponentialShadowMap = true;
  61165. }
  61166. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61167. shadowGenerator.useCloseExponentialShadowMap = true;
  61168. }
  61169. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61170. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61171. }
  61172. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61173. shadowGenerator.useExponentialShadowMap = true;
  61174. }
  61175. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61176. shadowGenerator.useBlurExponentialShadowMap = true;
  61177. }
  61178. if (parsedShadowGenerator.depthScale) {
  61179. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61180. }
  61181. if (parsedShadowGenerator.blurScale) {
  61182. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61183. }
  61184. if (parsedShadowGenerator.blurBoxOffset) {
  61185. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61186. }
  61187. if (parsedShadowGenerator.useKernelBlur) {
  61188. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61189. }
  61190. if (parsedShadowGenerator.blurKernel) {
  61191. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61192. }
  61193. if (parsedShadowGenerator.bias !== undefined) {
  61194. shadowGenerator.bias = parsedShadowGenerator.bias;
  61195. }
  61196. if (parsedShadowGenerator.darkness) {
  61197. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61198. }
  61199. if (parsedShadowGenerator.transparencyShadow) {
  61200. shadowGenerator.setTransparencyShadow(true);
  61201. }
  61202. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61203. return shadowGenerator;
  61204. };
  61205. ShadowGenerator._FILTER_NONE = 0;
  61206. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61207. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61208. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61209. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61210. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61211. return ShadowGenerator;
  61212. }());
  61213. BABYLON.ShadowGenerator = ShadowGenerator;
  61214. })(BABYLON || (BABYLON = {}));
  61215. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61216. var BABYLON;
  61217. (function (BABYLON) {
  61218. var DefaultLoadingScreen = /** @class */ (function () {
  61219. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61220. if (_loadingText === void 0) { _loadingText = ""; }
  61221. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61222. var _this = this;
  61223. this._renderingCanvas = _renderingCanvas;
  61224. this._loadingText = _loadingText;
  61225. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61226. // Resize
  61227. this._resizeLoadingUI = function () {
  61228. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61229. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61230. if (!_this._loadingDiv) {
  61231. return;
  61232. }
  61233. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61234. _this._loadingDiv.style.left = canvasRect.left + "px";
  61235. _this._loadingDiv.style.top = canvasRect.top + "px";
  61236. _this._loadingDiv.style.width = canvasRect.width + "px";
  61237. _this._loadingDiv.style.height = canvasRect.height + "px";
  61238. };
  61239. }
  61240. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61241. if (this._loadingDiv) {
  61242. // Do not add a loading screen if there is already one
  61243. return;
  61244. }
  61245. this._loadingDiv = document.createElement("div");
  61246. this._loadingDiv.id = "babylonjsLoadingDiv";
  61247. this._loadingDiv.style.opacity = "0";
  61248. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61249. this._loadingDiv.style.pointerEvents = "none";
  61250. // Loading text
  61251. this._loadingTextDiv = document.createElement("div");
  61252. this._loadingTextDiv.style.position = "absolute";
  61253. this._loadingTextDiv.style.left = "0";
  61254. this._loadingTextDiv.style.top = "50%";
  61255. this._loadingTextDiv.style.marginTop = "80px";
  61256. this._loadingTextDiv.style.width = "100%";
  61257. this._loadingTextDiv.style.height = "20px";
  61258. this._loadingTextDiv.style.fontFamily = "Arial";
  61259. this._loadingTextDiv.style.fontSize = "14px";
  61260. this._loadingTextDiv.style.color = "white";
  61261. this._loadingTextDiv.style.textAlign = "center";
  61262. this._loadingTextDiv.innerHTML = "Loading";
  61263. this._loadingDiv.appendChild(this._loadingTextDiv);
  61264. //set the predefined text
  61265. this._loadingTextDiv.innerHTML = this._loadingText;
  61266. // Generating keyframes
  61267. var style = document.createElement('style');
  61268. style.type = 'text/css';
  61269. 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 }";
  61270. style.innerHTML = keyFrames;
  61271. document.getElementsByTagName('head')[0].appendChild(style);
  61272. // Loading img
  61273. var imgBack = new Image();
  61274. 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";
  61275. imgBack.style.position = "absolute";
  61276. imgBack.style.left = "50%";
  61277. imgBack.style.top = "50%";
  61278. imgBack.style.marginLeft = "-60px";
  61279. imgBack.style.marginTop = "-60px";
  61280. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61281. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61282. imgBack.style.transformOrigin = "50% 50%";
  61283. imgBack.style.webkitTransformOrigin = "50% 50%";
  61284. this._loadingDiv.appendChild(imgBack);
  61285. this._resizeLoadingUI();
  61286. window.addEventListener("resize", this._resizeLoadingUI);
  61287. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61288. document.body.appendChild(this._loadingDiv);
  61289. this._loadingDiv.style.opacity = "1";
  61290. };
  61291. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61292. var _this = this;
  61293. if (!this._loadingDiv) {
  61294. return;
  61295. }
  61296. var onTransitionEnd = function () {
  61297. if (!_this._loadingDiv) {
  61298. return;
  61299. }
  61300. document.body.removeChild(_this._loadingDiv);
  61301. window.removeEventListener("resize", _this._resizeLoadingUI);
  61302. _this._loadingDiv = null;
  61303. };
  61304. this._loadingDiv.style.opacity = "0";
  61305. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61306. };
  61307. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61308. set: function (text) {
  61309. this._loadingText = text;
  61310. if (this._loadingTextDiv) {
  61311. this._loadingTextDiv.innerHTML = this._loadingText;
  61312. }
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61318. get: function () {
  61319. return this._loadingDivBackgroundColor;
  61320. },
  61321. set: function (color) {
  61322. this._loadingDivBackgroundColor = color;
  61323. if (!this._loadingDiv) {
  61324. return;
  61325. }
  61326. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61327. },
  61328. enumerable: true,
  61329. configurable: true
  61330. });
  61331. return DefaultLoadingScreen;
  61332. }());
  61333. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61334. })(BABYLON || (BABYLON = {}));
  61335. //# sourceMappingURL=babylon.loadingScreen.js.map
  61336. var BABYLON;
  61337. (function (BABYLON) {
  61338. var SceneLoaderProgressEvent = /** @class */ (function () {
  61339. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61340. this.lengthComputable = lengthComputable;
  61341. this.loaded = loaded;
  61342. this.total = total;
  61343. }
  61344. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61345. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61346. };
  61347. return SceneLoaderProgressEvent;
  61348. }());
  61349. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61350. var SceneLoader = /** @class */ (function () {
  61351. function SceneLoader() {
  61352. }
  61353. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61354. get: function () {
  61355. return 0;
  61356. },
  61357. enumerable: true,
  61358. configurable: true
  61359. });
  61360. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61361. get: function () {
  61362. return 1;
  61363. },
  61364. enumerable: true,
  61365. configurable: true
  61366. });
  61367. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61368. get: function () {
  61369. return 2;
  61370. },
  61371. enumerable: true,
  61372. configurable: true
  61373. });
  61374. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61375. get: function () {
  61376. return 3;
  61377. },
  61378. enumerable: true,
  61379. configurable: true
  61380. });
  61381. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61382. get: function () {
  61383. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61384. },
  61385. set: function (value) {
  61386. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61387. },
  61388. enumerable: true,
  61389. configurable: true
  61390. });
  61391. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61392. get: function () {
  61393. return SceneLoader._ShowLoadingScreen;
  61394. },
  61395. set: function (value) {
  61396. SceneLoader._ShowLoadingScreen = value;
  61397. },
  61398. enumerable: true,
  61399. configurable: true
  61400. });
  61401. Object.defineProperty(SceneLoader, "loggingLevel", {
  61402. get: function () {
  61403. return SceneLoader._loggingLevel;
  61404. },
  61405. set: function (value) {
  61406. SceneLoader._loggingLevel = value;
  61407. },
  61408. enumerable: true,
  61409. configurable: true
  61410. });
  61411. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61412. get: function () {
  61413. return SceneLoader._CleanBoneMatrixWeights;
  61414. },
  61415. set: function (value) {
  61416. SceneLoader._CleanBoneMatrixWeights = value;
  61417. },
  61418. enumerable: true,
  61419. configurable: true
  61420. });
  61421. SceneLoader._getDefaultPlugin = function () {
  61422. return SceneLoader._registeredPlugins[".babylon"];
  61423. };
  61424. SceneLoader._getPluginForExtension = function (extension) {
  61425. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61426. if (registeredPlugin) {
  61427. return registeredPlugin;
  61428. }
  61429. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61430. return SceneLoader._getDefaultPlugin();
  61431. };
  61432. SceneLoader._getPluginForDirectLoad = function (data) {
  61433. for (var extension in SceneLoader._registeredPlugins) {
  61434. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61435. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61436. return SceneLoader._registeredPlugins[extension];
  61437. }
  61438. }
  61439. return SceneLoader._getDefaultPlugin();
  61440. };
  61441. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61442. if (sceneFilename.name) {
  61443. sceneFilename = sceneFilename.name;
  61444. }
  61445. var queryStringPosition = sceneFilename.indexOf("?");
  61446. if (queryStringPosition !== -1) {
  61447. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61448. }
  61449. var dotPosition = sceneFilename.lastIndexOf(".");
  61450. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61451. return SceneLoader._getPluginForExtension(extension);
  61452. };
  61453. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61454. SceneLoader._getDirectLoad = function (sceneFilename) {
  61455. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61456. return sceneFilename.substr(5);
  61457. }
  61458. return null;
  61459. };
  61460. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61461. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61462. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61463. var plugin;
  61464. if (registeredPlugin.plugin.createPlugin) {
  61465. plugin = registeredPlugin.plugin.createPlugin();
  61466. }
  61467. else {
  61468. plugin = registeredPlugin.plugin;
  61469. }
  61470. var useArrayBuffer = registeredPlugin.isBinary;
  61471. var database;
  61472. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61473. var dataCallback = function (data, responseURL) {
  61474. if (scene.isDisposed) {
  61475. onError("Scene has been disposed");
  61476. return;
  61477. }
  61478. scene.database = database;
  61479. onSuccess(plugin, data, responseURL);
  61480. };
  61481. var request = null;
  61482. var pluginDisposed = false;
  61483. var onDisposeObservable = plugin.onDisposeObservable;
  61484. if (onDisposeObservable) {
  61485. onDisposeObservable.add(function () {
  61486. pluginDisposed = true;
  61487. if (request) {
  61488. request.abort();
  61489. request = null;
  61490. }
  61491. onDispose();
  61492. });
  61493. }
  61494. var manifestChecked = function () {
  61495. if (pluginDisposed) {
  61496. return;
  61497. }
  61498. var url = rootUrl + sceneFilename;
  61499. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61500. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61501. } : undefined, database, useArrayBuffer, function (request, exception) {
  61502. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61503. });
  61504. };
  61505. if (directLoad) {
  61506. dataCallback(directLoad);
  61507. return plugin;
  61508. }
  61509. if (rootUrl.indexOf("file:") === -1) {
  61510. if (scene.getEngine().enableOfflineSupport) {
  61511. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61512. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61513. }
  61514. else {
  61515. manifestChecked();
  61516. }
  61517. }
  61518. else {
  61519. var fileOrString = sceneFilename;
  61520. if (fileOrString.name) {
  61521. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61522. }
  61523. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61524. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61525. }
  61526. else {
  61527. onError("Unable to find file named " + sceneFilename);
  61528. }
  61529. }
  61530. return plugin;
  61531. };
  61532. // Public functions
  61533. SceneLoader.GetPluginForExtension = function (extension) {
  61534. return SceneLoader._getPluginForExtension(extension).plugin;
  61535. };
  61536. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61537. return !!SceneLoader._registeredPlugins[extension];
  61538. };
  61539. SceneLoader.RegisterPlugin = function (plugin) {
  61540. if (typeof plugin.extensions === "string") {
  61541. var extension = plugin.extensions;
  61542. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61543. plugin: plugin,
  61544. isBinary: false
  61545. };
  61546. }
  61547. else {
  61548. var extensions = plugin.extensions;
  61549. Object.keys(extensions).forEach(function (extension) {
  61550. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61551. plugin: plugin,
  61552. isBinary: extensions[extension].isBinary
  61553. };
  61554. });
  61555. }
  61556. };
  61557. /**
  61558. * Import meshes into a scene
  61559. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61560. * @param rootUrl a string that defines the root url for scene and resources
  61561. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61562. * @param scene the instance of BABYLON.Scene to append to
  61563. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61564. * @param onProgress a callback with a progress event for each file being loaded
  61565. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61566. * @param pluginExtension the extension used to determine the plugin
  61567. * @returns The loaded plugin
  61568. */
  61569. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61570. if (onSuccess === void 0) { onSuccess = null; }
  61571. if (onProgress === void 0) { onProgress = null; }
  61572. if (onError === void 0) { onError = null; }
  61573. if (pluginExtension === void 0) { pluginExtension = null; }
  61574. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61575. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61576. return null;
  61577. }
  61578. var loadingToken = {};
  61579. scene._addPendingData(loadingToken);
  61580. var disposeHandler = function () {
  61581. scene._removePendingData(loadingToken);
  61582. };
  61583. var errorHandler = function (message, exception) {
  61584. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61585. if (onError) {
  61586. onError(scene, errorMessage, exception);
  61587. }
  61588. else {
  61589. BABYLON.Tools.Error(errorMessage);
  61590. // should the exception be thrown?
  61591. }
  61592. disposeHandler();
  61593. };
  61594. var progressHandler = onProgress ? function (event) {
  61595. try {
  61596. onProgress(event);
  61597. }
  61598. catch (e) {
  61599. errorHandler("Error in onProgress callback", e);
  61600. }
  61601. } : undefined;
  61602. var successHandler = function (meshes, particleSystems, skeletons) {
  61603. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61604. if (onSuccess) {
  61605. try {
  61606. onSuccess(meshes, particleSystems, skeletons);
  61607. }
  61608. catch (e) {
  61609. errorHandler("Error in onSuccess callback", e);
  61610. }
  61611. }
  61612. scene._removePendingData(loadingToken);
  61613. };
  61614. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61615. if (plugin.rewriteRootURL) {
  61616. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61617. }
  61618. if (sceneFilename === "") {
  61619. if (sceneFilename === "") {
  61620. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61621. }
  61622. }
  61623. if (plugin.importMesh) {
  61624. var syncedPlugin = plugin;
  61625. var meshes = new Array();
  61626. var particleSystems = new Array();
  61627. var skeletons = new Array();
  61628. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61629. return;
  61630. }
  61631. scene.loadingPluginName = plugin.name;
  61632. successHandler(meshes, particleSystems, skeletons);
  61633. }
  61634. else {
  61635. var asyncedPlugin = plugin;
  61636. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61637. scene.loadingPluginName = plugin.name;
  61638. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61639. }).catch(function (error) {
  61640. errorHandler(error.message, error);
  61641. });
  61642. }
  61643. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61644. };
  61645. /**
  61646. * Import meshes into a scene
  61647. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61648. * @param rootUrl a string that defines the root url for scene and resources
  61649. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61650. * @param scene the instance of BABYLON.Scene to append to
  61651. * @param onProgress a callback with a progress event for each file being loaded
  61652. * @param pluginExtension the extension used to determine the plugin
  61653. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61654. */
  61655. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61656. if (onProgress === void 0) { onProgress = null; }
  61657. if (pluginExtension === void 0) { pluginExtension = null; }
  61658. return new Promise(function (resolve, reject) {
  61659. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61660. resolve({
  61661. meshes: meshes,
  61662. particleSystems: particleSystems,
  61663. skeletons: skeletons
  61664. });
  61665. }, onProgress, function (scene, message, exception) {
  61666. reject(exception || new Error(message));
  61667. });
  61668. });
  61669. };
  61670. /**
  61671. * Load a scene
  61672. * @param rootUrl a string that defines the root url for scene and resources
  61673. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61674. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61675. * @param onSuccess a callback with the scene when import succeeds
  61676. * @param onProgress a callback with a progress event for each file being loaded
  61677. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61678. * @param pluginExtension the extension used to determine the plugin
  61679. * @returns The loaded plugin
  61680. */
  61681. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61682. if (onSuccess === void 0) { onSuccess = null; }
  61683. if (onProgress === void 0) { onProgress = null; }
  61684. if (onError === void 0) { onError = null; }
  61685. if (pluginExtension === void 0) { pluginExtension = null; }
  61686. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61687. };
  61688. /**
  61689. * Load a scene
  61690. * @param rootUrl a string that defines the root url for scene and resources
  61691. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61692. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61693. * @param onProgress a callback with a progress event for each file being loaded
  61694. * @param pluginExtension the extension used to determine the plugin
  61695. * @returns The loaded scene
  61696. */
  61697. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61698. if (onProgress === void 0) { onProgress = null; }
  61699. if (pluginExtension === void 0) { pluginExtension = null; }
  61700. return new Promise(function (resolve, reject) {
  61701. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61702. resolve(scene);
  61703. }, onProgress, function (scene, message, exception) {
  61704. reject(exception || new Error(message));
  61705. }, pluginExtension);
  61706. });
  61707. };
  61708. /**
  61709. * Append a scene
  61710. * @param rootUrl a string that defines the root url for scene and resources
  61711. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61712. * @param scene is the instance of BABYLON.Scene to append to
  61713. * @param onSuccess a callback with the scene when import succeeds
  61714. * @param onProgress a callback with a progress event for each file being loaded
  61715. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61716. * @param pluginExtension the extension used to determine the plugin
  61717. * @returns The loaded plugin
  61718. */
  61719. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61720. if (onSuccess === void 0) { onSuccess = null; }
  61721. if (onProgress === void 0) { onProgress = null; }
  61722. if (onError === void 0) { onError = null; }
  61723. if (pluginExtension === void 0) { pluginExtension = null; }
  61724. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61725. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61726. return null;
  61727. }
  61728. if (SceneLoader.ShowLoadingScreen) {
  61729. scene.getEngine().displayLoadingUI();
  61730. }
  61731. var loadingToken = {};
  61732. scene._addPendingData(loadingToken);
  61733. var disposeHandler = function () {
  61734. scene._removePendingData(loadingToken);
  61735. scene.getEngine().hideLoadingUI();
  61736. };
  61737. var errorHandler = function (message, exception) {
  61738. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61739. if (onError) {
  61740. onError(scene, errorMessage, exception);
  61741. }
  61742. else {
  61743. BABYLON.Tools.Error(errorMessage);
  61744. // should the exception be thrown?
  61745. }
  61746. disposeHandler();
  61747. };
  61748. var progressHandler = onProgress ? function (event) {
  61749. try {
  61750. onProgress(event);
  61751. }
  61752. catch (e) {
  61753. errorHandler("Error in onProgress callback", e);
  61754. }
  61755. } : undefined;
  61756. var successHandler = function () {
  61757. if (onSuccess) {
  61758. try {
  61759. onSuccess(scene);
  61760. }
  61761. catch (e) {
  61762. errorHandler("Error in onSuccess callback", e);
  61763. }
  61764. }
  61765. scene._removePendingData(loadingToken);
  61766. };
  61767. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61768. if (sceneFilename === "") {
  61769. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61770. }
  61771. if (plugin.load) {
  61772. var syncedPlugin = plugin;
  61773. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61774. return;
  61775. }
  61776. scene.loadingPluginName = plugin.name;
  61777. successHandler();
  61778. }
  61779. else {
  61780. var asyncedPlugin = plugin;
  61781. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61782. scene.loadingPluginName = plugin.name;
  61783. successHandler();
  61784. }).catch(function (error) {
  61785. errorHandler(error.message, error);
  61786. });
  61787. }
  61788. if (SceneLoader.ShowLoadingScreen) {
  61789. scene.executeWhenReady(function () {
  61790. scene.getEngine().hideLoadingUI();
  61791. });
  61792. }
  61793. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61794. };
  61795. /**
  61796. * Append a scene
  61797. * @param rootUrl a string that defines the root url for scene and resources
  61798. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61799. * @param scene is the instance of BABYLON.Scene to append to
  61800. * @param onProgress a callback with a progress event for each file being loaded
  61801. * @param pluginExtension the extension used to determine the plugin
  61802. * @returns The given scene
  61803. */
  61804. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61805. if (onProgress === void 0) { onProgress = null; }
  61806. if (pluginExtension === void 0) { pluginExtension = null; }
  61807. return new Promise(function (resolve, reject) {
  61808. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61809. resolve(scene);
  61810. }, onProgress, function (scene, message, exception) {
  61811. reject(exception || new Error(message));
  61812. }, pluginExtension);
  61813. });
  61814. };
  61815. /**
  61816. * Load a scene into an asset container
  61817. * @param rootUrl a string that defines the root url for scene and resources
  61818. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61819. * @param scene is the instance of BABYLON.Scene to append to
  61820. * @param onSuccess a callback with the scene when import succeeds
  61821. * @param onProgress a callback with a progress event for each file being loaded
  61822. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61823. * @param pluginExtension the extension used to determine the plugin
  61824. * @returns The loaded plugin
  61825. */
  61826. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61827. if (onSuccess === void 0) { onSuccess = null; }
  61828. if (onProgress === void 0) { onProgress = null; }
  61829. if (onError === void 0) { onError = null; }
  61830. if (pluginExtension === void 0) { pluginExtension = null; }
  61831. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61832. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61833. return null;
  61834. }
  61835. var loadingToken = {};
  61836. scene._addPendingData(loadingToken);
  61837. var disposeHandler = function () {
  61838. scene._removePendingData(loadingToken);
  61839. };
  61840. var errorHandler = function (message, exception) {
  61841. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61842. if (onError) {
  61843. onError(scene, errorMessage, exception);
  61844. }
  61845. else {
  61846. BABYLON.Tools.Error(errorMessage);
  61847. // should the exception be thrown?
  61848. }
  61849. disposeHandler();
  61850. };
  61851. var progressHandler = onProgress ? function (event) {
  61852. try {
  61853. onProgress(event);
  61854. }
  61855. catch (e) {
  61856. errorHandler("Error in onProgress callback", e);
  61857. }
  61858. } : undefined;
  61859. var successHandler = function (assets) {
  61860. if (onSuccess) {
  61861. try {
  61862. onSuccess(assets);
  61863. }
  61864. catch (e) {
  61865. errorHandler("Error in onSuccess callback", e);
  61866. }
  61867. }
  61868. scene._removePendingData(loadingToken);
  61869. };
  61870. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61871. if (plugin.loadAssetContainer) {
  61872. var syncedPlugin = plugin;
  61873. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61874. if (!assetContainer) {
  61875. return;
  61876. }
  61877. scene.loadingPluginName = plugin.name;
  61878. successHandler(assetContainer);
  61879. }
  61880. else if (plugin.loadAssetContainerAsync) {
  61881. var asyncedPlugin = plugin;
  61882. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61883. scene.loadingPluginName = plugin.name;
  61884. successHandler(assetContainer);
  61885. }).catch(function (error) {
  61886. errorHandler(error.message, error);
  61887. });
  61888. }
  61889. else {
  61890. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61891. }
  61892. if (SceneLoader.ShowLoadingScreen) {
  61893. scene.executeWhenReady(function () {
  61894. scene.getEngine().hideLoadingUI();
  61895. });
  61896. }
  61897. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61898. };
  61899. /**
  61900. * Load a scene into an asset container
  61901. * @param rootUrl a string that defines the root url for scene and resources
  61902. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61903. * @param scene is the instance of BABYLON.Scene to append to
  61904. * @param onProgress a callback with a progress event for each file being loaded
  61905. * @param pluginExtension the extension used to determine the plugin
  61906. * @returns The loaded asset container
  61907. */
  61908. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61909. if (onProgress === void 0) { onProgress = null; }
  61910. if (pluginExtension === void 0) { pluginExtension = null; }
  61911. return new Promise(function (resolve, reject) {
  61912. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61913. resolve(assetContainer);
  61914. }, onProgress, function (scene, message, exception) {
  61915. reject(exception || new Error(message));
  61916. }, pluginExtension);
  61917. });
  61918. };
  61919. // Flags
  61920. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61921. SceneLoader._ShowLoadingScreen = true;
  61922. SceneLoader._CleanBoneMatrixWeights = false;
  61923. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61924. // Members
  61925. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61926. SceneLoader._registeredPlugins = {};
  61927. return SceneLoader;
  61928. }());
  61929. BABYLON.SceneLoader = SceneLoader;
  61930. ;
  61931. })(BABYLON || (BABYLON = {}));
  61932. //# sourceMappingURL=babylon.sceneLoader.js.map
  61933. var BABYLON;
  61934. (function (BABYLON) {
  61935. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61936. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61937. var parsedMaterial = parsedData.materials[index];
  61938. if (parsedMaterial.id === id) {
  61939. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61940. }
  61941. }
  61942. return null;
  61943. };
  61944. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61945. for (var i in names) {
  61946. if (mesh.name === names[i]) {
  61947. hierarchyIds.push(mesh.id);
  61948. return true;
  61949. }
  61950. }
  61951. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61952. hierarchyIds.push(mesh.id);
  61953. return true;
  61954. }
  61955. return false;
  61956. };
  61957. var logOperation = function (operation, producer) {
  61958. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61959. };
  61960. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61961. if (addToScene === void 0) { addToScene = false; }
  61962. var container = new BABYLON.AssetContainer(scene);
  61963. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61964. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61965. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61966. // and avoid problems with multiple concurrent .babylon loads.
  61967. var log = "importScene has failed JSON parse";
  61968. try {
  61969. var parsedData = JSON.parse(data);
  61970. log = "";
  61971. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61972. var index;
  61973. var cache;
  61974. // Lights
  61975. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61976. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61977. var parsedLight = parsedData.lights[index];
  61978. var light = BABYLON.Light.Parse(parsedLight, scene);
  61979. if (light) {
  61980. container.lights.push(light);
  61981. log += (index === 0 ? "\n\tLights:" : "");
  61982. log += "\n\t\t" + light.toString(fullDetails);
  61983. }
  61984. }
  61985. }
  61986. // Animations
  61987. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61988. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61989. var parsedAnimation = parsedData.animations[index];
  61990. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61991. scene.animations.push(animation);
  61992. container.animations.push(animation);
  61993. log += (index === 0 ? "\n\tAnimations:" : "");
  61994. log += "\n\t\t" + animation.toString(fullDetails);
  61995. }
  61996. }
  61997. // Materials
  61998. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61999. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62000. var parsedMaterial = parsedData.materials[index];
  62001. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62002. container.materials.push(mat);
  62003. log += (index === 0 ? "\n\tMaterials:" : "");
  62004. log += "\n\t\t" + mat.toString(fullDetails);
  62005. }
  62006. }
  62007. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62008. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62009. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62010. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62011. container.multiMaterials.push(mmat);
  62012. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62013. log += "\n\t\t" + mmat.toString(fullDetails);
  62014. }
  62015. }
  62016. // Morph targets
  62017. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62018. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62019. var managerData = _a[_i];
  62020. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62021. }
  62022. }
  62023. // Skeletons
  62024. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62025. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62026. var parsedSkeleton = parsedData.skeletons[index];
  62027. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62028. container.skeletons.push(skeleton);
  62029. log += (index === 0 ? "\n\tSkeletons:" : "");
  62030. log += "\n\t\t" + skeleton.toString(fullDetails);
  62031. }
  62032. }
  62033. // Geometries
  62034. var geometries = parsedData.geometries;
  62035. if (geometries !== undefined && geometries !== null) {
  62036. var addedGeometry = new Array();
  62037. // Boxes
  62038. var boxes = geometries.boxes;
  62039. if (boxes !== undefined && boxes !== null) {
  62040. for (index = 0, cache = boxes.length; index < cache; index++) {
  62041. var parsedBox = boxes[index];
  62042. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62043. }
  62044. }
  62045. // Spheres
  62046. var spheres = geometries.spheres;
  62047. if (spheres !== undefined && spheres !== null) {
  62048. for (index = 0, cache = spheres.length; index < cache; index++) {
  62049. var parsedSphere = spheres[index];
  62050. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62051. }
  62052. }
  62053. // Cylinders
  62054. var cylinders = geometries.cylinders;
  62055. if (cylinders !== undefined && cylinders !== null) {
  62056. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62057. var parsedCylinder = cylinders[index];
  62058. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62059. }
  62060. }
  62061. // Toruses
  62062. var toruses = geometries.toruses;
  62063. if (toruses !== undefined && toruses !== null) {
  62064. for (index = 0, cache = toruses.length; index < cache; index++) {
  62065. var parsedTorus = toruses[index];
  62066. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62067. }
  62068. }
  62069. // Grounds
  62070. var grounds = geometries.grounds;
  62071. if (grounds !== undefined && grounds !== null) {
  62072. for (index = 0, cache = grounds.length; index < cache; index++) {
  62073. var parsedGround = grounds[index];
  62074. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62075. }
  62076. }
  62077. // Planes
  62078. var planes = geometries.planes;
  62079. if (planes !== undefined && planes !== null) {
  62080. for (index = 0, cache = planes.length; index < cache; index++) {
  62081. var parsedPlane = planes[index];
  62082. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62083. }
  62084. }
  62085. // TorusKnots
  62086. var torusKnots = geometries.torusKnots;
  62087. if (torusKnots !== undefined && torusKnots !== null) {
  62088. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62089. var parsedTorusKnot = torusKnots[index];
  62090. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62091. }
  62092. }
  62093. // VertexData
  62094. var vertexData = geometries.vertexData;
  62095. if (vertexData !== undefined && vertexData !== null) {
  62096. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62097. var parsedVertexData = vertexData[index];
  62098. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62099. }
  62100. }
  62101. addedGeometry.forEach(function (g) {
  62102. if (g) {
  62103. container.geometries.push(g);
  62104. }
  62105. });
  62106. }
  62107. // Transform nodes
  62108. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62109. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62110. var parsedTransformNode = parsedData.transformNodes[index];
  62111. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62112. container.transformNodes.push(node);
  62113. }
  62114. }
  62115. // Meshes
  62116. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62117. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62118. var parsedMesh = parsedData.meshes[index];
  62119. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62120. container.meshes.push(mesh);
  62121. log += (index === 0 ? "\n\tMeshes:" : "");
  62122. log += "\n\t\t" + mesh.toString(fullDetails);
  62123. }
  62124. }
  62125. // Cameras
  62126. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62127. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62128. var parsedCamera = parsedData.cameras[index];
  62129. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62130. container.cameras.push(camera);
  62131. log += (index === 0 ? "\n\tCameras:" : "");
  62132. log += "\n\t\t" + camera.toString(fullDetails);
  62133. }
  62134. }
  62135. // Browsing all the graph to connect the dots
  62136. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62137. var camera = scene.cameras[index];
  62138. if (camera._waitingParentId) {
  62139. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62140. camera._waitingParentId = null;
  62141. }
  62142. }
  62143. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62144. var light_1 = scene.lights[index];
  62145. if (light_1 && light_1._waitingParentId) {
  62146. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62147. light_1._waitingParentId = null;
  62148. }
  62149. }
  62150. // Sounds
  62151. // TODO: add sound
  62152. var loadedSounds = [];
  62153. var loadedSound;
  62154. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62155. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62156. var parsedSound = parsedData.sounds[index];
  62157. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62158. if (!parsedSound.url)
  62159. parsedSound.url = parsedSound.name;
  62160. if (!loadedSounds[parsedSound.url]) {
  62161. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62162. loadedSounds[parsedSound.url] = loadedSound;
  62163. container.sounds.push(loadedSound);
  62164. }
  62165. else {
  62166. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62167. }
  62168. }
  62169. else {
  62170. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62171. }
  62172. }
  62173. }
  62174. loadedSounds = [];
  62175. // Connect parents & children and parse actions
  62176. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62177. var transformNode = scene.transformNodes[index];
  62178. if (transformNode._waitingParentId) {
  62179. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62180. transformNode._waitingParentId = null;
  62181. }
  62182. }
  62183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62184. var mesh = scene.meshes[index];
  62185. if (mesh._waitingParentId) {
  62186. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62187. mesh._waitingParentId = null;
  62188. }
  62189. if (mesh._waitingActions) {
  62190. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62191. mesh._waitingActions = null;
  62192. }
  62193. }
  62194. // freeze world matrix application
  62195. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62196. var currentMesh = scene.meshes[index];
  62197. if (currentMesh._waitingFreezeWorldMatrix) {
  62198. currentMesh.freezeWorldMatrix();
  62199. currentMesh._waitingFreezeWorldMatrix = null;
  62200. }
  62201. else {
  62202. currentMesh.computeWorldMatrix(true);
  62203. }
  62204. }
  62205. // Particles Systems
  62206. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62207. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62208. var parsedParticleSystem = parsedData.particleSystems[index];
  62209. if (parsedParticleSystem.activeParticleCount) {
  62210. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62211. container.particleSystems.push(ps);
  62212. }
  62213. else {
  62214. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62215. container.particleSystems.push(ps);
  62216. }
  62217. }
  62218. }
  62219. // Lens flares
  62220. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62221. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62222. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62223. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62224. container.lensFlareSystems.push(lf);
  62225. }
  62226. }
  62227. // Shadows
  62228. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62229. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62230. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62231. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62232. container.shadowGenerators.push(sg);
  62233. }
  62234. }
  62235. // Lights exclusions / inclusions
  62236. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62237. var light_2 = scene.lights[index];
  62238. // Excluded check
  62239. if (light_2._excludedMeshesIds.length > 0) {
  62240. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62241. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62242. if (excludedMesh) {
  62243. light_2.excludedMeshes.push(excludedMesh);
  62244. }
  62245. }
  62246. light_2._excludedMeshesIds = [];
  62247. }
  62248. // Included check
  62249. if (light_2._includedOnlyMeshesIds.length > 0) {
  62250. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62251. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62252. if (includedOnlyMesh) {
  62253. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62254. }
  62255. }
  62256. light_2._includedOnlyMeshesIds = [];
  62257. }
  62258. }
  62259. // Actions (scene)
  62260. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62261. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62262. }
  62263. if (!addToScene) {
  62264. container.removeAllFromScene();
  62265. }
  62266. }
  62267. catch (err) {
  62268. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62269. if (onError) {
  62270. onError(msg, err);
  62271. }
  62272. else {
  62273. BABYLON.Tools.Log(msg);
  62274. throw err;
  62275. }
  62276. }
  62277. finally {
  62278. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62279. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62280. }
  62281. }
  62282. return container;
  62283. };
  62284. BABYLON.SceneLoader.RegisterPlugin({
  62285. name: "babylon.js",
  62286. extensions: ".babylon",
  62287. canDirectLoad: function (data) {
  62288. if (data.indexOf("babylon") !== -1) {
  62289. return true;
  62290. }
  62291. return false;
  62292. },
  62293. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62294. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62295. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62296. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62297. // and avoid problems with multiple concurrent .babylon loads.
  62298. var log = "importMesh has failed JSON parse";
  62299. try {
  62300. var parsedData = JSON.parse(data);
  62301. log = "";
  62302. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62303. if (!meshesNames) {
  62304. meshesNames = null;
  62305. }
  62306. else if (!Array.isArray(meshesNames)) {
  62307. meshesNames = [meshesNames];
  62308. }
  62309. var hierarchyIds = new Array();
  62310. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62311. var loadedSkeletonsIds = [];
  62312. var loadedMaterialsIds = [];
  62313. var index;
  62314. var cache;
  62315. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62316. var parsedMesh = parsedData.meshes[index];
  62317. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62318. if (meshesNames !== null) {
  62319. // Remove found mesh name from list.
  62320. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62321. }
  62322. //Geometry?
  62323. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62324. //does the file contain geometries?
  62325. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62326. //find the correct geometry and add it to the scene
  62327. var found = false;
  62328. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62329. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62330. return;
  62331. }
  62332. else {
  62333. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62334. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62335. switch (geometryType) {
  62336. case "boxes":
  62337. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62338. break;
  62339. case "spheres":
  62340. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62341. break;
  62342. case "cylinders":
  62343. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62344. break;
  62345. case "toruses":
  62346. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62347. break;
  62348. case "grounds":
  62349. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62350. break;
  62351. case "planes":
  62352. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62353. break;
  62354. case "torusKnots":
  62355. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62356. break;
  62357. case "vertexData":
  62358. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62359. break;
  62360. }
  62361. found = true;
  62362. }
  62363. });
  62364. }
  62365. });
  62366. if (found === false) {
  62367. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62368. }
  62369. }
  62370. }
  62371. // Material ?
  62372. if (parsedMesh.materialId) {
  62373. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62374. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62375. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62376. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62377. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62378. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62379. var subMatId = parsedMultiMaterial.materials[matIndex];
  62380. loadedMaterialsIds.push(subMatId);
  62381. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62382. if (mat) {
  62383. log += "\n\tMaterial " + mat.toString(fullDetails);
  62384. }
  62385. }
  62386. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62387. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62388. if (mmat) {
  62389. materialFound = true;
  62390. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62391. }
  62392. break;
  62393. }
  62394. }
  62395. }
  62396. if (materialFound === false) {
  62397. loadedMaterialsIds.push(parsedMesh.materialId);
  62398. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62399. if (!mat) {
  62400. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62401. }
  62402. else {
  62403. log += "\n\tMaterial " + mat.toString(fullDetails);
  62404. }
  62405. }
  62406. }
  62407. // Skeleton ?
  62408. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62409. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62410. if (skeletonAlreadyLoaded === false) {
  62411. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62412. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62413. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62414. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62415. skeletons.push(skeleton);
  62416. loadedSkeletonsIds.push(parsedSkeleton.id);
  62417. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62418. }
  62419. }
  62420. }
  62421. }
  62422. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62423. meshes.push(mesh);
  62424. log += "\n\tMesh " + mesh.toString(fullDetails);
  62425. }
  62426. }
  62427. // Connecting parents
  62428. var currentMesh;
  62429. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62430. currentMesh = scene.meshes[index];
  62431. if (currentMesh._waitingParentId) {
  62432. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62433. currentMesh._waitingParentId = null;
  62434. }
  62435. }
  62436. // freeze and compute world matrix application
  62437. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62438. currentMesh = scene.meshes[index];
  62439. if (currentMesh._waitingFreezeWorldMatrix) {
  62440. currentMesh.freezeWorldMatrix();
  62441. currentMesh._waitingFreezeWorldMatrix = null;
  62442. }
  62443. else {
  62444. currentMesh.computeWorldMatrix(true);
  62445. }
  62446. }
  62447. }
  62448. // Particles
  62449. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62450. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62451. var parsedParticleSystem = parsedData.particleSystems[index];
  62452. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62453. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62454. }
  62455. }
  62456. }
  62457. return true;
  62458. }
  62459. catch (err) {
  62460. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62461. if (onError) {
  62462. onError(msg, err);
  62463. }
  62464. else {
  62465. BABYLON.Tools.Log(msg);
  62466. throw err;
  62467. }
  62468. }
  62469. finally {
  62470. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62471. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62472. }
  62473. }
  62474. return false;
  62475. },
  62476. load: function (scene, data, rootUrl, onError) {
  62477. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62478. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62479. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62480. // and avoid problems with multiple concurrent .babylon loads.
  62481. var log = "importScene has failed JSON parse";
  62482. try {
  62483. var parsedData = JSON.parse(data);
  62484. log = "";
  62485. // Scene
  62486. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62487. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62488. }
  62489. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62490. scene.autoClear = parsedData.autoClear;
  62491. }
  62492. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62493. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62494. }
  62495. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62496. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62497. }
  62498. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62499. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62500. }
  62501. // Fog
  62502. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62503. scene.fogMode = parsedData.fogMode;
  62504. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62505. scene.fogStart = parsedData.fogStart;
  62506. scene.fogEnd = parsedData.fogEnd;
  62507. scene.fogDensity = parsedData.fogDensity;
  62508. log += "\tFog mode for scene: ";
  62509. switch (scene.fogMode) {
  62510. // getters not compiling, so using hardcoded
  62511. case 1:
  62512. log += "exp\n";
  62513. break;
  62514. case 2:
  62515. log += "exp2\n";
  62516. break;
  62517. case 3:
  62518. log += "linear\n";
  62519. break;
  62520. }
  62521. }
  62522. //Physics
  62523. if (parsedData.physicsEnabled) {
  62524. var physicsPlugin;
  62525. if (parsedData.physicsEngine === "cannon") {
  62526. physicsPlugin = new BABYLON.CannonJSPlugin();
  62527. }
  62528. else if (parsedData.physicsEngine === "oimo") {
  62529. physicsPlugin = new BABYLON.OimoJSPlugin();
  62530. }
  62531. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62532. //else - default engine, which is currently oimo
  62533. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62534. scene.enablePhysics(physicsGravity, physicsPlugin);
  62535. }
  62536. // Metadata
  62537. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62538. scene.metadata = parsedData.metadata;
  62539. }
  62540. //collisions, if defined. otherwise, default is true
  62541. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62542. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62543. }
  62544. scene.workerCollisions = !!parsedData.workerCollisions;
  62545. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62546. if (!container) {
  62547. return false;
  62548. }
  62549. if (parsedData.autoAnimate) {
  62550. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62551. }
  62552. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62553. scene.setActiveCameraByID(parsedData.activeCameraID);
  62554. }
  62555. // Environment texture
  62556. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62557. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62558. if (parsedData.createDefaultSkybox === true) {
  62559. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62560. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62561. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62562. }
  62563. }
  62564. // Finish
  62565. return true;
  62566. }
  62567. catch (err) {
  62568. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62569. if (onError) {
  62570. onError(msg, err);
  62571. }
  62572. else {
  62573. BABYLON.Tools.Log(msg);
  62574. throw err;
  62575. }
  62576. }
  62577. finally {
  62578. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62579. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62580. }
  62581. }
  62582. return false;
  62583. },
  62584. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62585. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62586. return container;
  62587. }
  62588. });
  62589. })(BABYLON || (BABYLON = {}));
  62590. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62591. var BABYLON;
  62592. (function (BABYLON) {
  62593. var FilesInput = /** @class */ (function () {
  62594. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62595. this.onProcessFileCallback = function () { return true; };
  62596. this._engine = engine;
  62597. this._currentScene = scene;
  62598. this._sceneLoadedCallback = sceneLoadedCallback;
  62599. this._progressCallback = progressCallback;
  62600. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62601. this._textureLoadingCallback = textureLoadingCallback;
  62602. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62603. this._onReloadCallback = onReloadCallback;
  62604. this._errorCallback = errorCallback;
  62605. }
  62606. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62607. var _this = this;
  62608. if (elementToMonitor) {
  62609. this._elementToMonitor = elementToMonitor;
  62610. this._dragEnterHandler = function (e) { _this.drag(e); };
  62611. this._dragOverHandler = function (e) { _this.drag(e); };
  62612. this._dropHandler = function (e) { _this.drop(e); };
  62613. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62614. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62615. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62616. }
  62617. };
  62618. FilesInput.prototype.dispose = function () {
  62619. if (!this._elementToMonitor) {
  62620. return;
  62621. }
  62622. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62623. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62624. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62625. };
  62626. FilesInput.prototype.renderFunction = function () {
  62627. if (this._additionalRenderLoopLogicCallback) {
  62628. this._additionalRenderLoopLogicCallback();
  62629. }
  62630. if (this._currentScene) {
  62631. if (this._textureLoadingCallback) {
  62632. var remaining = this._currentScene.getWaitingItemsCount();
  62633. if (remaining > 0) {
  62634. this._textureLoadingCallback(remaining);
  62635. }
  62636. }
  62637. this._currentScene.render();
  62638. }
  62639. };
  62640. FilesInput.prototype.drag = function (e) {
  62641. e.stopPropagation();
  62642. e.preventDefault();
  62643. };
  62644. FilesInput.prototype.drop = function (eventDrop) {
  62645. eventDrop.stopPropagation();
  62646. eventDrop.preventDefault();
  62647. this.loadFiles(eventDrop);
  62648. };
  62649. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62650. var _this = this;
  62651. var reader = folder.createReader();
  62652. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62653. reader.readEntries(function (entries) {
  62654. remaining.count += entries.length;
  62655. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62656. var entry = entries_1[_i];
  62657. if (entry.isFile) {
  62658. entry.file(function (file) {
  62659. file.correctName = relativePath + file.name;
  62660. files.push(file);
  62661. if (--remaining.count === 0) {
  62662. callback();
  62663. }
  62664. });
  62665. }
  62666. else if (entry.isDirectory) {
  62667. _this._traverseFolder(entry, files, remaining, callback);
  62668. }
  62669. }
  62670. if (--remaining.count) {
  62671. callback();
  62672. }
  62673. });
  62674. };
  62675. FilesInput.prototype._processFiles = function (files) {
  62676. for (var i = 0; i < files.length; i++) {
  62677. var name = files[i].correctName.toLowerCase();
  62678. var extension = name.split('.').pop();
  62679. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62680. continue;
  62681. }
  62682. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62683. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62684. this._sceneFileToLoad = files[i];
  62685. }
  62686. else {
  62687. FilesInput.FilesToLoad[name] = files[i];
  62688. }
  62689. }
  62690. };
  62691. FilesInput.prototype.loadFiles = function (event) {
  62692. var _this = this;
  62693. if (this._startingProcessingFilesCallback)
  62694. this._startingProcessingFilesCallback();
  62695. // Handling data transfer via drag'n'drop
  62696. if (event && event.dataTransfer && event.dataTransfer.files) {
  62697. this._filesToLoad = event.dataTransfer.files;
  62698. }
  62699. // Handling files from input files
  62700. if (event && event.target && event.target.files) {
  62701. this._filesToLoad = event.target.files;
  62702. }
  62703. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62704. var files_1 = new Array();
  62705. var folders = [];
  62706. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62707. for (var i = 0; i < this._filesToLoad.length; i++) {
  62708. var fileToLoad = this._filesToLoad[i];
  62709. var name_1 = fileToLoad.name.toLowerCase();
  62710. var entry = void 0;
  62711. fileToLoad.correctName = name_1;
  62712. if (items) {
  62713. var item = items[i];
  62714. if (item.getAsEntry) {
  62715. entry = item.getAsEntry();
  62716. }
  62717. else if (item.webkitGetAsEntry) {
  62718. entry = item.webkitGetAsEntry();
  62719. }
  62720. }
  62721. if (!entry) {
  62722. files_1.push(fileToLoad);
  62723. }
  62724. else {
  62725. if (entry.isDirectory) {
  62726. folders.push(entry);
  62727. }
  62728. else {
  62729. files_1.push(fileToLoad);
  62730. }
  62731. }
  62732. }
  62733. if (folders.length === 0) {
  62734. this._processFiles(files_1);
  62735. this._processReload();
  62736. }
  62737. else {
  62738. var remaining = { count: folders.length };
  62739. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62740. var folder = folders_1[_i];
  62741. this._traverseFolder(folder, files_1, remaining, function () {
  62742. _this._processFiles(files_1);
  62743. if (remaining.count === 0) {
  62744. _this._processReload();
  62745. }
  62746. });
  62747. }
  62748. }
  62749. }
  62750. };
  62751. FilesInput.prototype._processReload = function () {
  62752. if (this._onReloadCallback) {
  62753. this._onReloadCallback(this._sceneFileToLoad);
  62754. }
  62755. else {
  62756. this.reload();
  62757. }
  62758. };
  62759. FilesInput.prototype.reload = function () {
  62760. var _this = this;
  62761. // If a scene file has been provided
  62762. if (this._sceneFileToLoad) {
  62763. if (this._currentScene) {
  62764. if (BABYLON.Tools.errorsCount > 0) {
  62765. BABYLON.Tools.ClearLogCache();
  62766. }
  62767. this._engine.stopRenderLoop();
  62768. this._currentScene.dispose();
  62769. }
  62770. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62771. if (_this._progressCallback) {
  62772. _this._progressCallback(progress);
  62773. }
  62774. }).then(function (scene) {
  62775. _this._currentScene = scene;
  62776. if (_this._sceneLoadedCallback) {
  62777. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62778. }
  62779. // Wait for textures and shaders to be ready
  62780. _this._currentScene.executeWhenReady(function () {
  62781. _this._engine.runRenderLoop(function () {
  62782. _this.renderFunction();
  62783. });
  62784. });
  62785. }).catch(function (error) {
  62786. if (_this._errorCallback) {
  62787. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62788. }
  62789. });
  62790. }
  62791. else {
  62792. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62793. }
  62794. };
  62795. FilesInput.FilesToLoad = {};
  62796. return FilesInput;
  62797. }());
  62798. BABYLON.FilesInput = FilesInput;
  62799. })(BABYLON || (BABYLON = {}));
  62800. //# sourceMappingURL=babylon.filesInput.js.map
  62801. var BABYLON;
  62802. (function (BABYLON) {
  62803. /**
  62804. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62805. * The underlying implementation relies on an associative array to ensure the best performances.
  62806. * The value can be anything including 'null' but except 'undefined'
  62807. */
  62808. var StringDictionary = /** @class */ (function () {
  62809. function StringDictionary() {
  62810. this._count = 0;
  62811. this._data = {};
  62812. }
  62813. /**
  62814. * This will clear this dictionary and copy the content from the 'source' one.
  62815. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62816. * @param source the dictionary to take the content from and copy to this dictionary
  62817. */
  62818. StringDictionary.prototype.copyFrom = function (source) {
  62819. var _this = this;
  62820. this.clear();
  62821. source.forEach(function (t, v) { return _this.add(t, v); });
  62822. };
  62823. /**
  62824. * Get a value based from its key
  62825. * @param key the given key to get the matching value from
  62826. * @return the value if found, otherwise undefined is returned
  62827. */
  62828. StringDictionary.prototype.get = function (key) {
  62829. var val = this._data[key];
  62830. if (val !== undefined) {
  62831. return val;
  62832. }
  62833. return undefined;
  62834. };
  62835. /**
  62836. * Get a value from its key or add it if it doesn't exist.
  62837. * This method will ensure you that a given key/data will be present in the dictionary.
  62838. * @param key the given key to get the matching value from
  62839. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62840. * The factory will only be invoked if there's no data for the given key.
  62841. * @return the value corresponding to the key.
  62842. */
  62843. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62844. var val = this.get(key);
  62845. if (val !== undefined) {
  62846. return val;
  62847. }
  62848. val = factory(key);
  62849. if (val) {
  62850. this.add(key, val);
  62851. }
  62852. return val;
  62853. };
  62854. /**
  62855. * Get a value from its key if present in the dictionary otherwise add it
  62856. * @param key the key to get the value from
  62857. * @param val if there's no such key/value pair in the dictionary add it with this value
  62858. * @return the value corresponding to the key
  62859. */
  62860. StringDictionary.prototype.getOrAdd = function (key, val) {
  62861. var curVal = this.get(key);
  62862. if (curVal !== undefined) {
  62863. return curVal;
  62864. }
  62865. this.add(key, val);
  62866. return val;
  62867. };
  62868. /**
  62869. * Check if there's a given key in the dictionary
  62870. * @param key the key to check for
  62871. * @return true if the key is present, false otherwise
  62872. */
  62873. StringDictionary.prototype.contains = function (key) {
  62874. return this._data[key] !== undefined;
  62875. };
  62876. /**
  62877. * Add a new key and its corresponding value
  62878. * @param key the key to add
  62879. * @param value the value corresponding to the key
  62880. * @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
  62881. */
  62882. StringDictionary.prototype.add = function (key, value) {
  62883. if (this._data[key] !== undefined) {
  62884. return false;
  62885. }
  62886. this._data[key] = value;
  62887. ++this._count;
  62888. return true;
  62889. };
  62890. StringDictionary.prototype.set = function (key, value) {
  62891. if (this._data[key] === undefined) {
  62892. return false;
  62893. }
  62894. this._data[key] = value;
  62895. return true;
  62896. };
  62897. /**
  62898. * Get the element of the given key and remove it from the dictionary
  62899. * @param key
  62900. */
  62901. StringDictionary.prototype.getAndRemove = function (key) {
  62902. var val = this.get(key);
  62903. if (val !== undefined) {
  62904. delete this._data[key];
  62905. --this._count;
  62906. return val;
  62907. }
  62908. return null;
  62909. };
  62910. /**
  62911. * Remove a key/value from the dictionary.
  62912. * @param key the key to remove
  62913. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62914. */
  62915. StringDictionary.prototype.remove = function (key) {
  62916. if (this.contains(key)) {
  62917. delete this._data[key];
  62918. --this._count;
  62919. return true;
  62920. }
  62921. return false;
  62922. };
  62923. /**
  62924. * Clear the whole content of the dictionary
  62925. */
  62926. StringDictionary.prototype.clear = function () {
  62927. this._data = {};
  62928. this._count = 0;
  62929. };
  62930. Object.defineProperty(StringDictionary.prototype, "count", {
  62931. get: function () {
  62932. return this._count;
  62933. },
  62934. enumerable: true,
  62935. configurable: true
  62936. });
  62937. /**
  62938. * Execute a callback on each key/val of the dictionary.
  62939. * Note that you can remove any element in this dictionary in the callback implementation
  62940. * @param callback the callback to execute on a given key/value pair
  62941. */
  62942. StringDictionary.prototype.forEach = function (callback) {
  62943. for (var cur in this._data) {
  62944. var val = this._data[cur];
  62945. callback(cur, val);
  62946. }
  62947. };
  62948. /**
  62949. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62950. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62951. * Note that you can remove any element in this dictionary in the callback implementation
  62952. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62953. */
  62954. StringDictionary.prototype.first = function (callback) {
  62955. for (var cur in this._data) {
  62956. var val = this._data[cur];
  62957. var res = callback(cur, val);
  62958. if (res) {
  62959. return res;
  62960. }
  62961. }
  62962. return null;
  62963. };
  62964. return StringDictionary;
  62965. }());
  62966. BABYLON.StringDictionary = StringDictionary;
  62967. })(BABYLON || (BABYLON = {}));
  62968. //# sourceMappingURL=babylon.stringDictionary.js.map
  62969. var BABYLON;
  62970. (function (BABYLON) {
  62971. var Tags = /** @class */ (function () {
  62972. function Tags() {
  62973. }
  62974. Tags.EnableFor = function (obj) {
  62975. obj._tags = obj._tags || {};
  62976. obj.hasTags = function () {
  62977. return Tags.HasTags(obj);
  62978. };
  62979. obj.addTags = function (tagsString) {
  62980. return Tags.AddTagsTo(obj, tagsString);
  62981. };
  62982. obj.removeTags = function (tagsString) {
  62983. return Tags.RemoveTagsFrom(obj, tagsString);
  62984. };
  62985. obj.matchesTagsQuery = function (tagsQuery) {
  62986. return Tags.MatchesQuery(obj, tagsQuery);
  62987. };
  62988. };
  62989. Tags.DisableFor = function (obj) {
  62990. delete obj._tags;
  62991. delete obj.hasTags;
  62992. delete obj.addTags;
  62993. delete obj.removeTags;
  62994. delete obj.matchesTagsQuery;
  62995. };
  62996. Tags.HasTags = function (obj) {
  62997. if (!obj._tags) {
  62998. return false;
  62999. }
  63000. return !BABYLON.Tools.IsEmpty(obj._tags);
  63001. };
  63002. Tags.GetTags = function (obj, asString) {
  63003. if (asString === void 0) { asString = true; }
  63004. if (!obj._tags) {
  63005. return null;
  63006. }
  63007. if (asString) {
  63008. var tagsArray = [];
  63009. for (var tag in obj._tags) {
  63010. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63011. tagsArray.push(tag);
  63012. }
  63013. }
  63014. return tagsArray.join(" ");
  63015. }
  63016. else {
  63017. return obj._tags;
  63018. }
  63019. };
  63020. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63021. // a tag cannot start with '||', '&&', and '!'
  63022. // it cannot contain whitespaces
  63023. Tags.AddTagsTo = function (obj, tagsString) {
  63024. if (!tagsString) {
  63025. return;
  63026. }
  63027. if (typeof tagsString !== "string") {
  63028. return;
  63029. }
  63030. var tags = tagsString.split(" ");
  63031. tags.forEach(function (tag, index, array) {
  63032. Tags._AddTagTo(obj, tag);
  63033. });
  63034. };
  63035. Tags._AddTagTo = function (obj, tag) {
  63036. tag = tag.trim();
  63037. if (tag === "" || tag === "true" || tag === "false") {
  63038. return;
  63039. }
  63040. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63041. return;
  63042. }
  63043. Tags.EnableFor(obj);
  63044. obj._tags[tag] = true;
  63045. };
  63046. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63047. if (!Tags.HasTags(obj)) {
  63048. return;
  63049. }
  63050. var tags = tagsString.split(" ");
  63051. for (var t in tags) {
  63052. Tags._RemoveTagFrom(obj, tags[t]);
  63053. }
  63054. };
  63055. Tags._RemoveTagFrom = function (obj, tag) {
  63056. delete obj._tags[tag];
  63057. };
  63058. Tags.MatchesQuery = function (obj, tagsQuery) {
  63059. if (tagsQuery === undefined) {
  63060. return true;
  63061. }
  63062. if (tagsQuery === "") {
  63063. return Tags.HasTags(obj);
  63064. }
  63065. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63066. };
  63067. return Tags;
  63068. }());
  63069. BABYLON.Tags = Tags;
  63070. })(BABYLON || (BABYLON = {}));
  63071. //# sourceMappingURL=babylon.tags.js.map
  63072. var BABYLON;
  63073. (function (BABYLON) {
  63074. var AndOrNotEvaluator = /** @class */ (function () {
  63075. function AndOrNotEvaluator() {
  63076. }
  63077. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63078. if (!query.match(/\([^\(\)]*\)/g)) {
  63079. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63080. }
  63081. else {
  63082. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63083. // remove parenthesis
  63084. r = r.slice(1, r.length - 1);
  63085. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63086. });
  63087. }
  63088. if (query === "true") {
  63089. return true;
  63090. }
  63091. if (query === "false") {
  63092. return false;
  63093. }
  63094. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63095. };
  63096. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63097. evaluateCallback = evaluateCallback || (function (r) {
  63098. return r === "true" ? true : false;
  63099. });
  63100. var result;
  63101. var or = parenthesisContent.split("||");
  63102. for (var i in or) {
  63103. if (or.hasOwnProperty(i)) {
  63104. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63105. var and = ori.split("&&");
  63106. if (and.length > 1) {
  63107. for (var j = 0; j < and.length; ++j) {
  63108. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63109. if (andj !== "true" && andj !== "false") {
  63110. if (andj[0] === "!") {
  63111. result = !evaluateCallback(andj.substring(1));
  63112. }
  63113. else {
  63114. result = evaluateCallback(andj);
  63115. }
  63116. }
  63117. else {
  63118. result = andj === "true" ? true : false;
  63119. }
  63120. if (!result) {
  63121. ori = "false";
  63122. break;
  63123. }
  63124. }
  63125. }
  63126. if (result || ori === "true") {
  63127. result = true;
  63128. break;
  63129. }
  63130. // result equals false (or undefined)
  63131. if (ori !== "true" && ori !== "false") {
  63132. if (ori[0] === "!") {
  63133. result = !evaluateCallback(ori.substring(1));
  63134. }
  63135. else {
  63136. result = evaluateCallback(ori);
  63137. }
  63138. }
  63139. else {
  63140. result = ori === "true" ? true : false;
  63141. }
  63142. }
  63143. }
  63144. // the whole parenthesis scope is replaced by 'true' or 'false'
  63145. return result ? "true" : "false";
  63146. };
  63147. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63148. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63149. // remove whitespaces
  63150. r = r.replace(/[\s]/g, function () { return ""; });
  63151. return r.length % 2 ? "!" : "";
  63152. });
  63153. booleanString = booleanString.trim();
  63154. if (booleanString === "!true") {
  63155. booleanString = "false";
  63156. }
  63157. else if (booleanString === "!false") {
  63158. booleanString = "true";
  63159. }
  63160. return booleanString;
  63161. };
  63162. return AndOrNotEvaluator;
  63163. }());
  63164. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63165. })(BABYLON || (BABYLON = {}));
  63166. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63167. var BABYLON;
  63168. (function (BABYLON) {
  63169. var Database = /** @class */ (function () {
  63170. function Database(urlToScene, callbackManifestChecked) {
  63171. // Handling various flavors of prefixed version of IndexedDB
  63172. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63173. this.callbackManifestChecked = callbackManifestChecked;
  63174. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63175. this.db = null;
  63176. this._enableSceneOffline = false;
  63177. this._enableTexturesOffline = false;
  63178. this.manifestVersionFound = 0;
  63179. this.mustUpdateRessources = false;
  63180. this.hasReachedQuota = false;
  63181. if (!Database.IDBStorageEnabled) {
  63182. this.callbackManifestChecked(true);
  63183. }
  63184. else {
  63185. this.checkManifestFile();
  63186. }
  63187. }
  63188. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63189. get: function () {
  63190. return this._enableSceneOffline;
  63191. },
  63192. enumerable: true,
  63193. configurable: true
  63194. });
  63195. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63196. get: function () {
  63197. return this._enableTexturesOffline;
  63198. },
  63199. enumerable: true,
  63200. configurable: true
  63201. });
  63202. Database.prototype.checkManifestFile = function () {
  63203. var _this = this;
  63204. var noManifestFile = function () {
  63205. _this._enableSceneOffline = false;
  63206. _this._enableTexturesOffline = false;
  63207. _this.callbackManifestChecked(false);
  63208. };
  63209. var timeStampUsed = false;
  63210. var manifestURL = this.currentSceneUrl + ".manifest";
  63211. var xhr = new XMLHttpRequest();
  63212. if (navigator.onLine) {
  63213. // Adding a timestamp to by-pass browsers' cache
  63214. timeStampUsed = true;
  63215. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63216. }
  63217. xhr.open("GET", manifestURL, true);
  63218. xhr.addEventListener("load", function () {
  63219. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63220. try {
  63221. var manifestFile = JSON.parse(xhr.response);
  63222. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63223. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63224. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63225. _this.manifestVersionFound = manifestFile.version;
  63226. }
  63227. if (_this.callbackManifestChecked) {
  63228. _this.callbackManifestChecked(true);
  63229. }
  63230. }
  63231. catch (ex) {
  63232. noManifestFile();
  63233. }
  63234. }
  63235. else {
  63236. noManifestFile();
  63237. }
  63238. }, false);
  63239. xhr.addEventListener("error", function (event) {
  63240. if (timeStampUsed) {
  63241. timeStampUsed = false;
  63242. // Let's retry without the timeStamp
  63243. // It could fail when coupled with HTML5 Offline API
  63244. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63245. xhr.open("GET", retryManifestURL, true);
  63246. xhr.send();
  63247. }
  63248. else {
  63249. noManifestFile();
  63250. }
  63251. }, false);
  63252. try {
  63253. xhr.send();
  63254. }
  63255. catch (ex) {
  63256. BABYLON.Tools.Error("Error on XHR send request.");
  63257. this.callbackManifestChecked(false);
  63258. }
  63259. };
  63260. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63261. var _this = this;
  63262. var handleError = function () {
  63263. _this.isSupported = false;
  63264. if (errorCallback)
  63265. errorCallback();
  63266. };
  63267. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63268. // Your browser doesn't support IndexedDB
  63269. this.isSupported = false;
  63270. if (errorCallback)
  63271. errorCallback();
  63272. }
  63273. else {
  63274. // If the DB hasn't been opened or created yet
  63275. if (!this.db) {
  63276. this.hasReachedQuota = false;
  63277. this.isSupported = true;
  63278. var request = this.idbFactory.open("babylonjs", 1);
  63279. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63280. request.onerror = function (event) {
  63281. handleError();
  63282. };
  63283. // executes when a version change transaction cannot complete due to other active transactions
  63284. request.onblocked = function (event) {
  63285. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63286. handleError();
  63287. };
  63288. // DB has been opened successfully
  63289. request.onsuccess = function (event) {
  63290. _this.db = request.result;
  63291. successCallback();
  63292. };
  63293. // Initialization of the DB. Creating Scenes & Textures stores
  63294. request.onupgradeneeded = function (event) {
  63295. _this.db = (event.target).result;
  63296. if (_this.db) {
  63297. try {
  63298. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63299. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63300. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63301. }
  63302. catch (ex) {
  63303. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63304. handleError();
  63305. }
  63306. }
  63307. };
  63308. }
  63309. else {
  63310. if (successCallback)
  63311. successCallback();
  63312. }
  63313. }
  63314. };
  63315. Database.prototype.loadImageFromDB = function (url, image) {
  63316. var _this = this;
  63317. var completeURL = Database.ReturnFullUrlLocation(url);
  63318. var saveAndLoadImage = function () {
  63319. if (!_this.hasReachedQuota && _this.db !== null) {
  63320. // the texture is not yet in the DB, let's try to save it
  63321. _this._saveImageIntoDBAsync(completeURL, image);
  63322. }
  63323. else {
  63324. image.src = url;
  63325. }
  63326. };
  63327. if (!this.mustUpdateRessources) {
  63328. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63329. }
  63330. else {
  63331. saveAndLoadImage();
  63332. }
  63333. };
  63334. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63335. if (this.isSupported && this.db !== null) {
  63336. var texture;
  63337. var transaction = this.db.transaction(["textures"]);
  63338. transaction.onabort = function (event) {
  63339. image.src = url;
  63340. };
  63341. transaction.oncomplete = function (event) {
  63342. var blobTextureURL;
  63343. if (texture) {
  63344. var URL = window.URL || window.webkitURL;
  63345. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63346. image.onerror = function () {
  63347. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63348. image.src = url;
  63349. };
  63350. image.src = blobTextureURL;
  63351. }
  63352. else {
  63353. notInDBCallback();
  63354. }
  63355. };
  63356. var getRequest = transaction.objectStore("textures").get(url);
  63357. getRequest.onsuccess = function (event) {
  63358. texture = (event.target).result;
  63359. };
  63360. getRequest.onerror = function (event) {
  63361. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63362. image.src = url;
  63363. };
  63364. }
  63365. else {
  63366. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63367. image.src = url;
  63368. }
  63369. };
  63370. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63371. var _this = this;
  63372. if (this.isSupported) {
  63373. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63374. var generateBlobUrl = function () {
  63375. var blobTextureURL;
  63376. if (blob) {
  63377. var URL = window.URL || window.webkitURL;
  63378. try {
  63379. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63380. }
  63381. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63382. catch (ex) {
  63383. blobTextureURL = URL.createObjectURL(blob);
  63384. }
  63385. }
  63386. if (blobTextureURL) {
  63387. image.src = blobTextureURL;
  63388. }
  63389. };
  63390. if (Database.IsUASupportingBlobStorage) {
  63391. var xhr = new XMLHttpRequest(), blob;
  63392. xhr.open("GET", url, true);
  63393. xhr.responseType = "blob";
  63394. xhr.addEventListener("load", function () {
  63395. if (xhr.status === 200 && _this.db) {
  63396. // Blob as response (XHR2)
  63397. blob = xhr.response;
  63398. var transaction = _this.db.transaction(["textures"], "readwrite");
  63399. // the transaction could abort because of a QuotaExceededError error
  63400. transaction.onabort = function (event) {
  63401. try {
  63402. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63403. var srcElement = (event.srcElement || event.target);
  63404. var error = srcElement.error;
  63405. if (error && error.name === "QuotaExceededError") {
  63406. _this.hasReachedQuota = true;
  63407. }
  63408. }
  63409. catch (ex) { }
  63410. generateBlobUrl();
  63411. };
  63412. transaction.oncomplete = function (event) {
  63413. generateBlobUrl();
  63414. };
  63415. var newTexture = { textureUrl: url, data: blob };
  63416. try {
  63417. // Put the blob into the dabase
  63418. var addRequest = transaction.objectStore("textures").put(newTexture);
  63419. addRequest.onsuccess = function (event) {
  63420. };
  63421. addRequest.onerror = function (event) {
  63422. generateBlobUrl();
  63423. };
  63424. }
  63425. catch (ex) {
  63426. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63427. if (ex.code === 25) {
  63428. Database.IsUASupportingBlobStorage = false;
  63429. }
  63430. image.src = url;
  63431. }
  63432. }
  63433. else {
  63434. image.src = url;
  63435. }
  63436. }, false);
  63437. xhr.addEventListener("error", function (event) {
  63438. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63439. image.src = url;
  63440. }, false);
  63441. xhr.send();
  63442. }
  63443. else {
  63444. image.src = url;
  63445. }
  63446. }
  63447. else {
  63448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63449. image.src = url;
  63450. }
  63451. };
  63452. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63453. var _this = this;
  63454. var updateVersion = function () {
  63455. // the version is not yet in the DB or we need to update it
  63456. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63457. };
  63458. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63459. };
  63460. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63461. var _this = this;
  63462. if (this.isSupported && this.db) {
  63463. var version;
  63464. try {
  63465. var transaction = this.db.transaction(["versions"]);
  63466. transaction.oncomplete = function (event) {
  63467. if (version) {
  63468. // If the version in the JSON file is > than the version in DB
  63469. if (_this.manifestVersionFound > version.data) {
  63470. _this.mustUpdateRessources = true;
  63471. updateInDBCallback();
  63472. }
  63473. else {
  63474. callback(version.data);
  63475. }
  63476. }
  63477. else {
  63478. _this.mustUpdateRessources = true;
  63479. updateInDBCallback();
  63480. }
  63481. };
  63482. transaction.onabort = function (event) {
  63483. callback(-1);
  63484. };
  63485. var getRequest = transaction.objectStore("versions").get(url);
  63486. getRequest.onsuccess = function (event) {
  63487. version = (event.target).result;
  63488. };
  63489. getRequest.onerror = function (event) {
  63490. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63491. callback(-1);
  63492. };
  63493. }
  63494. catch (ex) {
  63495. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63496. callback(-1);
  63497. }
  63498. }
  63499. else {
  63500. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63501. callback(-1);
  63502. }
  63503. };
  63504. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63505. var _this = this;
  63506. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63507. try {
  63508. // Open a transaction to the database
  63509. var transaction = this.db.transaction(["versions"], "readwrite");
  63510. // the transaction could abort because of a QuotaExceededError error
  63511. transaction.onabort = function (event) {
  63512. try {
  63513. var error = event.srcElement['error'];
  63514. if (error && error.name === "QuotaExceededError") {
  63515. _this.hasReachedQuota = true;
  63516. }
  63517. }
  63518. catch (ex) { }
  63519. callback(-1);
  63520. };
  63521. transaction.oncomplete = function (event) {
  63522. callback(_this.manifestVersionFound);
  63523. };
  63524. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63525. // Put the scene into the database
  63526. var addRequest = transaction.objectStore("versions").put(newVersion);
  63527. addRequest.onsuccess = function (event) {
  63528. };
  63529. addRequest.onerror = function (event) {
  63530. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63531. };
  63532. }
  63533. catch (ex) {
  63534. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63535. callback(-1);
  63536. }
  63537. }
  63538. else {
  63539. callback(-1);
  63540. }
  63541. };
  63542. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63543. var _this = this;
  63544. var completeUrl = Database.ReturnFullUrlLocation(url);
  63545. var saveAndLoadFile = function () {
  63546. // the scene is not yet in the DB, let's try to save it
  63547. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63548. };
  63549. this._checkVersionFromDB(completeUrl, function (version) {
  63550. if (version !== -1) {
  63551. if (!_this.mustUpdateRessources) {
  63552. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63553. }
  63554. else {
  63555. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63556. }
  63557. }
  63558. else {
  63559. if (errorCallback) {
  63560. errorCallback();
  63561. }
  63562. }
  63563. });
  63564. };
  63565. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63566. if (this.isSupported && this.db) {
  63567. var targetStore;
  63568. if (url.indexOf(".babylon") !== -1) {
  63569. targetStore = "scenes";
  63570. }
  63571. else {
  63572. targetStore = "textures";
  63573. }
  63574. var file;
  63575. var transaction = this.db.transaction([targetStore]);
  63576. transaction.oncomplete = function (event) {
  63577. if (file) {
  63578. callback(file.data);
  63579. }
  63580. else {
  63581. notInDBCallback();
  63582. }
  63583. };
  63584. transaction.onabort = function (event) {
  63585. notInDBCallback();
  63586. };
  63587. var getRequest = transaction.objectStore(targetStore).get(url);
  63588. getRequest.onsuccess = function (event) {
  63589. file = (event.target).result;
  63590. };
  63591. getRequest.onerror = function (event) {
  63592. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63593. notInDBCallback();
  63594. };
  63595. }
  63596. else {
  63597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63598. callback();
  63599. }
  63600. };
  63601. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63602. var _this = this;
  63603. if (this.isSupported) {
  63604. var targetStore;
  63605. if (url.indexOf(".babylon") !== -1) {
  63606. targetStore = "scenes";
  63607. }
  63608. else {
  63609. targetStore = "textures";
  63610. }
  63611. // Create XHR
  63612. var xhr = new XMLHttpRequest();
  63613. var fileData;
  63614. xhr.open("GET", url, true);
  63615. if (useArrayBuffer) {
  63616. xhr.responseType = "arraybuffer";
  63617. }
  63618. if (progressCallback) {
  63619. xhr.onprogress = progressCallback;
  63620. }
  63621. xhr.addEventListener("load", function () {
  63622. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63623. // Blob as response (XHR2)
  63624. //fileData = xhr.responseText;
  63625. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63626. if (!_this.hasReachedQuota && _this.db) {
  63627. // Open a transaction to the database
  63628. var transaction = _this.db.transaction([targetStore], "readwrite");
  63629. // the transaction could abort because of a QuotaExceededError error
  63630. transaction.onabort = function (event) {
  63631. try {
  63632. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63633. var error = event.srcElement['error'];
  63634. if (error && error.name === "QuotaExceededError") {
  63635. _this.hasReachedQuota = true;
  63636. }
  63637. }
  63638. catch (ex) { }
  63639. callback(fileData);
  63640. };
  63641. transaction.oncomplete = function (event) {
  63642. callback(fileData);
  63643. };
  63644. var newFile;
  63645. if (targetStore === "scenes") {
  63646. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63647. }
  63648. else {
  63649. newFile = { textureUrl: url, data: fileData };
  63650. }
  63651. try {
  63652. // Put the scene into the database
  63653. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63654. addRequest.onsuccess = function (event) {
  63655. };
  63656. addRequest.onerror = function (event) {
  63657. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63658. };
  63659. }
  63660. catch (ex) {
  63661. callback(fileData);
  63662. }
  63663. }
  63664. else {
  63665. callback(fileData);
  63666. }
  63667. }
  63668. else {
  63669. callback();
  63670. }
  63671. }, false);
  63672. xhr.addEventListener("error", function (event) {
  63673. BABYLON.Tools.Error("error on XHR request.");
  63674. callback();
  63675. }, false);
  63676. xhr.send();
  63677. }
  63678. else {
  63679. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63680. callback();
  63681. }
  63682. };
  63683. Database.IsUASupportingBlobStorage = true;
  63684. Database.IDBStorageEnabled = true;
  63685. Database.parseURL = function (url) {
  63686. var a = document.createElement('a');
  63687. a.href = url;
  63688. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63689. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63690. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63691. return absLocation;
  63692. };
  63693. Database.ReturnFullUrlLocation = function (url) {
  63694. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63695. return (Database.parseURL(window.location.href) + url);
  63696. }
  63697. else {
  63698. return url;
  63699. }
  63700. };
  63701. return Database;
  63702. }());
  63703. BABYLON.Database = Database;
  63704. })(BABYLON || (BABYLON = {}));
  63705. //# sourceMappingURL=babylon.database.js.map
  63706. var BABYLON;
  63707. (function (BABYLON) {
  63708. var FresnelParameters = /** @class */ (function () {
  63709. function FresnelParameters() {
  63710. this._isEnabled = true;
  63711. this.leftColor = BABYLON.Color3.White();
  63712. this.rightColor = BABYLON.Color3.Black();
  63713. this.bias = 0;
  63714. this.power = 1;
  63715. }
  63716. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63717. get: function () {
  63718. return this._isEnabled;
  63719. },
  63720. set: function (value) {
  63721. if (this._isEnabled === value) {
  63722. return;
  63723. }
  63724. this._isEnabled = value;
  63725. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63726. },
  63727. enumerable: true,
  63728. configurable: true
  63729. });
  63730. FresnelParameters.prototype.clone = function () {
  63731. var newFresnelParameters = new FresnelParameters();
  63732. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63733. return newFresnelParameters;
  63734. };
  63735. FresnelParameters.prototype.serialize = function () {
  63736. var serializationObject = {};
  63737. serializationObject.isEnabled = this.isEnabled;
  63738. serializationObject.leftColor = this.leftColor;
  63739. serializationObject.rightColor = this.rightColor;
  63740. serializationObject.bias = this.bias;
  63741. serializationObject.power = this.power;
  63742. return serializationObject;
  63743. };
  63744. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63745. var fresnelParameters = new FresnelParameters();
  63746. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63747. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63748. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63749. fresnelParameters.bias = parsedFresnelParameters.bias;
  63750. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63751. return fresnelParameters;
  63752. };
  63753. return FresnelParameters;
  63754. }());
  63755. BABYLON.FresnelParameters = FresnelParameters;
  63756. })(BABYLON || (BABYLON = {}));
  63757. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63758. var BABYLON;
  63759. (function (BABYLON) {
  63760. var MultiMaterial = /** @class */ (function (_super) {
  63761. __extends(MultiMaterial, _super);
  63762. function MultiMaterial(name, scene) {
  63763. var _this = _super.call(this, name, scene, true) || this;
  63764. scene.multiMaterials.push(_this);
  63765. _this.subMaterials = new Array();
  63766. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63767. return _this;
  63768. }
  63769. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63770. get: function () {
  63771. return this._subMaterials;
  63772. },
  63773. set: function (value) {
  63774. this._subMaterials = value;
  63775. this._hookArray(value);
  63776. },
  63777. enumerable: true,
  63778. configurable: true
  63779. });
  63780. MultiMaterial.prototype._hookArray = function (array) {
  63781. var _this = this;
  63782. var oldPush = array.push;
  63783. array.push = function () {
  63784. var items = [];
  63785. for (var _i = 0; _i < arguments.length; _i++) {
  63786. items[_i] = arguments[_i];
  63787. }
  63788. var result = oldPush.apply(array, items);
  63789. _this._markAllSubMeshesAsTexturesDirty();
  63790. return result;
  63791. };
  63792. var oldSplice = array.splice;
  63793. array.splice = function (index, deleteCount) {
  63794. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63795. _this._markAllSubMeshesAsTexturesDirty();
  63796. return deleted;
  63797. };
  63798. };
  63799. // Properties
  63800. MultiMaterial.prototype.getSubMaterial = function (index) {
  63801. if (index < 0 || index >= this.subMaterials.length) {
  63802. return this.getScene().defaultMaterial;
  63803. }
  63804. return this.subMaterials[index];
  63805. };
  63806. MultiMaterial.prototype.getActiveTextures = function () {
  63807. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63808. if (subMaterial) {
  63809. return subMaterial.getActiveTextures();
  63810. }
  63811. else {
  63812. return [];
  63813. }
  63814. }));
  63815. var _a;
  63816. };
  63817. // Methods
  63818. MultiMaterial.prototype.getClassName = function () {
  63819. return "MultiMaterial";
  63820. };
  63821. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63822. for (var index = 0; index < this.subMaterials.length; index++) {
  63823. var subMaterial = this.subMaterials[index];
  63824. if (subMaterial) {
  63825. if (subMaterial.storeEffectOnSubMeshes) {
  63826. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63827. return false;
  63828. }
  63829. continue;
  63830. }
  63831. if (!subMaterial.isReady(mesh)) {
  63832. return false;
  63833. }
  63834. }
  63835. }
  63836. return true;
  63837. };
  63838. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63839. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63840. for (var index = 0; index < this.subMaterials.length; index++) {
  63841. var subMaterial = null;
  63842. var current = this.subMaterials[index];
  63843. if (cloneChildren && current) {
  63844. subMaterial = current.clone(name + "-" + current.name);
  63845. }
  63846. else {
  63847. subMaterial = this.subMaterials[index];
  63848. }
  63849. newMultiMaterial.subMaterials.push(subMaterial);
  63850. }
  63851. return newMultiMaterial;
  63852. };
  63853. MultiMaterial.prototype.serialize = function () {
  63854. var serializationObject = {};
  63855. serializationObject.name = this.name;
  63856. serializationObject.id = this.id;
  63857. if (BABYLON.Tags) {
  63858. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63859. }
  63860. serializationObject.materials = [];
  63861. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63862. var subMat = this.subMaterials[matIndex];
  63863. if (subMat) {
  63864. serializationObject.materials.push(subMat.id);
  63865. }
  63866. else {
  63867. serializationObject.materials.push(null);
  63868. }
  63869. }
  63870. return serializationObject;
  63871. };
  63872. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63873. var scene = this.getScene();
  63874. if (!scene) {
  63875. return;
  63876. }
  63877. var index = scene.multiMaterials.indexOf(this);
  63878. if (index >= 0) {
  63879. scene.multiMaterials.splice(index, 1);
  63880. }
  63881. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63882. };
  63883. return MultiMaterial;
  63884. }(BABYLON.Material));
  63885. BABYLON.MultiMaterial = MultiMaterial;
  63886. })(BABYLON || (BABYLON = {}));
  63887. //# sourceMappingURL=babylon.multiMaterial.js.map
  63888. var BABYLON;
  63889. (function (BABYLON) {
  63890. var FreeCameraTouchInput = /** @class */ (function () {
  63891. function FreeCameraTouchInput() {
  63892. this._offsetX = null;
  63893. this._offsetY = null;
  63894. this._pointerPressed = new Array();
  63895. this.touchAngularSensibility = 200000.0;
  63896. this.touchMoveSensibility = 250.0;
  63897. }
  63898. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63899. var _this = this;
  63900. var previousPosition = null;
  63901. if (this._pointerInput === undefined) {
  63902. this._onLostFocus = function (evt) {
  63903. _this._offsetX = null;
  63904. _this._offsetY = null;
  63905. };
  63906. this._pointerInput = function (p, s) {
  63907. var evt = p.event;
  63908. if (evt.pointerType === "mouse") {
  63909. return;
  63910. }
  63911. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63912. if (!noPreventDefault) {
  63913. evt.preventDefault();
  63914. }
  63915. _this._pointerPressed.push(evt.pointerId);
  63916. if (_this._pointerPressed.length !== 1) {
  63917. return;
  63918. }
  63919. previousPosition = {
  63920. x: evt.clientX,
  63921. y: evt.clientY
  63922. };
  63923. }
  63924. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63925. if (!noPreventDefault) {
  63926. evt.preventDefault();
  63927. }
  63928. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63929. if (index === -1) {
  63930. return;
  63931. }
  63932. _this._pointerPressed.splice(index, 1);
  63933. if (index != 0) {
  63934. return;
  63935. }
  63936. previousPosition = null;
  63937. _this._offsetX = null;
  63938. _this._offsetY = null;
  63939. }
  63940. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63941. if (!noPreventDefault) {
  63942. evt.preventDefault();
  63943. }
  63944. if (!previousPosition) {
  63945. return;
  63946. }
  63947. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63948. if (index != 0) {
  63949. return;
  63950. }
  63951. _this._offsetX = evt.clientX - previousPosition.x;
  63952. _this._offsetY = -(evt.clientY - previousPosition.y);
  63953. }
  63954. };
  63955. }
  63956. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63957. if (this._onLostFocus) {
  63958. element.addEventListener("blur", this._onLostFocus);
  63959. }
  63960. };
  63961. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63962. if (this._pointerInput && element) {
  63963. if (this._observer) {
  63964. this.camera.getScene().onPointerObservable.remove(this._observer);
  63965. this._observer = null;
  63966. }
  63967. if (this._onLostFocus) {
  63968. element.removeEventListener("blur", this._onLostFocus);
  63969. this._onLostFocus = null;
  63970. }
  63971. this._pointerPressed = [];
  63972. this._offsetX = null;
  63973. this._offsetY = null;
  63974. }
  63975. };
  63976. FreeCameraTouchInput.prototype.checkInputs = function () {
  63977. if (this._offsetX && this._offsetY) {
  63978. var camera = this.camera;
  63979. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63980. if (this._pointerPressed.length > 1) {
  63981. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63982. }
  63983. else {
  63984. var speed = camera._computeLocalCameraSpeed();
  63985. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63986. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63987. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63988. }
  63989. }
  63990. };
  63991. FreeCameraTouchInput.prototype.getClassName = function () {
  63992. return "FreeCameraTouchInput";
  63993. };
  63994. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63995. return "touch";
  63996. };
  63997. __decorate([
  63998. BABYLON.serialize()
  63999. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64000. __decorate([
  64001. BABYLON.serialize()
  64002. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64003. return FreeCameraTouchInput;
  64004. }());
  64005. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64006. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64007. })(BABYLON || (BABYLON = {}));
  64008. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64009. var BABYLON;
  64010. (function (BABYLON) {
  64011. // We're mainly based on the logic defined into the FreeCamera code
  64012. var TouchCamera = /** @class */ (function (_super) {
  64013. __extends(TouchCamera, _super);
  64014. //-- end properties for backward compatibility for inputs
  64015. function TouchCamera(name, position, scene) {
  64016. var _this = _super.call(this, name, position, scene) || this;
  64017. _this.inputs.addTouch();
  64018. _this._setupInputs();
  64019. return _this;
  64020. }
  64021. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64022. //-- Begin properties for backward compatibility for inputs
  64023. get: function () {
  64024. var touch = this.inputs.attached["touch"];
  64025. if (touch)
  64026. return touch.touchAngularSensibility;
  64027. return 0;
  64028. },
  64029. set: function (value) {
  64030. var touch = this.inputs.attached["touch"];
  64031. if (touch)
  64032. touch.touchAngularSensibility = value;
  64033. },
  64034. enumerable: true,
  64035. configurable: true
  64036. });
  64037. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64038. get: function () {
  64039. var touch = this.inputs.attached["touch"];
  64040. if (touch)
  64041. return touch.touchMoveSensibility;
  64042. return 0;
  64043. },
  64044. set: function (value) {
  64045. var touch = this.inputs.attached["touch"];
  64046. if (touch)
  64047. touch.touchMoveSensibility = value;
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. TouchCamera.prototype.getClassName = function () {
  64053. return "TouchCamera";
  64054. };
  64055. TouchCamera.prototype._setupInputs = function () {
  64056. var mouse = this.inputs.attached["mouse"];
  64057. if (mouse) {
  64058. mouse.touchEnabled = false;
  64059. }
  64060. };
  64061. return TouchCamera;
  64062. }(BABYLON.FreeCamera));
  64063. BABYLON.TouchCamera = TouchCamera;
  64064. })(BABYLON || (BABYLON = {}));
  64065. //# sourceMappingURL=babylon.touchCamera.js.map
  64066. var BABYLON;
  64067. (function (BABYLON) {
  64068. var ProceduralTexture = /** @class */ (function (_super) {
  64069. __extends(ProceduralTexture, _super);
  64070. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64071. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64072. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64073. if (isCube === void 0) { isCube = false; }
  64074. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64075. _this.isCube = isCube;
  64076. _this.isEnabled = true;
  64077. _this._currentRefreshId = -1;
  64078. _this._refreshRate = 1;
  64079. _this._vertexBuffers = {};
  64080. _this._uniforms = new Array();
  64081. _this._samplers = new Array();
  64082. _this._textures = {};
  64083. _this._floats = {};
  64084. _this._floatsArrays = {};
  64085. _this._colors3 = {};
  64086. _this._colors4 = {};
  64087. _this._vectors2 = {};
  64088. _this._vectors3 = {};
  64089. _this._matrices = {};
  64090. _this._fallbackTextureUsed = false;
  64091. scene._proceduralTextures.push(_this);
  64092. _this._engine = scene.getEngine();
  64093. _this.name = name;
  64094. _this.isRenderTarget = true;
  64095. _this._size = size;
  64096. _this._generateMipMaps = generateMipMaps;
  64097. _this.setFragment(fragment);
  64098. _this._fallbackTexture = fallbackTexture;
  64099. if (isCube) {
  64100. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64101. _this.setFloat("face", 0);
  64102. }
  64103. else {
  64104. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64105. }
  64106. // VBO
  64107. var vertices = [];
  64108. vertices.push(1, 1);
  64109. vertices.push(-1, 1);
  64110. vertices.push(-1, -1);
  64111. vertices.push(1, -1);
  64112. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64113. _this._createIndexBuffer();
  64114. return _this;
  64115. }
  64116. ProceduralTexture.prototype._createIndexBuffer = function () {
  64117. var engine = this._engine;
  64118. // Indices
  64119. var indices = [];
  64120. indices.push(0);
  64121. indices.push(1);
  64122. indices.push(2);
  64123. indices.push(0);
  64124. indices.push(2);
  64125. indices.push(3);
  64126. this._indexBuffer = engine.createIndexBuffer(indices);
  64127. };
  64128. ProceduralTexture.prototype._rebuild = function () {
  64129. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64130. if (vb) {
  64131. vb._rebuild();
  64132. }
  64133. this._createIndexBuffer();
  64134. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64135. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64136. }
  64137. };
  64138. ProceduralTexture.prototype.reset = function () {
  64139. if (this._effect === undefined) {
  64140. return;
  64141. }
  64142. var engine = this._engine;
  64143. engine._releaseEffect(this._effect);
  64144. };
  64145. ProceduralTexture.prototype.isReady = function () {
  64146. var _this = this;
  64147. var engine = this._engine;
  64148. var shaders;
  64149. if (!this._fragment) {
  64150. return false;
  64151. }
  64152. if (this._fallbackTextureUsed) {
  64153. return true;
  64154. }
  64155. if (this._fragment.fragmentElement !== undefined) {
  64156. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64157. }
  64158. else {
  64159. shaders = { vertex: "procedural", fragment: this._fragment };
  64160. }
  64161. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64162. _this.releaseInternalTexture();
  64163. if (_this._fallbackTexture) {
  64164. _this._texture = _this._fallbackTexture._texture;
  64165. if (_this._texture) {
  64166. _this._texture.incrementReferences();
  64167. }
  64168. }
  64169. _this._fallbackTextureUsed = true;
  64170. });
  64171. return this._effect.isReady();
  64172. };
  64173. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64174. this._currentRefreshId = -1;
  64175. };
  64176. ProceduralTexture.prototype.setFragment = function (fragment) {
  64177. this._fragment = fragment;
  64178. };
  64179. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64180. get: function () {
  64181. return this._refreshRate;
  64182. },
  64183. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64184. set: function (value) {
  64185. this._refreshRate = value;
  64186. this.resetRefreshCounter();
  64187. },
  64188. enumerable: true,
  64189. configurable: true
  64190. });
  64191. ProceduralTexture.prototype._shouldRender = function () {
  64192. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64193. return false;
  64194. }
  64195. if (this._fallbackTextureUsed) {
  64196. return false;
  64197. }
  64198. if (this._currentRefreshId === -1) {
  64199. this._currentRefreshId = 1;
  64200. return true;
  64201. }
  64202. if (this.refreshRate === this._currentRefreshId) {
  64203. this._currentRefreshId = 1;
  64204. return true;
  64205. }
  64206. this._currentRefreshId++;
  64207. return false;
  64208. };
  64209. ProceduralTexture.prototype.getRenderSize = function () {
  64210. return this._size;
  64211. };
  64212. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64213. if (this._fallbackTextureUsed) {
  64214. return;
  64215. }
  64216. this.releaseInternalTexture();
  64217. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64218. };
  64219. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64220. if (this._uniforms.indexOf(uniformName) === -1) {
  64221. this._uniforms.push(uniformName);
  64222. }
  64223. };
  64224. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64225. if (this._samplers.indexOf(name) === -1) {
  64226. this._samplers.push(name);
  64227. }
  64228. this._textures[name] = texture;
  64229. return this;
  64230. };
  64231. ProceduralTexture.prototype.setFloat = function (name, value) {
  64232. this._checkUniform(name);
  64233. this._floats[name] = value;
  64234. return this;
  64235. };
  64236. ProceduralTexture.prototype.setFloats = function (name, value) {
  64237. this._checkUniform(name);
  64238. this._floatsArrays[name] = value;
  64239. return this;
  64240. };
  64241. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64242. this._checkUniform(name);
  64243. this._colors3[name] = value;
  64244. return this;
  64245. };
  64246. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64247. this._checkUniform(name);
  64248. this._colors4[name] = value;
  64249. return this;
  64250. };
  64251. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64252. this._checkUniform(name);
  64253. this._vectors2[name] = value;
  64254. return this;
  64255. };
  64256. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64257. this._checkUniform(name);
  64258. this._vectors3[name] = value;
  64259. return this;
  64260. };
  64261. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64262. this._checkUniform(name);
  64263. this._matrices[name] = value;
  64264. return this;
  64265. };
  64266. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64267. var scene = this.getScene();
  64268. if (!scene) {
  64269. return;
  64270. }
  64271. var engine = this._engine;
  64272. // Render
  64273. engine.enableEffect(this._effect);
  64274. engine.setState(false);
  64275. // Texture
  64276. for (var name in this._textures) {
  64277. this._effect.setTexture(name, this._textures[name]);
  64278. }
  64279. // Float
  64280. for (name in this._floats) {
  64281. this._effect.setFloat(name, this._floats[name]);
  64282. }
  64283. // Floats
  64284. for (name in this._floatsArrays) {
  64285. this._effect.setArray(name, this._floatsArrays[name]);
  64286. }
  64287. // Color3
  64288. for (name in this._colors3) {
  64289. this._effect.setColor3(name, this._colors3[name]);
  64290. }
  64291. // Color4
  64292. for (name in this._colors4) {
  64293. var color = this._colors4[name];
  64294. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64295. }
  64296. // Vector2
  64297. for (name in this._vectors2) {
  64298. this._effect.setVector2(name, this._vectors2[name]);
  64299. }
  64300. // Vector3
  64301. for (name in this._vectors3) {
  64302. this._effect.setVector3(name, this._vectors3[name]);
  64303. }
  64304. // Matrix
  64305. for (name in this._matrices) {
  64306. this._effect.setMatrix(name, this._matrices[name]);
  64307. }
  64308. if (!this._texture) {
  64309. return;
  64310. }
  64311. if (this.isCube) {
  64312. for (var face = 0; face < 6; face++) {
  64313. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64314. // VBOs
  64315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64316. this._effect.setFloat("face", face);
  64317. // Clear
  64318. engine.clear(scene.clearColor, true, true, true);
  64319. // Draw order
  64320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64321. // Mipmaps
  64322. if (face === 5) {
  64323. engine.generateMipMapsForCubemap(this._texture);
  64324. }
  64325. }
  64326. }
  64327. else {
  64328. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64329. // VBOs
  64330. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64331. // Clear
  64332. engine.clear(scene.clearColor, true, true, true);
  64333. // Draw order
  64334. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64335. }
  64336. // Unbind
  64337. engine.unBindFramebuffer(this._texture, this.isCube);
  64338. if (this.onGenerated) {
  64339. this.onGenerated();
  64340. }
  64341. };
  64342. ProceduralTexture.prototype.clone = function () {
  64343. var textureSize = this.getSize();
  64344. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64345. // Base texture
  64346. newTexture.hasAlpha = this.hasAlpha;
  64347. newTexture.level = this.level;
  64348. // RenderTarget Texture
  64349. newTexture.coordinatesMode = this.coordinatesMode;
  64350. return newTexture;
  64351. };
  64352. ProceduralTexture.prototype.dispose = function () {
  64353. var scene = this.getScene();
  64354. if (!scene) {
  64355. return;
  64356. }
  64357. var index = scene._proceduralTextures.indexOf(this);
  64358. if (index >= 0) {
  64359. scene._proceduralTextures.splice(index, 1);
  64360. }
  64361. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64362. if (vertexBuffer) {
  64363. vertexBuffer.dispose();
  64364. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64365. }
  64366. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64367. this._indexBuffer = null;
  64368. }
  64369. _super.prototype.dispose.call(this);
  64370. };
  64371. return ProceduralTexture;
  64372. }(BABYLON.Texture));
  64373. BABYLON.ProceduralTexture = ProceduralTexture;
  64374. })(BABYLON || (BABYLON = {}));
  64375. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64376. var BABYLON;
  64377. (function (BABYLON) {
  64378. var CustomProceduralTexture = /** @class */ (function (_super) {
  64379. __extends(CustomProceduralTexture, _super);
  64380. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64381. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64382. _this._animate = true;
  64383. _this._time = 0;
  64384. _this._texturePath = texturePath;
  64385. //Try to load json
  64386. _this.loadJson(texturePath);
  64387. _this.refreshRate = 1;
  64388. return _this;
  64389. }
  64390. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64391. var _this = this;
  64392. var noConfigFile = function () {
  64393. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64394. try {
  64395. _this.setFragment(_this._texturePath);
  64396. }
  64397. catch (ex) {
  64398. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64399. }
  64400. };
  64401. var configFileUrl = jsonUrl + "/config.json";
  64402. var xhr = new XMLHttpRequest();
  64403. xhr.open("GET", configFileUrl, true);
  64404. xhr.addEventListener("load", function () {
  64405. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64406. try {
  64407. _this._config = JSON.parse(xhr.response);
  64408. _this.updateShaderUniforms();
  64409. _this.updateTextures();
  64410. _this.setFragment(_this._texturePath + "/custom");
  64411. _this._animate = _this._config.animate;
  64412. _this.refreshRate = _this._config.refreshrate;
  64413. }
  64414. catch (ex) {
  64415. noConfigFile();
  64416. }
  64417. }
  64418. else {
  64419. noConfigFile();
  64420. }
  64421. }, false);
  64422. xhr.addEventListener("error", function () {
  64423. noConfigFile();
  64424. }, false);
  64425. try {
  64426. xhr.send();
  64427. }
  64428. catch (ex) {
  64429. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64430. }
  64431. };
  64432. CustomProceduralTexture.prototype.isReady = function () {
  64433. if (!_super.prototype.isReady.call(this)) {
  64434. return false;
  64435. }
  64436. for (var name in this._textures) {
  64437. var texture = this._textures[name];
  64438. if (!texture.isReady()) {
  64439. return false;
  64440. }
  64441. }
  64442. return true;
  64443. };
  64444. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64445. var scene = this.getScene();
  64446. if (this._animate && scene) {
  64447. this._time += scene.getAnimationRatio() * 0.03;
  64448. this.updateShaderUniforms();
  64449. }
  64450. _super.prototype.render.call(this, useCameraPostProcess);
  64451. };
  64452. CustomProceduralTexture.prototype.updateTextures = function () {
  64453. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64454. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64455. }
  64456. };
  64457. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64458. if (this._config) {
  64459. for (var j = 0; j < this._config.uniforms.length; j++) {
  64460. var uniform = this._config.uniforms[j];
  64461. switch (uniform.type) {
  64462. case "float":
  64463. this.setFloat(uniform.name, uniform.value);
  64464. break;
  64465. case "color3":
  64466. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64467. break;
  64468. case "color4":
  64469. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64470. break;
  64471. case "vector2":
  64472. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64473. break;
  64474. case "vector3":
  64475. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64476. break;
  64477. }
  64478. }
  64479. }
  64480. this.setFloat("time", this._time);
  64481. };
  64482. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64483. get: function () {
  64484. return this._animate;
  64485. },
  64486. set: function (value) {
  64487. this._animate = value;
  64488. },
  64489. enumerable: true,
  64490. configurable: true
  64491. });
  64492. return CustomProceduralTexture;
  64493. }(BABYLON.ProceduralTexture));
  64494. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64495. })(BABYLON || (BABYLON = {}));
  64496. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64497. var BABYLON;
  64498. (function (BABYLON) {
  64499. var FreeCameraGamepadInput = /** @class */ (function () {
  64500. function FreeCameraGamepadInput() {
  64501. this.gamepadAngularSensibility = 200;
  64502. this.gamepadMoveSensibility = 40;
  64503. // private members
  64504. this._cameraTransform = BABYLON.Matrix.Identity();
  64505. this._deltaTransform = BABYLON.Vector3.Zero();
  64506. this._vector3 = BABYLON.Vector3.Zero();
  64507. this._vector2 = BABYLON.Vector2.Zero();
  64508. }
  64509. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64510. var _this = this;
  64511. var manager = this.camera.getScene().gamepadManager;
  64512. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64513. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64514. // prioritize XBOX gamepads.
  64515. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64516. _this.gamepad = gamepad;
  64517. }
  64518. }
  64519. });
  64520. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64521. if (_this.gamepad === gamepad) {
  64522. _this.gamepad = null;
  64523. }
  64524. });
  64525. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64526. };
  64527. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64528. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64529. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64530. this.gamepad = null;
  64531. };
  64532. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64533. if (this.gamepad && this.gamepad.leftStick) {
  64534. var camera = this.camera;
  64535. var LSValues = this.gamepad.leftStick;
  64536. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64537. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64538. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64539. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64540. var RSValues = this.gamepad.rightStick;
  64541. if (RSValues) {
  64542. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64543. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64544. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64545. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64546. }
  64547. else {
  64548. RSValues = { x: 0, y: 0 };
  64549. }
  64550. if (!camera.rotationQuaternion) {
  64551. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64552. }
  64553. else {
  64554. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64555. }
  64556. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64557. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64558. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64559. camera.cameraDirection.addInPlace(this._deltaTransform);
  64560. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64561. camera.cameraRotation.addInPlace(this._vector2);
  64562. }
  64563. };
  64564. FreeCameraGamepadInput.prototype.getClassName = function () {
  64565. return "FreeCameraGamepadInput";
  64566. };
  64567. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64568. return "gamepad";
  64569. };
  64570. __decorate([
  64571. BABYLON.serialize()
  64572. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64573. __decorate([
  64574. BABYLON.serialize()
  64575. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64576. return FreeCameraGamepadInput;
  64577. }());
  64578. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64579. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64580. })(BABYLON || (BABYLON = {}));
  64581. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64582. var BABYLON;
  64583. (function (BABYLON) {
  64584. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64585. function ArcRotateCameraGamepadInput() {
  64586. this.gamepadRotationSensibility = 80;
  64587. this.gamepadMoveSensibility = 40;
  64588. }
  64589. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64590. var _this = this;
  64591. var manager = this.camera.getScene().gamepadManager;
  64592. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64593. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64594. // prioritize XBOX gamepads.
  64595. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64596. _this.gamepad = gamepad;
  64597. }
  64598. }
  64599. });
  64600. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64601. if (_this.gamepad === gamepad) {
  64602. _this.gamepad = null;
  64603. }
  64604. });
  64605. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64606. };
  64607. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64608. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64609. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64610. this.gamepad = null;
  64611. };
  64612. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64613. if (this.gamepad) {
  64614. var camera = this.camera;
  64615. var RSValues = this.gamepad.rightStick;
  64616. if (RSValues) {
  64617. if (RSValues.x != 0) {
  64618. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64619. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64620. camera.inertialAlphaOffset += normalizedRX;
  64621. }
  64622. }
  64623. if (RSValues.y != 0) {
  64624. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64625. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64626. camera.inertialBetaOffset += normalizedRY;
  64627. }
  64628. }
  64629. }
  64630. var LSValues = this.gamepad.leftStick;
  64631. if (LSValues && LSValues.y != 0) {
  64632. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64633. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64634. this.camera.inertialRadiusOffset -= normalizedLY;
  64635. }
  64636. }
  64637. }
  64638. };
  64639. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64640. return "ArcRotateCameraGamepadInput";
  64641. };
  64642. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64643. return "gamepad";
  64644. };
  64645. __decorate([
  64646. BABYLON.serialize()
  64647. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64648. __decorate([
  64649. BABYLON.serialize()
  64650. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64651. return ArcRotateCameraGamepadInput;
  64652. }());
  64653. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64654. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64655. })(BABYLON || (BABYLON = {}));
  64656. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64657. var BABYLON;
  64658. (function (BABYLON) {
  64659. var GamepadManager = /** @class */ (function () {
  64660. function GamepadManager(_scene) {
  64661. var _this = this;
  64662. this._scene = _scene;
  64663. this._babylonGamepads = [];
  64664. this._oneGamepadConnected = false;
  64665. this._isMonitoring = false;
  64666. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64667. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64668. this._gamepadEventSupported = false;
  64669. }
  64670. else {
  64671. this._gamepadEventSupported = 'GamepadEvent' in window;
  64672. this._gamepadSupport = (navigator.getGamepads ||
  64673. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64674. }
  64675. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64676. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64677. for (var i in _this._babylonGamepads) {
  64678. var gamepad = _this._babylonGamepads[i];
  64679. if (gamepad && gamepad._isConnected) {
  64680. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64681. }
  64682. }
  64683. });
  64684. this._onGamepadConnectedEvent = function (evt) {
  64685. var gamepad = evt.gamepad;
  64686. if (gamepad.index in _this._babylonGamepads) {
  64687. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64688. return;
  64689. }
  64690. }
  64691. var newGamepad;
  64692. if (_this._babylonGamepads[gamepad.index]) {
  64693. newGamepad = _this._babylonGamepads[gamepad.index];
  64694. newGamepad.browserGamepad = gamepad;
  64695. newGamepad._isConnected = true;
  64696. }
  64697. else {
  64698. newGamepad = _this._addNewGamepad(gamepad);
  64699. }
  64700. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64701. _this._startMonitoringGamepads();
  64702. };
  64703. this._onGamepadDisconnectedEvent = function (evt) {
  64704. var gamepad = evt.gamepad;
  64705. // Remove the gamepad from the list of gamepads to monitor.
  64706. for (var i in _this._babylonGamepads) {
  64707. if (_this._babylonGamepads[i].index === gamepad.index) {
  64708. var disconnectedGamepad = _this._babylonGamepads[i];
  64709. disconnectedGamepad._isConnected = false;
  64710. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64711. break;
  64712. }
  64713. }
  64714. };
  64715. if (this._gamepadSupport) {
  64716. //first add already-connected gamepads
  64717. this._updateGamepadObjects();
  64718. if (this._babylonGamepads.length) {
  64719. this._startMonitoringGamepads();
  64720. }
  64721. // Checking if the gamepad connected event is supported (like in Firefox)
  64722. if (this._gamepadEventSupported) {
  64723. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64724. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64725. }
  64726. else {
  64727. this._startMonitoringGamepads();
  64728. }
  64729. }
  64730. }
  64731. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64732. get: function () {
  64733. return this._babylonGamepads;
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. GamepadManager.prototype.getGamepadByType = function (type) {
  64739. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64740. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64741. var gamepad = _a[_i];
  64742. if (gamepad && gamepad.type === type) {
  64743. return gamepad;
  64744. }
  64745. }
  64746. return null;
  64747. };
  64748. GamepadManager.prototype.dispose = function () {
  64749. if (this._gamepadEventSupported) {
  64750. if (this._onGamepadConnectedEvent) {
  64751. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64752. }
  64753. if (this._onGamepadDisconnectedEvent) {
  64754. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64755. }
  64756. this._onGamepadConnectedEvent = null;
  64757. this._onGamepadDisconnectedEvent = null;
  64758. }
  64759. this._babylonGamepads.forEach(function (gamepad) {
  64760. gamepad.dispose();
  64761. });
  64762. this.onGamepadConnectedObservable.clear();
  64763. this.onGamepadDisconnectedObservable.clear();
  64764. this._oneGamepadConnected = false;
  64765. this._stopMonitoringGamepads();
  64766. this._babylonGamepads = [];
  64767. };
  64768. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64769. if (!this._oneGamepadConnected) {
  64770. this._oneGamepadConnected = true;
  64771. }
  64772. var newGamepad;
  64773. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64774. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64775. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64776. }
  64777. else if (gamepad.pose) {
  64778. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64779. }
  64780. else {
  64781. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64782. }
  64783. this._babylonGamepads[newGamepad.index] = newGamepad;
  64784. return newGamepad;
  64785. };
  64786. GamepadManager.prototype._startMonitoringGamepads = function () {
  64787. if (!this._isMonitoring) {
  64788. this._isMonitoring = true;
  64789. //back-comp
  64790. if (!this._scene) {
  64791. this._checkGamepadsStatus();
  64792. }
  64793. }
  64794. };
  64795. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64796. this._isMonitoring = false;
  64797. };
  64798. GamepadManager.prototype._checkGamepadsStatus = function () {
  64799. var _this = this;
  64800. // Hack to be compatible Chrome
  64801. this._updateGamepadObjects();
  64802. for (var i in this._babylonGamepads) {
  64803. var gamepad = this._babylonGamepads[i];
  64804. if (!gamepad || !gamepad.isConnected) {
  64805. continue;
  64806. }
  64807. gamepad.update();
  64808. }
  64809. if (this._isMonitoring && !this._scene) {
  64810. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64811. }
  64812. };
  64813. // This function is called only on Chrome, which does not properly support
  64814. // connection/disconnection events and forces you to recopy again the gamepad object
  64815. GamepadManager.prototype._updateGamepadObjects = function () {
  64816. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64817. for (var i = 0; i < gamepads.length; i++) {
  64818. if (gamepads[i]) {
  64819. if (!this._babylonGamepads[gamepads[i].index]) {
  64820. var newGamepad = this._addNewGamepad(gamepads[i]);
  64821. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64822. }
  64823. else {
  64824. // Forced to copy again this object for Chrome for unknown reason
  64825. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64826. if (!this._babylonGamepads[i].isConnected) {
  64827. this._babylonGamepads[i]._isConnected = true;
  64828. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64829. }
  64830. }
  64831. }
  64832. }
  64833. };
  64834. return GamepadManager;
  64835. }());
  64836. BABYLON.GamepadManager = GamepadManager;
  64837. })(BABYLON || (BABYLON = {}));
  64838. //# sourceMappingURL=babylon.gamepadManager.js.map
  64839. var BABYLON;
  64840. (function (BABYLON) {
  64841. var StickValues = /** @class */ (function () {
  64842. function StickValues(x, y) {
  64843. this.x = x;
  64844. this.y = y;
  64845. }
  64846. return StickValues;
  64847. }());
  64848. BABYLON.StickValues = StickValues;
  64849. var Gamepad = /** @class */ (function () {
  64850. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64851. if (leftStickX === void 0) { leftStickX = 0; }
  64852. if (leftStickY === void 0) { leftStickY = 1; }
  64853. if (rightStickX === void 0) { rightStickX = 2; }
  64854. if (rightStickY === void 0) { rightStickY = 3; }
  64855. this.id = id;
  64856. this.index = index;
  64857. this.browserGamepad = browserGamepad;
  64858. this._isConnected = true;
  64859. this._invertLeftStickY = false;
  64860. this.type = Gamepad.GAMEPAD;
  64861. this._leftStickAxisX = leftStickX;
  64862. this._leftStickAxisY = leftStickY;
  64863. this._rightStickAxisX = rightStickX;
  64864. this._rightStickAxisY = rightStickY;
  64865. if (this.browserGamepad.axes.length >= 2) {
  64866. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64867. }
  64868. if (this.browserGamepad.axes.length >= 4) {
  64869. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64870. }
  64871. }
  64872. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64873. get: function () {
  64874. return this._isConnected;
  64875. },
  64876. enumerable: true,
  64877. configurable: true
  64878. });
  64879. Gamepad.prototype.onleftstickchanged = function (callback) {
  64880. this._onleftstickchanged = callback;
  64881. };
  64882. Gamepad.prototype.onrightstickchanged = function (callback) {
  64883. this._onrightstickchanged = callback;
  64884. };
  64885. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64886. get: function () {
  64887. return this._leftStick;
  64888. },
  64889. set: function (newValues) {
  64890. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64891. this._onleftstickchanged(newValues);
  64892. }
  64893. this._leftStick = newValues;
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64899. get: function () {
  64900. return this._rightStick;
  64901. },
  64902. set: function (newValues) {
  64903. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64904. this._onrightstickchanged(newValues);
  64905. }
  64906. this._rightStick = newValues;
  64907. },
  64908. enumerable: true,
  64909. configurable: true
  64910. });
  64911. Gamepad.prototype.update = function () {
  64912. if (this._leftStick) {
  64913. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64914. if (this._invertLeftStickY) {
  64915. this.leftStick.y *= -1;
  64916. }
  64917. }
  64918. if (this._rightStick) {
  64919. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64920. }
  64921. };
  64922. Gamepad.prototype.dispose = function () {
  64923. };
  64924. Gamepad.GAMEPAD = 0;
  64925. Gamepad.GENERIC = 1;
  64926. Gamepad.XBOX = 2;
  64927. Gamepad.POSE_ENABLED = 3;
  64928. return Gamepad;
  64929. }());
  64930. BABYLON.Gamepad = Gamepad;
  64931. var GenericPad = /** @class */ (function (_super) {
  64932. __extends(GenericPad, _super);
  64933. function GenericPad(id, index, browserGamepad) {
  64934. var _this = _super.call(this, id, index, browserGamepad) || this;
  64935. _this.onButtonDownObservable = new BABYLON.Observable();
  64936. _this.onButtonUpObservable = new BABYLON.Observable();
  64937. _this.type = Gamepad.GENERIC;
  64938. _this._buttons = new Array(browserGamepad.buttons.length);
  64939. return _this;
  64940. }
  64941. GenericPad.prototype.onbuttondown = function (callback) {
  64942. this._onbuttondown = callback;
  64943. };
  64944. GenericPad.prototype.onbuttonup = function (callback) {
  64945. this._onbuttonup = callback;
  64946. };
  64947. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64948. if (newValue !== currentValue) {
  64949. if (newValue === 1) {
  64950. if (this._onbuttondown) {
  64951. this._onbuttondown(buttonIndex);
  64952. }
  64953. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64954. }
  64955. if (newValue === 0) {
  64956. if (this._onbuttonup) {
  64957. this._onbuttonup(buttonIndex);
  64958. }
  64959. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64960. }
  64961. }
  64962. return newValue;
  64963. };
  64964. GenericPad.prototype.update = function () {
  64965. _super.prototype.update.call(this);
  64966. for (var index = 0; index < this._buttons.length; index++) {
  64967. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64968. }
  64969. };
  64970. GenericPad.prototype.dispose = function () {
  64971. _super.prototype.dispose.call(this);
  64972. this.onButtonDownObservable.clear();
  64973. this.onButtonUpObservable.clear();
  64974. };
  64975. return GenericPad;
  64976. }(Gamepad));
  64977. BABYLON.GenericPad = GenericPad;
  64978. })(BABYLON || (BABYLON = {}));
  64979. //# sourceMappingURL=babylon.gamepad.js.map
  64980. var BABYLON;
  64981. (function (BABYLON) {
  64982. var Xbox360Button;
  64983. (function (Xbox360Button) {
  64984. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64985. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64986. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64987. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64988. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64989. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64990. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64991. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64992. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64993. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64994. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64995. var Xbox360Dpad;
  64996. (function (Xbox360Dpad) {
  64997. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64998. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64999. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65000. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65001. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65002. var Xbox360Pad = /** @class */ (function (_super) {
  65003. __extends(Xbox360Pad, _super);
  65004. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65005. if (xboxOne === void 0) { xboxOne = false; }
  65006. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65007. _this._leftTrigger = 0;
  65008. _this._rightTrigger = 0;
  65009. _this.onButtonDownObservable = new BABYLON.Observable();
  65010. _this.onButtonUpObservable = new BABYLON.Observable();
  65011. _this.onPadDownObservable = new BABYLON.Observable();
  65012. _this.onPadUpObservable = new BABYLON.Observable();
  65013. _this._buttonA = 0;
  65014. _this._buttonB = 0;
  65015. _this._buttonX = 0;
  65016. _this._buttonY = 0;
  65017. _this._buttonBack = 0;
  65018. _this._buttonStart = 0;
  65019. _this._buttonLB = 0;
  65020. _this._buttonRB = 0;
  65021. _this._buttonLeftStick = 0;
  65022. _this._buttonRightStick = 0;
  65023. _this._dPadUp = 0;
  65024. _this._dPadDown = 0;
  65025. _this._dPadLeft = 0;
  65026. _this._dPadRight = 0;
  65027. _this._isXboxOnePad = false;
  65028. _this.type = BABYLON.Gamepad.XBOX;
  65029. _this._isXboxOnePad = xboxOne;
  65030. return _this;
  65031. }
  65032. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65033. this._onlefttriggerchanged = callback;
  65034. };
  65035. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65036. this._onrighttriggerchanged = callback;
  65037. };
  65038. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65039. get: function () {
  65040. return this._leftTrigger;
  65041. },
  65042. set: function (newValue) {
  65043. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65044. this._onlefttriggerchanged(newValue);
  65045. }
  65046. this._leftTrigger = newValue;
  65047. },
  65048. enumerable: true,
  65049. configurable: true
  65050. });
  65051. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65052. get: function () {
  65053. return this._rightTrigger;
  65054. },
  65055. set: function (newValue) {
  65056. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65057. this._onrighttriggerchanged(newValue);
  65058. }
  65059. this._rightTrigger = newValue;
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65065. this._onbuttondown = callback;
  65066. };
  65067. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65068. this._onbuttonup = callback;
  65069. };
  65070. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65071. this._ondpaddown = callback;
  65072. };
  65073. Xbox360Pad.prototype.ondpadup = function (callback) {
  65074. this._ondpadup = callback;
  65075. };
  65076. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65077. if (newValue !== currentValue) {
  65078. if (newValue === 1) {
  65079. if (this._onbuttondown) {
  65080. this._onbuttondown(buttonType);
  65081. }
  65082. this.onButtonDownObservable.notifyObservers(buttonType);
  65083. }
  65084. if (newValue === 0) {
  65085. if (this._onbuttonup) {
  65086. this._onbuttonup(buttonType);
  65087. }
  65088. this.onButtonUpObservable.notifyObservers(buttonType);
  65089. }
  65090. }
  65091. return newValue;
  65092. };
  65093. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65094. if (newValue !== currentValue) {
  65095. if (newValue === 1) {
  65096. if (this._ondpaddown) {
  65097. this._ondpaddown(buttonType);
  65098. }
  65099. this.onPadDownObservable.notifyObservers(buttonType);
  65100. }
  65101. if (newValue === 0) {
  65102. if (this._ondpadup) {
  65103. this._ondpadup(buttonType);
  65104. }
  65105. this.onPadUpObservable.notifyObservers(buttonType);
  65106. }
  65107. }
  65108. return newValue;
  65109. };
  65110. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65111. get: function () {
  65112. return this._buttonA;
  65113. },
  65114. set: function (value) {
  65115. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65121. get: function () {
  65122. return this._buttonB;
  65123. },
  65124. set: function (value) {
  65125. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65126. },
  65127. enumerable: true,
  65128. configurable: true
  65129. });
  65130. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65131. get: function () {
  65132. return this._buttonX;
  65133. },
  65134. set: function (value) {
  65135. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65136. },
  65137. enumerable: true,
  65138. configurable: true
  65139. });
  65140. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65141. get: function () {
  65142. return this._buttonY;
  65143. },
  65144. set: function (value) {
  65145. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65146. },
  65147. enumerable: true,
  65148. configurable: true
  65149. });
  65150. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65151. get: function () {
  65152. return this._buttonStart;
  65153. },
  65154. set: function (value) {
  65155. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65156. },
  65157. enumerable: true,
  65158. configurable: true
  65159. });
  65160. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65161. get: function () {
  65162. return this._buttonBack;
  65163. },
  65164. set: function (value) {
  65165. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65166. },
  65167. enumerable: true,
  65168. configurable: true
  65169. });
  65170. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65171. get: function () {
  65172. return this._buttonLB;
  65173. },
  65174. set: function (value) {
  65175. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65176. },
  65177. enumerable: true,
  65178. configurable: true
  65179. });
  65180. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65181. get: function () {
  65182. return this._buttonRB;
  65183. },
  65184. set: function (value) {
  65185. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65186. },
  65187. enumerable: true,
  65188. configurable: true
  65189. });
  65190. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65191. get: function () {
  65192. return this._buttonLeftStick;
  65193. },
  65194. set: function (value) {
  65195. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65196. },
  65197. enumerable: true,
  65198. configurable: true
  65199. });
  65200. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65201. get: function () {
  65202. return this._buttonRightStick;
  65203. },
  65204. set: function (value) {
  65205. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65206. },
  65207. enumerable: true,
  65208. configurable: true
  65209. });
  65210. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65211. get: function () {
  65212. return this._dPadUp;
  65213. },
  65214. set: function (value) {
  65215. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65216. },
  65217. enumerable: true,
  65218. configurable: true
  65219. });
  65220. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65221. get: function () {
  65222. return this._dPadDown;
  65223. },
  65224. set: function (value) {
  65225. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65226. },
  65227. enumerable: true,
  65228. configurable: true
  65229. });
  65230. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65231. get: function () {
  65232. return this._dPadLeft;
  65233. },
  65234. set: function (value) {
  65235. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65236. },
  65237. enumerable: true,
  65238. configurable: true
  65239. });
  65240. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65241. get: function () {
  65242. return this._dPadRight;
  65243. },
  65244. set: function (value) {
  65245. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65246. },
  65247. enumerable: true,
  65248. configurable: true
  65249. });
  65250. Xbox360Pad.prototype.update = function () {
  65251. _super.prototype.update.call(this);
  65252. if (this._isXboxOnePad) {
  65253. this.buttonA = this.browserGamepad.buttons[0].value;
  65254. this.buttonB = this.browserGamepad.buttons[1].value;
  65255. this.buttonX = this.browserGamepad.buttons[2].value;
  65256. this.buttonY = this.browserGamepad.buttons[3].value;
  65257. this.buttonLB = this.browserGamepad.buttons[4].value;
  65258. this.buttonRB = this.browserGamepad.buttons[5].value;
  65259. this.leftTrigger = this.browserGamepad.axes[2];
  65260. this.rightTrigger = this.browserGamepad.axes[5];
  65261. this.buttonBack = this.browserGamepad.buttons[9].value;
  65262. this.buttonStart = this.browserGamepad.buttons[8].value;
  65263. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65264. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65265. this.dPadUp = this.browserGamepad.buttons[11].value;
  65266. this.dPadDown = this.browserGamepad.buttons[12].value;
  65267. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65268. this.dPadRight = this.browserGamepad.buttons[14].value;
  65269. }
  65270. else {
  65271. this.buttonA = this.browserGamepad.buttons[0].value;
  65272. this.buttonB = this.browserGamepad.buttons[1].value;
  65273. this.buttonX = this.browserGamepad.buttons[2].value;
  65274. this.buttonY = this.browserGamepad.buttons[3].value;
  65275. this.buttonLB = this.browserGamepad.buttons[4].value;
  65276. this.buttonRB = this.browserGamepad.buttons[5].value;
  65277. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65278. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65279. this.buttonBack = this.browserGamepad.buttons[8].value;
  65280. this.buttonStart = this.browserGamepad.buttons[9].value;
  65281. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65282. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65283. this.dPadUp = this.browserGamepad.buttons[12].value;
  65284. this.dPadDown = this.browserGamepad.buttons[13].value;
  65285. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65286. this.dPadRight = this.browserGamepad.buttons[15].value;
  65287. }
  65288. };
  65289. Xbox360Pad.prototype.dispose = function () {
  65290. _super.prototype.dispose.call(this);
  65291. this.onButtonDownObservable.clear();
  65292. this.onButtonUpObservable.clear();
  65293. this.onPadDownObservable.clear();
  65294. this.onPadUpObservable.clear();
  65295. };
  65296. return Xbox360Pad;
  65297. }(BABYLON.Gamepad));
  65298. BABYLON.Xbox360Pad = Xbox360Pad;
  65299. })(BABYLON || (BABYLON = {}));
  65300. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65301. var BABYLON;
  65302. (function (BABYLON) {
  65303. var PoseEnabledControllerType;
  65304. (function (PoseEnabledControllerType) {
  65305. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65306. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65307. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65308. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65309. /**
  65310. * Google Daydream
  65311. */
  65312. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65313. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65314. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65315. var PoseEnabledControllerHelper = /** @class */ (function () {
  65316. function PoseEnabledControllerHelper() {
  65317. }
  65318. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65319. // Oculus Touch
  65320. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65321. return new BABYLON.OculusTouchController(vrGamepad);
  65322. }
  65323. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65324. return new BABYLON.WindowsMotionController(vrGamepad);
  65325. }
  65326. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65327. return new BABYLON.ViveController(vrGamepad);
  65328. }
  65329. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65330. return new BABYLON.GearVRController(vrGamepad);
  65331. }
  65332. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65333. return new BABYLON.DaydreamController(vrGamepad);
  65334. }
  65335. else {
  65336. return new BABYLON.GenericController(vrGamepad);
  65337. }
  65338. };
  65339. return PoseEnabledControllerHelper;
  65340. }());
  65341. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65342. var PoseEnabledController = /** @class */ (function (_super) {
  65343. __extends(PoseEnabledController, _super);
  65344. function PoseEnabledController(browserGamepad) {
  65345. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65346. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65347. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65348. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65349. // Represents device position and rotation in babylon space
  65350. _this.devicePosition = BABYLON.Vector3.Zero();
  65351. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65352. _this.deviceScaleFactor = 1;
  65353. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65354. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65355. /**
  65356. * Node to be used when casting a ray from the controller
  65357. */
  65358. _this._pointingPoseNode = null;
  65359. _this._workingMatrix = BABYLON.Matrix.Identity();
  65360. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65361. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65362. _this.position = BABYLON.Vector3.Zero();
  65363. _this.rotationQuaternion = new BABYLON.Quaternion();
  65364. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65365. _this._calculatedRotation = new BABYLON.Quaternion();
  65366. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65367. return _this;
  65368. }
  65369. PoseEnabledController.prototype.update = function () {
  65370. _super.prototype.update.call(this);
  65371. var pose = this.browserGamepad.pose;
  65372. this.updateFromDevice(pose);
  65373. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65374. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65375. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65376. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65377. if (this._mesh) {
  65378. this._mesh.position.copyFrom(this.devicePosition);
  65379. if (this._mesh.rotationQuaternion) {
  65380. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65381. }
  65382. }
  65383. };
  65384. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65385. if (poseData) {
  65386. this.rawPose = poseData;
  65387. if (poseData.position) {
  65388. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65389. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65390. this._deviceRoomPosition.z *= -1;
  65391. }
  65392. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65393. this._calculatedPosition.addInPlace(this.position);
  65394. }
  65395. var pose = this.rawPose;
  65396. if (poseData.orientation && pose.orientation) {
  65397. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65398. if (this._mesh) {
  65399. if (this._mesh.getScene().useRightHandedSystem) {
  65400. this._deviceRoomRotationQuaternion.z *= -1;
  65401. this._deviceRoomRotationQuaternion.w *= -1;
  65402. }
  65403. else {
  65404. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65405. }
  65406. }
  65407. // if the camera is set, rotate to the camera's rotation
  65408. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65409. }
  65410. }
  65411. };
  65412. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65413. if (this._mesh) {
  65414. this._mesh.parent = null;
  65415. }
  65416. this._mesh = mesh;
  65417. if (this._poseControlledCamera) {
  65418. this._mesh.parent = this._poseControlledCamera;
  65419. }
  65420. if (!this._mesh.rotationQuaternion) {
  65421. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65422. }
  65423. };
  65424. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65425. this._poseControlledCamera = camera;
  65426. if (this._mesh) {
  65427. this._mesh.parent = this._poseControlledCamera;
  65428. }
  65429. };
  65430. PoseEnabledController.prototype.dispose = function () {
  65431. if (this._mesh) {
  65432. this._mesh.dispose();
  65433. }
  65434. this._mesh = null;
  65435. _super.prototype.dispose.call(this);
  65436. };
  65437. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65438. get: function () {
  65439. return this._mesh;
  65440. },
  65441. enumerable: true,
  65442. configurable: true
  65443. });
  65444. PoseEnabledController.prototype.getForwardRay = function (length) {
  65445. if (length === void 0) { length = 100; }
  65446. if (!this.mesh) {
  65447. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65448. }
  65449. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65450. var origin = m.getTranslation();
  65451. var forward = new BABYLON.Vector3(0, 0, -1);
  65452. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65453. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65454. return new BABYLON.Ray(origin, direction, length);
  65455. };
  65456. /**
  65457. * Name of the child mesh that can be used to cast a ray from the controller
  65458. */
  65459. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65460. return PoseEnabledController;
  65461. }(BABYLON.Gamepad));
  65462. BABYLON.PoseEnabledController = PoseEnabledController;
  65463. })(BABYLON || (BABYLON = {}));
  65464. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65465. var BABYLON;
  65466. (function (BABYLON) {
  65467. var WebVRController = /** @class */ (function (_super) {
  65468. __extends(WebVRController, _super);
  65469. function WebVRController(vrGamepad) {
  65470. var _this = _super.call(this, vrGamepad) || this;
  65471. // Observables
  65472. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65473. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65474. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65475. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65476. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65477. _this.pad = { x: 0, y: 0 };
  65478. // avoid GC, store state in a tmp object
  65479. _this._changes = {
  65480. pressChanged: false,
  65481. touchChanged: false,
  65482. valueChanged: false,
  65483. changed: false
  65484. };
  65485. _this._buttons = new Array(vrGamepad.buttons.length);
  65486. _this.hand = vrGamepad.hand;
  65487. return _this;
  65488. }
  65489. WebVRController.prototype.onButtonStateChange = function (callback) {
  65490. this._onButtonStateChange = callback;
  65491. };
  65492. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65493. get: function () {
  65494. return this._defaultModel;
  65495. },
  65496. enumerable: true,
  65497. configurable: true
  65498. });
  65499. WebVRController.prototype.update = function () {
  65500. _super.prototype.update.call(this);
  65501. for (var index = 0; index < this._buttons.length; index++) {
  65502. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65503. }
  65504. ;
  65505. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65506. this.pad.x = this.leftStick.x;
  65507. this.pad.y = this.leftStick.y;
  65508. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65509. }
  65510. };
  65511. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65512. if (!newState) {
  65513. newState = {
  65514. pressed: false,
  65515. touched: false,
  65516. value: 0
  65517. };
  65518. }
  65519. if (!currentState) {
  65520. this._buttons[buttonIndex] = {
  65521. pressed: newState.pressed,
  65522. touched: newState.touched,
  65523. value: newState.value
  65524. };
  65525. return;
  65526. }
  65527. this._checkChanges(newState, currentState);
  65528. if (this._changes.changed) {
  65529. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65530. this._handleButtonChange(buttonIndex, newState, this._changes);
  65531. }
  65532. this._buttons[buttonIndex].pressed = newState.pressed;
  65533. this._buttons[buttonIndex].touched = newState.touched;
  65534. // oculus triggers are never 0, thou not touched.
  65535. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65536. };
  65537. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65538. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65539. this._changes.touchChanged = newState.touched !== currentState.touched;
  65540. this._changes.valueChanged = newState.value !== currentState.value;
  65541. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65542. return this._changes;
  65543. };
  65544. WebVRController.prototype.dispose = function () {
  65545. _super.prototype.dispose.call(this);
  65546. this.onTriggerStateChangedObservable.clear();
  65547. this.onMainButtonStateChangedObservable.clear();
  65548. this.onSecondaryButtonStateChangedObservable.clear();
  65549. this.onPadStateChangedObservable.clear();
  65550. this.onPadValuesChangedObservable.clear();
  65551. };
  65552. return WebVRController;
  65553. }(BABYLON.PoseEnabledController));
  65554. BABYLON.WebVRController = WebVRController;
  65555. })(BABYLON || (BABYLON = {}));
  65556. //# sourceMappingURL=babylon.webVRController.js.map
  65557. var BABYLON;
  65558. (function (BABYLON) {
  65559. var OculusTouchController = /** @class */ (function (_super) {
  65560. __extends(OculusTouchController, _super);
  65561. function OculusTouchController(vrGamepad) {
  65562. var _this = _super.call(this, vrGamepad) || this;
  65563. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65564. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65565. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65566. return _this;
  65567. }
  65568. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65569. var _this = this;
  65570. var meshName;
  65571. // Hand
  65572. if (this.hand === 'left') {
  65573. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65574. }
  65575. else {
  65576. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65577. }
  65578. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65579. /*
  65580. Parent Mesh name: oculus_touch_left
  65581. - body
  65582. - trigger
  65583. - thumbstick
  65584. - grip
  65585. - button_y
  65586. - button_x
  65587. - button_enter
  65588. */
  65589. _this._defaultModel = newMeshes[1];
  65590. _this.attachToMesh(_this._defaultModel);
  65591. if (meshLoaded) {
  65592. meshLoaded(_this._defaultModel);
  65593. }
  65594. });
  65595. };
  65596. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65597. // helper getters for left and right hand.
  65598. get: function () {
  65599. if (this.hand === 'right') {
  65600. return this.onMainButtonStateChangedObservable;
  65601. }
  65602. else {
  65603. throw new Error('No A button on left hand');
  65604. }
  65605. },
  65606. enumerable: true,
  65607. configurable: true
  65608. });
  65609. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65610. get: function () {
  65611. if (this.hand === 'right') {
  65612. return this.onSecondaryButtonStateChangedObservable;
  65613. }
  65614. else {
  65615. throw new Error('No B button on left hand');
  65616. }
  65617. },
  65618. enumerable: true,
  65619. configurable: true
  65620. });
  65621. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65622. get: function () {
  65623. if (this.hand === 'left') {
  65624. return this.onMainButtonStateChangedObservable;
  65625. }
  65626. else {
  65627. throw new Error('No X button on right hand');
  65628. }
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65634. get: function () {
  65635. if (this.hand === 'left') {
  65636. return this.onSecondaryButtonStateChangedObservable;
  65637. }
  65638. else {
  65639. throw new Error('No Y button on right hand');
  65640. }
  65641. },
  65642. enumerable: true,
  65643. configurable: true
  65644. });
  65645. /*
  65646. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65647. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65648. 2) secondary trigger (same)
  65649. 3) A (right) X (left), touch, pressed = value
  65650. 4) B / Y
  65651. 5) thumb rest
  65652. */
  65653. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65654. var notifyObject = state; //{ state: state, changes: changes };
  65655. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65656. switch (buttonIdx) {
  65657. case 0:
  65658. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65659. return;
  65660. case 1:// index trigger
  65661. if (this._defaultModel) {
  65662. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65663. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65664. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65665. }
  65666. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65667. return;
  65668. case 2:// secondary trigger
  65669. if (this._defaultModel) {
  65670. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65671. }
  65672. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65673. return;
  65674. case 3:
  65675. if (this._defaultModel) {
  65676. if (notifyObject.pressed) {
  65677. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65678. }
  65679. else {
  65680. (this._defaultModel.getChildren()[1]).position.y = 0;
  65681. }
  65682. }
  65683. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65684. return;
  65685. case 4:
  65686. if (this._defaultModel) {
  65687. if (notifyObject.pressed) {
  65688. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65689. }
  65690. else {
  65691. (this._defaultModel.getChildren()[2]).position.y = 0;
  65692. }
  65693. }
  65694. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65695. return;
  65696. case 5:
  65697. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65698. return;
  65699. }
  65700. };
  65701. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65702. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65703. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65704. return OculusTouchController;
  65705. }(BABYLON.WebVRController));
  65706. BABYLON.OculusTouchController = OculusTouchController;
  65707. })(BABYLON || (BABYLON = {}));
  65708. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65709. var BABYLON;
  65710. (function (BABYLON) {
  65711. var ViveController = /** @class */ (function (_super) {
  65712. __extends(ViveController, _super);
  65713. function ViveController(vrGamepad) {
  65714. var _this = _super.call(this, vrGamepad) || this;
  65715. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65716. _this._invertLeftStickY = true;
  65717. return _this;
  65718. }
  65719. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65720. var _this = this;
  65721. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65722. /*
  65723. Parent Mesh name: ViveWand
  65724. - body
  65725. - r_gripper
  65726. - l_gripper
  65727. - menu_button
  65728. - system_button
  65729. - trackpad
  65730. - trigger
  65731. - LED
  65732. */
  65733. _this._defaultModel = newMeshes[1];
  65734. _this.attachToMesh(_this._defaultModel);
  65735. if (meshLoaded) {
  65736. meshLoaded(_this._defaultModel);
  65737. }
  65738. });
  65739. };
  65740. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65741. get: function () {
  65742. return this.onMainButtonStateChangedObservable;
  65743. },
  65744. enumerable: true,
  65745. configurable: true
  65746. });
  65747. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65748. get: function () {
  65749. return this.onMainButtonStateChangedObservable;
  65750. },
  65751. enumerable: true,
  65752. configurable: true
  65753. });
  65754. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65755. get: function () {
  65756. return this.onSecondaryButtonStateChangedObservable;
  65757. },
  65758. enumerable: true,
  65759. configurable: true
  65760. });
  65761. /**
  65762. * Vive mapping:
  65763. * 0: touchpad
  65764. * 1: trigger
  65765. * 2: left AND right buttons
  65766. * 3: menu button
  65767. */
  65768. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65769. var notifyObject = state; //{ state: state, changes: changes };
  65770. switch (buttonIdx) {
  65771. case 0:
  65772. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65773. return;
  65774. case 1:// index trigger
  65775. if (this._defaultModel) {
  65776. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65777. }
  65778. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65779. return;
  65780. case 2:// left AND right button
  65781. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65782. return;
  65783. case 3:
  65784. if (this._defaultModel) {
  65785. if (notifyObject.pressed) {
  65786. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65787. }
  65788. else {
  65789. (this._defaultModel.getChildren()[2]).position.y = 0;
  65790. }
  65791. }
  65792. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65793. return;
  65794. }
  65795. };
  65796. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65797. ViveController.MODEL_FILENAME = 'wand.babylon';
  65798. return ViveController;
  65799. }(BABYLON.WebVRController));
  65800. BABYLON.ViveController = ViveController;
  65801. })(BABYLON || (BABYLON = {}));
  65802. //# sourceMappingURL=babylon.viveController.js.map
  65803. var BABYLON;
  65804. (function (BABYLON) {
  65805. var GenericController = /** @class */ (function (_super) {
  65806. __extends(GenericController, _super);
  65807. function GenericController(vrGamepad) {
  65808. return _super.call(this, vrGamepad) || this;
  65809. }
  65810. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65811. var _this = this;
  65812. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65813. _this._defaultModel = newMeshes[1];
  65814. _this.attachToMesh(_this._defaultModel);
  65815. if (meshLoaded) {
  65816. meshLoaded(_this._defaultModel);
  65817. }
  65818. });
  65819. };
  65820. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65821. console.log("Button id: " + buttonIdx + "state: ");
  65822. console.dir(state);
  65823. };
  65824. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65825. GenericController.MODEL_FILENAME = 'generic.babylon';
  65826. return GenericController;
  65827. }(BABYLON.WebVRController));
  65828. BABYLON.GenericController = GenericController;
  65829. })(BABYLON || (BABYLON = {}));
  65830. //# sourceMappingURL=babylon.genericController.js.map
  65831. var BABYLON;
  65832. (function (BABYLON) {
  65833. var LoadedMeshInfo = /** @class */ (function () {
  65834. function LoadedMeshInfo() {
  65835. this.buttonMeshes = {};
  65836. this.axisMeshes = {};
  65837. }
  65838. return LoadedMeshInfo;
  65839. }());
  65840. var WindowsMotionController = /** @class */ (function (_super) {
  65841. __extends(WindowsMotionController, _super);
  65842. function WindowsMotionController(vrGamepad) {
  65843. var _this = _super.call(this, vrGamepad) || this;
  65844. _this._mapping = {
  65845. // Semantic button names
  65846. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65847. // A mapping of the button name to glTF model node name
  65848. // that should be transformed by button value.
  65849. buttonMeshNames: {
  65850. 'trigger': 'SELECT',
  65851. 'menu': 'MENU',
  65852. 'grip': 'GRASP',
  65853. 'thumbstick': 'THUMBSTICK_PRESS',
  65854. 'trackpad': 'TOUCHPAD_PRESS'
  65855. },
  65856. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65857. buttonObservableNames: {
  65858. 'trigger': 'onTriggerStateChangedObservable',
  65859. 'menu': 'onSecondaryButtonStateChangedObservable',
  65860. 'grip': 'onMainButtonStateChangedObservable',
  65861. 'thumbstick': 'onPadStateChangedObservable',
  65862. 'trackpad': 'onTrackpadChangedObservable'
  65863. },
  65864. // A mapping of the axis name to glTF model node name
  65865. // that should be transformed by axis value.
  65866. // This array mirrors the browserGamepad.axes array, such that
  65867. // the mesh corresponding to axis 0 is in this array index 0.
  65868. axisMeshNames: [
  65869. 'THUMBSTICK_X',
  65870. 'THUMBSTICK_Y',
  65871. 'TOUCHPAD_TOUCH_X',
  65872. 'TOUCHPAD_TOUCH_Y'
  65873. ],
  65874. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65875. };
  65876. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65877. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65878. _this.trackpad = { x: 0, y: 0 };
  65879. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65880. _this._loadedMeshInfo = null;
  65881. return _this;
  65882. }
  65883. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65884. get: function () {
  65885. return this.onTriggerStateChangedObservable;
  65886. },
  65887. enumerable: true,
  65888. configurable: true
  65889. });
  65890. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65891. get: function () {
  65892. return this.onSecondaryButtonStateChangedObservable;
  65893. },
  65894. enumerable: true,
  65895. configurable: true
  65896. });
  65897. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65898. get: function () {
  65899. return this.onMainButtonStateChangedObservable;
  65900. },
  65901. enumerable: true,
  65902. configurable: true
  65903. });
  65904. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65905. get: function () {
  65906. return this.onPadStateChangedObservable;
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65912. get: function () {
  65913. return this.onTrackpadChangedObservable;
  65914. },
  65915. enumerable: true,
  65916. configurable: true
  65917. });
  65918. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65919. get: function () {
  65920. return this.onTrackpadValuesChangedObservable;
  65921. },
  65922. enumerable: true,
  65923. configurable: true
  65924. });
  65925. /**
  65926. * Called once per frame by the engine.
  65927. */
  65928. WindowsMotionController.prototype.update = function () {
  65929. _super.prototype.update.call(this);
  65930. if (this.browserGamepad.axes) {
  65931. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65932. this.trackpad.x = this.browserGamepad["axes"][2];
  65933. this.trackpad.y = this.browserGamepad["axes"][3];
  65934. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65935. }
  65936. // Only need to animate axes if there is a loaded mesh
  65937. if (this._loadedMeshInfo) {
  65938. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65939. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65940. }
  65941. }
  65942. }
  65943. };
  65944. /**
  65945. * Called once for each button that changed state since the last frame
  65946. * @param buttonIdx Which button index changed
  65947. * @param state New state of the button
  65948. * @param changes Which properties on the state changed since last frame
  65949. */
  65950. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65951. var buttonName = this._mapping.buttons[buttonIdx];
  65952. if (!buttonName) {
  65953. return;
  65954. }
  65955. // Only emit events for buttons that we know how to map from index to name
  65956. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65957. if (observable) {
  65958. observable.notifyObservers(state);
  65959. }
  65960. this.lerpButtonTransform(buttonName, state.value);
  65961. };
  65962. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65963. // If there is no loaded mesh, there is nothing to transform.
  65964. if (!this._loadedMeshInfo) {
  65965. return;
  65966. }
  65967. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65968. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65969. return;
  65970. }
  65971. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65972. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65973. };
  65974. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65975. if (!this._loadedMeshInfo) {
  65976. return;
  65977. }
  65978. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65979. if (!meshInfo) {
  65980. return;
  65981. }
  65982. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65983. return;
  65984. }
  65985. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65986. var lerpValue = axisValue * 0.5 + 0.5;
  65987. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65988. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65989. };
  65990. /**
  65991. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65992. * @param scene scene in which to add meshes
  65993. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65994. */
  65995. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65996. var _this = this;
  65997. if (forceDefault === void 0) { forceDefault = false; }
  65998. var path;
  65999. var filename;
  66000. // Checking if GLB loader is present
  66001. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66002. // Determine the device specific folder based on the ID suffix
  66003. var device = 'default';
  66004. if (this.id && !forceDefault) {
  66005. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66006. device = ((match && match[0]) || device);
  66007. }
  66008. // Hand
  66009. if (this.hand === 'left') {
  66010. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66011. }
  66012. else {
  66013. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66014. }
  66015. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66016. }
  66017. else {
  66018. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66019. path = BABYLON.GenericController.MODEL_BASE_URL;
  66020. filename = BABYLON.GenericController.MODEL_FILENAME;
  66021. }
  66022. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66023. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66024. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66025. if (!_this._loadedMeshInfo) {
  66026. return;
  66027. }
  66028. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66029. _this.attachToMesh(_this._defaultModel);
  66030. if (meshLoaded) {
  66031. meshLoaded(_this._defaultModel);
  66032. }
  66033. }, null, function (scene, message) {
  66034. BABYLON.Tools.Log(message);
  66035. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66036. if (!forceDefault) {
  66037. _this.initControllerMesh(scene, meshLoaded, true);
  66038. }
  66039. });
  66040. };
  66041. /**
  66042. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66043. * can be transformed by button presses and axes values, based on this._mapping.
  66044. *
  66045. * @param scene scene in which the meshes exist
  66046. * @param meshes list of meshes that make up the controller model to process
  66047. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66048. */
  66049. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66050. var loadedMeshInfo = null;
  66051. // Create a new mesh to contain the glTF hierarchy
  66052. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66053. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66054. var childMesh = null;
  66055. for (var i = 0; i < meshes.length; i++) {
  66056. var mesh = meshes[i];
  66057. if (!mesh.parent) {
  66058. // Exclude controller meshes from picking results
  66059. mesh.isPickable = false;
  66060. // Handle root node, attach to the new parentMesh
  66061. childMesh = mesh;
  66062. break;
  66063. }
  66064. }
  66065. if (childMesh) {
  66066. childMesh.setParent(parentMesh);
  66067. // Create our mesh info. Note that this method will always return non-null.
  66068. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66069. }
  66070. else {
  66071. BABYLON.Tools.Warn('Could not find root node in model file.');
  66072. }
  66073. return loadedMeshInfo;
  66074. };
  66075. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66076. var loadedMeshInfo = new LoadedMeshInfo();
  66077. var i;
  66078. loadedMeshInfo.rootNode = rootNode;
  66079. // Reset the caches
  66080. loadedMeshInfo.buttonMeshes = {};
  66081. loadedMeshInfo.axisMeshes = {};
  66082. // Button Meshes
  66083. for (i = 0; i < this._mapping.buttons.length; i++) {
  66084. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66085. if (!buttonMeshName) {
  66086. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66087. continue;
  66088. }
  66089. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66090. if (!buttonMesh) {
  66091. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66092. continue;
  66093. }
  66094. var buttonMeshInfo = {
  66095. index: i,
  66096. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66097. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66098. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66099. };
  66100. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66101. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66102. }
  66103. else {
  66104. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66105. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66106. '(VALUE: ' + !!buttonMeshInfo.value +
  66107. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66108. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66109. ')');
  66110. }
  66111. }
  66112. // Axis Meshes
  66113. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66114. var axisMeshName = this._mapping.axisMeshNames[i];
  66115. if (!axisMeshName) {
  66116. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66117. continue;
  66118. }
  66119. var axisMesh = getChildByName(rootNode, axisMeshName);
  66120. if (!axisMesh) {
  66121. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66122. continue;
  66123. }
  66124. var axisMeshInfo = {
  66125. index: i,
  66126. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66127. min: getImmediateChildByName(axisMesh, 'MIN'),
  66128. max: getImmediateChildByName(axisMesh, 'MAX')
  66129. };
  66130. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66131. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66132. }
  66133. else {
  66134. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66135. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66136. '(VALUE: ' + !!axisMeshInfo.value +
  66137. ', MIN: ' + !!axisMeshInfo.min +
  66138. ', MAX:' + !!axisMeshInfo.max +
  66139. ')');
  66140. }
  66141. }
  66142. // Pointing Ray
  66143. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66144. if (!loadedMeshInfo.pointingPoseNode) {
  66145. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66146. }
  66147. return loadedMeshInfo;
  66148. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66149. function getChildByName(node, name) {
  66150. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66151. }
  66152. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66153. function getImmediateChildByName(node, name) {
  66154. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66155. }
  66156. };
  66157. WindowsMotionController.prototype.getForwardRay = function (length) {
  66158. if (length === void 0) { length = 100; }
  66159. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66160. return _super.prototype.getForwardRay.call(this, length);
  66161. }
  66162. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66163. var origin = m.getTranslation();
  66164. var forward = new BABYLON.Vector3(0, 0, -1);
  66165. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66166. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66167. return new BABYLON.Ray(origin, direction, length);
  66168. };
  66169. WindowsMotionController.prototype.dispose = function () {
  66170. _super.prototype.dispose.call(this);
  66171. this.onTrackpadChangedObservable.clear();
  66172. };
  66173. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66174. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66175. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66176. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66177. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66178. return WindowsMotionController;
  66179. }(BABYLON.WebVRController));
  66180. BABYLON.WindowsMotionController = WindowsMotionController;
  66181. })(BABYLON || (BABYLON = {}));
  66182. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66183. var BABYLON;
  66184. (function (BABYLON) {
  66185. var GearVRController = /** @class */ (function (_super) {
  66186. __extends(GearVRController, _super);
  66187. function GearVRController(vrGamepad) {
  66188. var _this = _super.call(this, vrGamepad) || this;
  66189. _this._buttonIndexToObservableNameMap = [
  66190. 'onTrackpadChangedObservable',
  66191. 'onTriggerStateChangedObservable' // Trigger
  66192. ];
  66193. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66194. return _this;
  66195. }
  66196. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66197. var _this = this;
  66198. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66199. _this._defaultModel = newMeshes[1];
  66200. _this.attachToMesh(_this._defaultModel);
  66201. if (meshLoaded) {
  66202. meshLoaded(_this._defaultModel);
  66203. }
  66204. });
  66205. };
  66206. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66207. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66208. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66209. // Only emit events for buttons that we know how to map from index to observable
  66210. var observable = this[observableName];
  66211. if (observable) {
  66212. observable.notifyObservers(state);
  66213. }
  66214. }
  66215. };
  66216. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66217. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66218. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66219. return GearVRController;
  66220. }(BABYLON.WebVRController));
  66221. BABYLON.GearVRController = GearVRController;
  66222. })(BABYLON || (BABYLON = {}));
  66223. //# sourceMappingURL=babylon.gearVRController.js.map
  66224. var BABYLON;
  66225. (function (BABYLON) {
  66226. /**
  66227. * Google Daydream controller
  66228. */
  66229. var DaydreamController = /** @class */ (function (_super) {
  66230. __extends(DaydreamController, _super);
  66231. function DaydreamController(vrGamepad) {
  66232. var _this = _super.call(this, vrGamepad) || this;
  66233. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66234. return _this;
  66235. }
  66236. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66237. var _this = this;
  66238. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66239. _this._defaultModel = newMeshes[1];
  66240. _this.attachToMesh(_this._defaultModel);
  66241. if (meshLoaded) {
  66242. meshLoaded(_this._defaultModel);
  66243. }
  66244. });
  66245. };
  66246. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66247. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66248. if (buttonIdx === 0) {
  66249. var observable = this.onTriggerStateChangedObservable;
  66250. if (observable) {
  66251. observable.notifyObservers(state);
  66252. }
  66253. }
  66254. else {
  66255. // If the app or home buttons are ever made available
  66256. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66257. }
  66258. };
  66259. /**
  66260. * Base Url for the controller model.
  66261. */
  66262. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66263. /**
  66264. * File name for the controller model.
  66265. */
  66266. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66267. /**
  66268. * Gamepad Id prefix used to identify Daydream Controller.
  66269. */
  66270. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66271. return DaydreamController;
  66272. }(BABYLON.WebVRController));
  66273. BABYLON.DaydreamController = DaydreamController;
  66274. })(BABYLON || (BABYLON = {}));
  66275. //# sourceMappingURL=babylon.daydreamController.js.map
  66276. var BABYLON;
  66277. (function (BABYLON) {
  66278. var FollowCamera = /** @class */ (function (_super) {
  66279. __extends(FollowCamera, _super);
  66280. function FollowCamera(name, position, scene, lockedTarget) {
  66281. if (lockedTarget === void 0) { lockedTarget = null; }
  66282. var _this = _super.call(this, name, position, scene) || this;
  66283. _this.radius = 12;
  66284. _this.rotationOffset = 0;
  66285. _this.heightOffset = 4;
  66286. _this.cameraAcceleration = 0.05;
  66287. _this.maxCameraSpeed = 20;
  66288. _this.lockedTarget = lockedTarget;
  66289. return _this;
  66290. }
  66291. FollowCamera.prototype.getRadians = function (degrees) {
  66292. return degrees * Math.PI / 180;
  66293. };
  66294. FollowCamera.prototype.follow = function (cameraTarget) {
  66295. if (!cameraTarget)
  66296. return;
  66297. var yRotation;
  66298. if (cameraTarget.rotationQuaternion) {
  66299. var rotMatrix = new BABYLON.Matrix();
  66300. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66301. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66302. }
  66303. else {
  66304. yRotation = cameraTarget.rotation.y;
  66305. }
  66306. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66307. var targetPosition = cameraTarget.getAbsolutePosition();
  66308. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66309. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66310. var dx = targetX - this.position.x;
  66311. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66312. var dz = (targetZ) - this.position.z;
  66313. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66314. var vy = dy * this.cameraAcceleration;
  66315. var vz = dz * this.cameraAcceleration * 2;
  66316. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66317. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66318. }
  66319. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66320. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66321. }
  66322. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66323. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66324. }
  66325. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66326. this.setTarget(targetPosition);
  66327. };
  66328. FollowCamera.prototype._checkInputs = function () {
  66329. _super.prototype._checkInputs.call(this);
  66330. if (this.lockedTarget) {
  66331. this.follow(this.lockedTarget);
  66332. }
  66333. };
  66334. FollowCamera.prototype.getClassName = function () {
  66335. return "FollowCamera";
  66336. };
  66337. __decorate([
  66338. BABYLON.serialize()
  66339. ], FollowCamera.prototype, "radius", void 0);
  66340. __decorate([
  66341. BABYLON.serialize()
  66342. ], FollowCamera.prototype, "rotationOffset", void 0);
  66343. __decorate([
  66344. BABYLON.serialize()
  66345. ], FollowCamera.prototype, "heightOffset", void 0);
  66346. __decorate([
  66347. BABYLON.serialize()
  66348. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66349. __decorate([
  66350. BABYLON.serialize()
  66351. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66352. __decorate([
  66353. BABYLON.serializeAsMeshReference("lockedTargetId")
  66354. ], FollowCamera.prototype, "lockedTarget", void 0);
  66355. return FollowCamera;
  66356. }(BABYLON.TargetCamera));
  66357. BABYLON.FollowCamera = FollowCamera;
  66358. var ArcFollowCamera = /** @class */ (function (_super) {
  66359. __extends(ArcFollowCamera, _super);
  66360. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66361. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66362. _this.alpha = alpha;
  66363. _this.beta = beta;
  66364. _this.radius = radius;
  66365. _this.target = target;
  66366. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66367. _this.follow();
  66368. return _this;
  66369. }
  66370. ArcFollowCamera.prototype.follow = function () {
  66371. if (!this.target) {
  66372. return;
  66373. }
  66374. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66375. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66376. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66377. var targetPosition = this.target.getAbsolutePosition();
  66378. this.position = targetPosition.add(this._cartesianCoordinates);
  66379. this.setTarget(targetPosition);
  66380. };
  66381. ArcFollowCamera.prototype._checkInputs = function () {
  66382. _super.prototype._checkInputs.call(this);
  66383. this.follow();
  66384. };
  66385. ArcFollowCamera.prototype.getClassName = function () {
  66386. return "ArcFollowCamera";
  66387. };
  66388. return ArcFollowCamera;
  66389. }(BABYLON.TargetCamera));
  66390. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66391. })(BABYLON || (BABYLON = {}));
  66392. //# sourceMappingURL=babylon.followCamera.js.map
  66393. var BABYLON;
  66394. (function (BABYLON) {
  66395. // We're mainly based on the logic defined into the FreeCamera code
  66396. var UniversalCamera = /** @class */ (function (_super) {
  66397. __extends(UniversalCamera, _super);
  66398. //-- end properties for backward compatibility for inputs
  66399. function UniversalCamera(name, position, scene) {
  66400. var _this = _super.call(this, name, position, scene) || this;
  66401. _this.inputs.addGamepad();
  66402. return _this;
  66403. }
  66404. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66405. //-- Begin properties for backward compatibility for inputs
  66406. get: function () {
  66407. var gamepad = this.inputs.attached["gamepad"];
  66408. if (gamepad)
  66409. return gamepad.gamepadAngularSensibility;
  66410. return 0;
  66411. },
  66412. set: function (value) {
  66413. var gamepad = this.inputs.attached["gamepad"];
  66414. if (gamepad)
  66415. gamepad.gamepadAngularSensibility = value;
  66416. },
  66417. enumerable: true,
  66418. configurable: true
  66419. });
  66420. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66421. get: function () {
  66422. var gamepad = this.inputs.attached["gamepad"];
  66423. if (gamepad)
  66424. return gamepad.gamepadMoveSensibility;
  66425. return 0;
  66426. },
  66427. set: function (value) {
  66428. var gamepad = this.inputs.attached["gamepad"];
  66429. if (gamepad)
  66430. gamepad.gamepadMoveSensibility = value;
  66431. },
  66432. enumerable: true,
  66433. configurable: true
  66434. });
  66435. UniversalCamera.prototype.getClassName = function () {
  66436. return "UniversalCamera";
  66437. };
  66438. return UniversalCamera;
  66439. }(BABYLON.TouchCamera));
  66440. BABYLON.UniversalCamera = UniversalCamera;
  66441. })(BABYLON || (BABYLON = {}));
  66442. //# sourceMappingURL=babylon.universalCamera.js.map
  66443. var BABYLON;
  66444. (function (BABYLON) {
  66445. // We're mainly based on the logic defined into the FreeCamera code
  66446. var GamepadCamera = /** @class */ (function (_super) {
  66447. __extends(GamepadCamera, _super);
  66448. //-- end properties for backward compatibility for inputs
  66449. function GamepadCamera(name, position, scene) {
  66450. return _super.call(this, name, position, scene) || this;
  66451. }
  66452. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66453. //-- Begin properties for backward compatibility for inputs
  66454. get: function () {
  66455. var gamepad = this.inputs.attached["gamepad"];
  66456. if (gamepad)
  66457. return gamepad.gamepadAngularSensibility;
  66458. return 0;
  66459. },
  66460. set: function (value) {
  66461. var gamepad = this.inputs.attached["gamepad"];
  66462. if (gamepad)
  66463. gamepad.gamepadAngularSensibility = value;
  66464. },
  66465. enumerable: true,
  66466. configurable: true
  66467. });
  66468. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66469. get: function () {
  66470. var gamepad = this.inputs.attached["gamepad"];
  66471. if (gamepad)
  66472. return gamepad.gamepadMoveSensibility;
  66473. return 0;
  66474. },
  66475. set: function (value) {
  66476. var gamepad = this.inputs.attached["gamepad"];
  66477. if (gamepad)
  66478. gamepad.gamepadMoveSensibility = value;
  66479. },
  66480. enumerable: true,
  66481. configurable: true
  66482. });
  66483. GamepadCamera.prototype.getClassName = function () {
  66484. return "GamepadCamera";
  66485. };
  66486. return GamepadCamera;
  66487. }(BABYLON.UniversalCamera));
  66488. BABYLON.GamepadCamera = GamepadCamera;
  66489. })(BABYLON || (BABYLON = {}));
  66490. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66491. var BABYLON;
  66492. (function (BABYLON) {
  66493. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66494. function PostProcessRenderPipelineManager() {
  66495. this._renderPipelines = {};
  66496. }
  66497. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66498. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66499. };
  66500. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66501. if (unique === void 0) { unique = false; }
  66502. var renderPipeline = this._renderPipelines[renderPipelineName];
  66503. if (!renderPipeline) {
  66504. return;
  66505. }
  66506. renderPipeline._attachCameras(cameras, unique);
  66507. };
  66508. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66509. var renderPipeline = this._renderPipelines[renderPipelineName];
  66510. if (!renderPipeline) {
  66511. return;
  66512. }
  66513. renderPipeline._detachCameras(cameras);
  66514. };
  66515. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66516. var renderPipeline = this._renderPipelines[renderPipelineName];
  66517. if (!renderPipeline) {
  66518. return;
  66519. }
  66520. renderPipeline._enableEffect(renderEffectName, cameras);
  66521. };
  66522. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66523. var renderPipeline = this._renderPipelines[renderPipelineName];
  66524. if (!renderPipeline) {
  66525. return;
  66526. }
  66527. renderPipeline._disableEffect(renderEffectName, cameras);
  66528. };
  66529. PostProcessRenderPipelineManager.prototype.update = function () {
  66530. for (var renderPipelineName in this._renderPipelines) {
  66531. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66532. var pipeline = this._renderPipelines[renderPipelineName];
  66533. if (!pipeline.isSupported) {
  66534. pipeline.dispose();
  66535. delete this._renderPipelines[renderPipelineName];
  66536. }
  66537. else {
  66538. pipeline._update();
  66539. }
  66540. }
  66541. }
  66542. };
  66543. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66544. for (var renderPipelineName in this._renderPipelines) {
  66545. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66546. var pipeline = this._renderPipelines[renderPipelineName];
  66547. pipeline._rebuild();
  66548. }
  66549. }
  66550. };
  66551. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66552. for (var renderPipelineName in this._renderPipelines) {
  66553. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66554. var pipeline = this._renderPipelines[renderPipelineName];
  66555. pipeline.dispose();
  66556. }
  66557. }
  66558. };
  66559. return PostProcessRenderPipelineManager;
  66560. }());
  66561. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66562. })(BABYLON || (BABYLON = {}));
  66563. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. /**
  66567. * This represents a set of one or more post processes in Babylon.
  66568. * A post process can be used to apply a shader to a texture after it is rendered.
  66569. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66570. */
  66571. var PostProcessRenderEffect = /** @class */ (function () {
  66572. /**
  66573. * Instantiates a post process render effect.
  66574. * A post process can be used to apply a shader to a texture after it is rendered.
  66575. * @param engine The engine the effect is tied to
  66576. * @param name The name of the effect
  66577. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66578. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66579. */
  66580. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66581. this._name = name;
  66582. this._singleInstance = singleInstance || true;
  66583. this._getPostProcesses = getPostProcesses;
  66584. this._cameras = {};
  66585. this._indicesForCamera = {};
  66586. this._postProcesses = {};
  66587. }
  66588. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66589. /**
  66590. * Checks if all the post processes in the effect are supported.
  66591. */
  66592. get: function () {
  66593. for (var index in this._postProcesses) {
  66594. for (var ppIndex in this._postProcesses[index]) {
  66595. if (!this._postProcesses[index][ppIndex].isSupported) {
  66596. return false;
  66597. }
  66598. }
  66599. }
  66600. return true;
  66601. },
  66602. enumerable: true,
  66603. configurable: true
  66604. });
  66605. /**
  66606. * Updates the current state of the effect
  66607. */
  66608. PostProcessRenderEffect.prototype._update = function () {
  66609. };
  66610. /**
  66611. * Attaches the effect on cameras
  66612. * @param cameras The camera to attach to.
  66613. */
  66614. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66615. var _this = this;
  66616. var cameraKey;
  66617. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66618. if (!cams) {
  66619. return;
  66620. }
  66621. for (var i = 0; i < cams.length; i++) {
  66622. var camera = cams[i];
  66623. var cameraName = camera.name;
  66624. if (this._singleInstance) {
  66625. cameraKey = 0;
  66626. }
  66627. else {
  66628. cameraKey = cameraName;
  66629. }
  66630. if (!this._postProcesses[cameraKey]) {
  66631. var postProcess = this._getPostProcesses();
  66632. if (postProcess) {
  66633. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66634. }
  66635. }
  66636. if (!this._indicesForCamera[cameraName]) {
  66637. this._indicesForCamera[cameraName] = [];
  66638. }
  66639. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66640. var index = camera.attachPostProcess(postProcess);
  66641. _this._indicesForCamera[cameraName].push(index);
  66642. });
  66643. if (!this._cameras[cameraName]) {
  66644. this._cameras[cameraName] = camera;
  66645. }
  66646. }
  66647. };
  66648. /**
  66649. * Detatches the effect on cameras
  66650. * @param cameras The camera to detatch from.
  66651. */
  66652. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66653. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66654. if (!cams) {
  66655. return;
  66656. }
  66657. for (var i = 0; i < cams.length; i++) {
  66658. var camera = cams[i];
  66659. var cameraName = camera.name;
  66660. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66661. camera.detachPostProcess(postProcess);
  66662. });
  66663. if (this._cameras[cameraName]) {
  66664. //this._indicesForCamera.splice(index, 1);
  66665. this._cameras[cameraName] = null;
  66666. }
  66667. }
  66668. };
  66669. /**
  66670. * Enables the effect on given cameras
  66671. * @param cameras The camera to enable.
  66672. */
  66673. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66674. var _this = this;
  66675. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66676. if (!cams) {
  66677. return;
  66678. }
  66679. for (var i = 0; i < cams.length; i++) {
  66680. var camera = cams[i];
  66681. var cameraName = camera.name;
  66682. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66683. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66684. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66685. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66686. });
  66687. }
  66688. }
  66689. }
  66690. };
  66691. /**
  66692. * Disables the effect on the given cameras
  66693. * @param cameras The camera to disable.
  66694. */
  66695. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66696. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66697. if (!cams) {
  66698. return;
  66699. }
  66700. for (var i = 0; i < cams.length; i++) {
  66701. var camera = cams[i];
  66702. var cameraName = camera.name;
  66703. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66704. camera.detachPostProcess(postProcess);
  66705. });
  66706. }
  66707. };
  66708. /**
  66709. * Gets a list of the post processes contained in the effect.
  66710. * @param camera The camera to get the post processes on.
  66711. * @returns The list of the post processes in the effect.
  66712. */
  66713. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66714. if (this._singleInstance) {
  66715. return this._postProcesses[0];
  66716. }
  66717. else {
  66718. if (!camera) {
  66719. return null;
  66720. }
  66721. return this._postProcesses[camera.name];
  66722. }
  66723. };
  66724. return PostProcessRenderEffect;
  66725. }());
  66726. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66727. })(BABYLON || (BABYLON = {}));
  66728. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66729. var BABYLON;
  66730. (function (BABYLON) {
  66731. var PostProcessRenderPipeline = /** @class */ (function () {
  66732. function PostProcessRenderPipeline(engine, name) {
  66733. this.engine = engine;
  66734. this._name = name;
  66735. this._renderEffects = {};
  66736. this._renderEffectsForIsolatedPass = new Array();
  66737. this._cameras = [];
  66738. }
  66739. PostProcessRenderPipeline.prototype.getClassName = function () {
  66740. return "PostProcessRenderPipeline";
  66741. };
  66742. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66743. get: function () {
  66744. for (var renderEffectName in this._renderEffects) {
  66745. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66746. if (!this._renderEffects[renderEffectName].isSupported) {
  66747. return false;
  66748. }
  66749. }
  66750. }
  66751. return true;
  66752. },
  66753. enumerable: true,
  66754. configurable: true
  66755. });
  66756. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66757. this._renderEffects[renderEffect._name] = renderEffect;
  66758. };
  66759. // private
  66760. PostProcessRenderPipeline.prototype._rebuild = function () {
  66761. };
  66762. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66763. var renderEffects = this._renderEffects[renderEffectName];
  66764. if (!renderEffects) {
  66765. return;
  66766. }
  66767. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66768. };
  66769. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66770. var renderEffects = this._renderEffects[renderEffectName];
  66771. if (!renderEffects) {
  66772. return;
  66773. }
  66774. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66775. };
  66776. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66777. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66778. if (!cams) {
  66779. return;
  66780. }
  66781. var indicesToDelete = [];
  66782. var i;
  66783. for (i = 0; i < cams.length; i++) {
  66784. var camera = cams[i];
  66785. var cameraName = camera.name;
  66786. if (this._cameras.indexOf(camera) === -1) {
  66787. this._cameras[cameraName] = camera;
  66788. }
  66789. else if (unique) {
  66790. indicesToDelete.push(i);
  66791. }
  66792. }
  66793. for (i = 0; i < indicesToDelete.length; i++) {
  66794. cameras.splice(indicesToDelete[i], 1);
  66795. }
  66796. for (var renderEffectName in this._renderEffects) {
  66797. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66798. this._renderEffects[renderEffectName]._attachCameras(cams);
  66799. }
  66800. }
  66801. };
  66802. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66803. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66804. if (!cams) {
  66805. return;
  66806. }
  66807. for (var renderEffectName in this._renderEffects) {
  66808. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66809. this._renderEffects[renderEffectName]._detachCameras(cams);
  66810. }
  66811. }
  66812. for (var i = 0; i < cams.length; i++) {
  66813. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66814. }
  66815. };
  66816. PostProcessRenderPipeline.prototype._update = function () {
  66817. for (var renderEffectName in this._renderEffects) {
  66818. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66819. this._renderEffects[renderEffectName]._update();
  66820. }
  66821. }
  66822. for (var i = 0; i < this._cameras.length; i++) {
  66823. var cameraName = this._cameras[i].name;
  66824. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66825. this._renderEffectsForIsolatedPass[cameraName]._update();
  66826. }
  66827. }
  66828. };
  66829. PostProcessRenderPipeline.prototype._reset = function () {
  66830. this._renderEffects = {};
  66831. this._renderEffectsForIsolatedPass = new Array();
  66832. };
  66833. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66834. // 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)
  66835. var effectKeys = Object.keys(this._renderEffects);
  66836. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66837. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66838. if (postProcesses) {
  66839. postProcesses[0].samples = 4;
  66840. return true;
  66841. }
  66842. }
  66843. return false;
  66844. };
  66845. PostProcessRenderPipeline.prototype.dispose = function () {
  66846. // Must be implemented by children
  66847. };
  66848. __decorate([
  66849. BABYLON.serialize()
  66850. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66851. return PostProcessRenderPipeline;
  66852. }());
  66853. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66854. })(BABYLON || (BABYLON = {}));
  66855. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66856. var BABYLON;
  66857. (function (BABYLON) {
  66858. /**
  66859. * This represents a depth renderer in Babylon.
  66860. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66861. */
  66862. var DepthRenderer = /** @class */ (function () {
  66863. /**
  66864. * Instantiates a depth renderer
  66865. * @param scene The scene the renderer belongs to
  66866. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66867. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66868. */
  66869. function DepthRenderer(scene, type, camera) {
  66870. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66871. if (camera === void 0) { camera = null; }
  66872. var _this = this;
  66873. this._scene = scene;
  66874. this._camera = camera;
  66875. var engine = scene.getEngine();
  66876. // Render target
  66877. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66878. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66879. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66880. this._depthMap.refreshRate = 1;
  66881. this._depthMap.renderParticles = false;
  66882. this._depthMap.renderList = null;
  66883. // Camera to get depth map from to support multiple concurrent cameras
  66884. this._depthMap.activeCamera = this._camera;
  66885. this._depthMap.ignoreCameraViewport = true;
  66886. this._depthMap.useCameraPostProcesses = false;
  66887. // set default depth value to 1.0 (far away)
  66888. this._depthMap.onClearObservable.add(function (engine) {
  66889. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66890. });
  66891. // Custom render function
  66892. var renderSubMesh = function (subMesh) {
  66893. var mesh = subMesh.getRenderingMesh();
  66894. var scene = _this._scene;
  66895. var engine = scene.getEngine();
  66896. var material = subMesh.getMaterial();
  66897. if (!material) {
  66898. return;
  66899. }
  66900. // Culling and reverse (right handed system)
  66901. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66902. // Managing instances
  66903. var batch = mesh._getInstancesRenderList(subMesh._id);
  66904. if (batch.mustReturn) {
  66905. return;
  66906. }
  66907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66908. var camera = _this._camera || scene.activeCamera;
  66909. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66910. engine.enableEffect(_this._effect);
  66911. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66912. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66913. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66914. // Alpha test
  66915. if (material && material.needAlphaTesting()) {
  66916. var alphaTexture = material.getAlphaTestTexture();
  66917. if (alphaTexture) {
  66918. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66919. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66920. }
  66921. }
  66922. // Bones
  66923. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66924. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66925. }
  66926. // Draw
  66927. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66928. }
  66929. };
  66930. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66931. var index;
  66932. if (depthOnlySubMeshes.length) {
  66933. engine.setColorWrite(false);
  66934. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66935. renderSubMesh(depthOnlySubMeshes.data[index]);
  66936. }
  66937. engine.setColorWrite(true);
  66938. }
  66939. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66940. renderSubMesh(opaqueSubMeshes.data[index]);
  66941. }
  66942. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66943. renderSubMesh(alphaTestSubMeshes.data[index]);
  66944. }
  66945. };
  66946. }
  66947. /**
  66948. * Creates the depth rendering effect and checks if the effect is ready.
  66949. * @param subMesh The submesh to be used to render the depth map of
  66950. * @param useInstances If multiple world instances should be used
  66951. * @returns if the depth renderer is ready to render the depth map
  66952. */
  66953. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66954. var material = subMesh.getMaterial();
  66955. if (material.disableDepthWrite) {
  66956. return false;
  66957. }
  66958. var defines = [];
  66959. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66960. var mesh = subMesh.getMesh();
  66961. // Alpha test
  66962. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66963. defines.push("#define ALPHATEST");
  66964. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66965. attribs.push(BABYLON.VertexBuffer.UVKind);
  66966. defines.push("#define UV1");
  66967. }
  66968. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66969. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66970. defines.push("#define UV2");
  66971. }
  66972. }
  66973. // Bones
  66974. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66975. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66976. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66977. if (mesh.numBoneInfluencers > 4) {
  66978. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66979. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66980. }
  66981. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66982. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66983. }
  66984. else {
  66985. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66986. }
  66987. // Instances
  66988. if (useInstances) {
  66989. defines.push("#define INSTANCES");
  66990. attribs.push("world0");
  66991. attribs.push("world1");
  66992. attribs.push("world2");
  66993. attribs.push("world3");
  66994. }
  66995. // Get correct effect
  66996. var join = defines.join("\n");
  66997. if (this._cachedDefines !== join) {
  66998. this._cachedDefines = join;
  66999. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67000. }
  67001. return this._effect.isReady();
  67002. };
  67003. /**
  67004. * Gets the texture which the depth map will be written to.
  67005. * @returns The depth map texture
  67006. */
  67007. DepthRenderer.prototype.getDepthMap = function () {
  67008. return this._depthMap;
  67009. };
  67010. /**
  67011. * Disposes of the depth renderer.
  67012. */
  67013. DepthRenderer.prototype.dispose = function () {
  67014. this._depthMap.dispose();
  67015. };
  67016. return DepthRenderer;
  67017. }());
  67018. BABYLON.DepthRenderer = DepthRenderer;
  67019. })(BABYLON || (BABYLON = {}));
  67020. //# sourceMappingURL=babylon.depthRenderer.js.map
  67021. var BABYLON;
  67022. (function (BABYLON) {
  67023. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67024. __extends(SSAORenderingPipeline, _super);
  67025. /**
  67026. * @constructor
  67027. * @param {string} name - The rendering pipeline name
  67028. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67029. * @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 }
  67030. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67031. */
  67032. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67033. var _this = _super.call(this, scene.getEngine(), name) || this;
  67034. // Members
  67035. /**
  67036. * The PassPostProcess id in the pipeline that contains the original scene color
  67037. * @type {string}
  67038. */
  67039. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67040. /**
  67041. * The SSAO PostProcess id in the pipeline
  67042. * @type {string}
  67043. */
  67044. _this.SSAORenderEffect = "SSAORenderEffect";
  67045. /**
  67046. * The horizontal blur PostProcess id in the pipeline
  67047. * @type {string}
  67048. */
  67049. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67050. /**
  67051. * The vertical blur PostProcess id in the pipeline
  67052. * @type {string}
  67053. */
  67054. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67055. /**
  67056. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67057. * @type {string}
  67058. */
  67059. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67060. /**
  67061. * The output strength of the SSAO post-process. Default value is 1.0.
  67062. * @type {number}
  67063. */
  67064. _this.totalStrength = 1.0;
  67065. /**
  67066. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67067. * @type {number}
  67068. */
  67069. _this.radius = 0.0001;
  67070. /**
  67071. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67072. * Must not be equal to fallOff and superior to fallOff.
  67073. * Default value is 0.975
  67074. * @type {number}
  67075. */
  67076. _this.area = 0.0075;
  67077. /**
  67078. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67079. * Must not be equal to area and inferior to area.
  67080. * Default value is 0.0
  67081. * @type {number}
  67082. */
  67083. _this.fallOff = 0.000001;
  67084. /**
  67085. * The base color of the SSAO post-process
  67086. * The final result is "base + ssao" between [0, 1]
  67087. * @type {number}
  67088. */
  67089. _this.base = 0.5;
  67090. _this._firstUpdate = true;
  67091. _this._scene = scene;
  67092. // Set up assets
  67093. _this._createRandomTexture();
  67094. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67095. var ssaoRatio = ratio.ssaoRatio || ratio;
  67096. var combineRatio = ratio.combineRatio || ratio;
  67097. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67098. _this._createSSAOPostProcess(ssaoRatio);
  67099. _this._createBlurPostProcess(ssaoRatio);
  67100. _this._createSSAOCombinePostProcess(combineRatio);
  67101. // Set up pipeline
  67102. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67103. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67104. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67107. // Finish
  67108. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67109. if (cameras)
  67110. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67111. return _this;
  67112. }
  67113. // Public Methods
  67114. /**
  67115. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67116. */
  67117. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67118. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67119. for (var i = 0; i < this._scene.cameras.length; i++) {
  67120. var camera = this._scene.cameras[i];
  67121. this._originalColorPostProcess.dispose(camera);
  67122. this._ssaoPostProcess.dispose(camera);
  67123. this._blurHPostProcess.dispose(camera);
  67124. this._blurVPostProcess.dispose(camera);
  67125. this._ssaoCombinePostProcess.dispose(camera);
  67126. }
  67127. this._randomTexture.dispose();
  67128. if (disableDepthRender)
  67129. this._scene.disableDepthRenderer();
  67130. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67131. _super.prototype.dispose.call(this);
  67132. };
  67133. // Private Methods
  67134. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67135. var _this = this;
  67136. var size = 16;
  67137. 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);
  67138. 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);
  67139. this._blurHPostProcess.onActivateObservable.add(function () {
  67140. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67141. _this._blurHPostProcess.kernel = size * dw;
  67142. });
  67143. this._blurVPostProcess.onActivateObservable.add(function () {
  67144. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67145. _this._blurVPostProcess.kernel = size * dw;
  67146. });
  67147. };
  67148. SSAORenderingPipeline.prototype._rebuild = function () {
  67149. this._firstUpdate = true;
  67150. _super.prototype._rebuild.call(this);
  67151. };
  67152. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67153. var _this = this;
  67154. var numSamples = 16;
  67155. var sampleSphere = [
  67156. 0.5381, 0.1856, -0.4319,
  67157. 0.1379, 0.2486, 0.4430,
  67158. 0.3371, 0.5679, -0.0057,
  67159. -0.6999, -0.0451, -0.0019,
  67160. 0.0689, -0.1598, -0.8547,
  67161. 0.0560, 0.0069, -0.1843,
  67162. -0.0146, 0.1402, 0.0762,
  67163. 0.0100, -0.1924, -0.0344,
  67164. -0.3577, -0.5301, -0.4358,
  67165. -0.3169, 0.1063, 0.0158,
  67166. 0.0103, -0.5869, 0.0046,
  67167. -0.0897, -0.4940, 0.3287,
  67168. 0.7119, -0.0154, -0.0918,
  67169. -0.0533, 0.0596, -0.5411,
  67170. 0.0352, -0.0631, 0.5460,
  67171. -0.4776, 0.2847, -0.0271
  67172. ];
  67173. var samplesFactor = 1.0 / numSamples;
  67174. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67175. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67176. "area", "fallOff", "base", "range", "viewport"
  67177. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67178. this._ssaoPostProcess.onApply = function (effect) {
  67179. if (_this._firstUpdate) {
  67180. effect.setArray3("sampleSphere", sampleSphere);
  67181. effect.setFloat("samplesFactor", samplesFactor);
  67182. effect.setFloat("randTextureTiles", 4.0);
  67183. }
  67184. effect.setFloat("totalStrength", _this.totalStrength);
  67185. effect.setFloat("radius", _this.radius);
  67186. effect.setFloat("area", _this.area);
  67187. effect.setFloat("fallOff", _this.fallOff);
  67188. effect.setFloat("base", _this.base);
  67189. effect.setTexture("textureSampler", _this._depthTexture);
  67190. effect.setTexture("randomSampler", _this._randomTexture);
  67191. };
  67192. };
  67193. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67194. var _this = this;
  67195. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67196. this._ssaoCombinePostProcess.onApply = function (effect) {
  67197. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67198. };
  67199. };
  67200. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67201. var size = 512;
  67202. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67203. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67204. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67205. var context = this._randomTexture.getContext();
  67206. var rand = function (min, max) {
  67207. return Math.random() * (max - min) + min;
  67208. };
  67209. var randVector = BABYLON.Vector3.Zero();
  67210. for (var x = 0; x < size; x++) {
  67211. for (var y = 0; y < size; y++) {
  67212. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67213. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67214. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67215. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67216. context.fillRect(x, y, 1, 1);
  67217. }
  67218. }
  67219. this._randomTexture.update(false);
  67220. };
  67221. __decorate([
  67222. BABYLON.serialize()
  67223. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67224. __decorate([
  67225. BABYLON.serialize()
  67226. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67227. __decorate([
  67228. BABYLON.serialize()
  67229. ], SSAORenderingPipeline.prototype, "area", void 0);
  67230. __decorate([
  67231. BABYLON.serialize()
  67232. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67233. __decorate([
  67234. BABYLON.serialize()
  67235. ], SSAORenderingPipeline.prototype, "base", void 0);
  67236. return SSAORenderingPipeline;
  67237. }(BABYLON.PostProcessRenderPipeline));
  67238. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67239. })(BABYLON || (BABYLON = {}));
  67240. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67241. var BABYLON;
  67242. (function (BABYLON) {
  67243. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67244. __extends(SSAO2RenderingPipeline, _super);
  67245. /**
  67246. * @constructor
  67247. * @param {string} name - The rendering pipeline name
  67248. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67249. * @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 }
  67250. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67251. */
  67252. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67253. var _this = _super.call(this, scene.getEngine(), name) || this;
  67254. // Members
  67255. /**
  67256. * The PassPostProcess id in the pipeline that contains the original scene color
  67257. * @type {string}
  67258. */
  67259. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67260. /**
  67261. * The SSAO PostProcess id in the pipeline
  67262. * @type {string}
  67263. */
  67264. _this.SSAORenderEffect = "SSAORenderEffect";
  67265. /**
  67266. * The horizontal blur PostProcess id in the pipeline
  67267. * @type {string}
  67268. */
  67269. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67270. /**
  67271. * The vertical blur PostProcess id in the pipeline
  67272. * @type {string}
  67273. */
  67274. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67275. /**
  67276. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67277. * @type {string}
  67278. */
  67279. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67280. /**
  67281. * The output strength of the SSAO post-process. Default value is 1.0.
  67282. * @type {number}
  67283. */
  67284. _this.totalStrength = 1.0;
  67285. /**
  67286. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67287. * @type {number}
  67288. */
  67289. _this.maxZ = 100.0;
  67290. /**
  67291. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67292. * @type {number}
  67293. */
  67294. _this.minZAspect = 0.2;
  67295. /**
  67296. * Number of samples used for the SSAO calculations. Default value is 8
  67297. * @type {number}
  67298. */
  67299. _this._samples = 8;
  67300. /**
  67301. * Are we using bilateral blur ?
  67302. * @type {boolean}
  67303. */
  67304. _this._expensiveBlur = true;
  67305. /**
  67306. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67307. * @type {number}
  67308. */
  67309. _this.radius = 2.0;
  67310. /**
  67311. * The base color of the SSAO post-process
  67312. * The final result is "base + ssao" between [0, 1]
  67313. * @type {number}
  67314. */
  67315. _this.base = 0.1;
  67316. _this._firstUpdate = true;
  67317. _this._scene = scene;
  67318. if (!_this.isSupported) {
  67319. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67320. return _this;
  67321. }
  67322. var ssaoRatio = ratio.ssaoRatio || ratio;
  67323. var blurRatio = ratio.blurRatio || ratio;
  67324. // Set up assets
  67325. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67326. _this._createRandomTexture();
  67327. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67328. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67329. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67330. _this._createSSAOPostProcess(1.0);
  67331. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67332. _this._createSSAOCombinePostProcess(blurRatio);
  67333. // Set up pipeline
  67334. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67335. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67336. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67337. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67338. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67339. // Finish
  67340. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67341. if (cameras)
  67342. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67343. return _this;
  67344. }
  67345. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67346. get: function () {
  67347. return this._samples;
  67348. },
  67349. set: function (n) {
  67350. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67351. this._samples = n;
  67352. this._sampleSphere = this._generateHemisphere();
  67353. this._firstUpdate = true;
  67354. },
  67355. enumerable: true,
  67356. configurable: true
  67357. });
  67358. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67359. get: function () {
  67360. return this._expensiveBlur;
  67361. },
  67362. set: function (b) {
  67363. 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"]);
  67364. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67365. this._expensiveBlur = b;
  67366. this._firstUpdate = true;
  67367. },
  67368. enumerable: true,
  67369. configurable: true
  67370. });
  67371. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67372. /**
  67373. * Support test.
  67374. * @type {boolean}
  67375. */
  67376. get: function () {
  67377. var engine = BABYLON.Engine.LastCreatedEngine;
  67378. if (!engine) {
  67379. return false;
  67380. }
  67381. return engine.getCaps().drawBuffersExtension;
  67382. },
  67383. enumerable: true,
  67384. configurable: true
  67385. });
  67386. // Public Methods
  67387. /**
  67388. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67389. */
  67390. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67391. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67392. for (var i = 0; i < this._scene.cameras.length; i++) {
  67393. var camera = this._scene.cameras[i];
  67394. this._originalColorPostProcess.dispose(camera);
  67395. this._ssaoPostProcess.dispose(camera);
  67396. this._blurHPostProcess.dispose(camera);
  67397. this._blurVPostProcess.dispose(camera);
  67398. this._ssaoCombinePostProcess.dispose(camera);
  67399. }
  67400. this._randomTexture.dispose();
  67401. if (disableGeometryBufferRenderer)
  67402. this._scene.disableGeometryBufferRenderer();
  67403. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67404. _super.prototype.dispose.call(this);
  67405. };
  67406. // Private Methods
  67407. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67408. var _this = this;
  67409. this._samplerOffsets = [];
  67410. var expensive = this.expensiveBlur;
  67411. for (var i = -8; i < 8; i++) {
  67412. this._samplerOffsets.push(i * 2 + 0.5);
  67413. }
  67414. 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");
  67415. this._blurHPostProcess.onApply = function (effect) {
  67416. if (!_this._scene.activeCamera) {
  67417. return;
  67418. }
  67419. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67420. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67421. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67422. effect.setFloat("radius", _this.radius);
  67423. effect.setTexture("depthSampler", _this._depthTexture);
  67424. if (_this._firstUpdate) {
  67425. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67426. }
  67427. };
  67428. 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");
  67429. this._blurVPostProcess.onApply = function (effect) {
  67430. if (!_this._scene.activeCamera) {
  67431. return;
  67432. }
  67433. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67434. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67435. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67436. effect.setFloat("radius", _this.radius);
  67437. effect.setTexture("depthSampler", _this._depthTexture);
  67438. if (_this._firstUpdate) {
  67439. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67440. _this._firstUpdate = false;
  67441. }
  67442. };
  67443. };
  67444. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67445. this._firstUpdate = true;
  67446. _super.prototype._rebuild.call(this);
  67447. };
  67448. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67449. var numSamples = this.samples;
  67450. var result = [];
  67451. var vector, scale;
  67452. var rand = function (min, max) {
  67453. return Math.random() * (max - min) + min;
  67454. };
  67455. var i = 0;
  67456. while (i < numSamples) {
  67457. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67458. vector.normalize();
  67459. scale = i / numSamples;
  67460. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67461. vector.scaleInPlace(scale);
  67462. result.push(vector.x, vector.y, vector.z);
  67463. i++;
  67464. }
  67465. return result;
  67466. };
  67467. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67468. var _this = this;
  67469. var numSamples = this.samples;
  67470. this._sampleSphere = this._generateHemisphere();
  67471. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67472. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67473. "base", "range", "projection", "near", "far", "texelSize",
  67474. "xViewport", "yViewport", "maxZ", "minZAspect"
  67475. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67476. this._ssaoPostProcess.onApply = function (effect) {
  67477. if (_this._firstUpdate) {
  67478. effect.setArray3("sampleSphere", _this._sampleSphere);
  67479. effect.setFloat("randTextureTiles", 4.0);
  67480. }
  67481. if (!_this._scene.activeCamera) {
  67482. return;
  67483. }
  67484. effect.setFloat("samplesFactor", 1 / _this.samples);
  67485. effect.setFloat("totalStrength", _this.totalStrength);
  67486. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67487. effect.setFloat("radius", _this.radius);
  67488. effect.setFloat("maxZ", _this.maxZ);
  67489. effect.setFloat("minZAspect", _this.minZAspect);
  67490. effect.setFloat("base", _this.base);
  67491. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67492. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67493. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67494. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67495. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67496. effect.setTexture("textureSampler", _this._depthTexture);
  67497. effect.setTexture("normalSampler", _this._normalTexture);
  67498. effect.setTexture("randomSampler", _this._randomTexture);
  67499. };
  67500. };
  67501. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67502. var _this = this;
  67503. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67504. this._ssaoCombinePostProcess.onApply = function (effect) {
  67505. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67506. };
  67507. };
  67508. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67509. var size = 512;
  67510. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67511. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67512. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67513. var context = this._randomTexture.getContext();
  67514. var rand = function (min, max) {
  67515. return Math.random() * (max - min) + min;
  67516. };
  67517. var randVector = BABYLON.Vector3.Zero();
  67518. for (var x = 0; x < size; x++) {
  67519. for (var y = 0; y < size; y++) {
  67520. randVector.x = rand(0.0, 1.0);
  67521. randVector.y = rand(0.0, 1.0);
  67522. randVector.z = 0.0;
  67523. randVector.normalize();
  67524. randVector.scaleInPlace(255);
  67525. randVector.x = Math.floor(randVector.x);
  67526. randVector.y = Math.floor(randVector.y);
  67527. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67528. context.fillRect(x, y, 1, 1);
  67529. }
  67530. }
  67531. this._randomTexture.update(false);
  67532. };
  67533. __decorate([
  67534. BABYLON.serialize()
  67535. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67536. __decorate([
  67537. BABYLON.serialize()
  67538. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67539. __decorate([
  67540. BABYLON.serialize()
  67541. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67542. __decorate([
  67543. BABYLON.serialize("samples")
  67544. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67545. __decorate([
  67546. BABYLON.serialize("expensiveBlur")
  67547. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67548. __decorate([
  67549. BABYLON.serialize()
  67550. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67551. __decorate([
  67552. BABYLON.serialize()
  67553. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67554. return SSAO2RenderingPipeline;
  67555. }(BABYLON.PostProcessRenderPipeline));
  67556. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67557. })(BABYLON || (BABYLON = {}));
  67558. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67559. // BABYLON.JS Chromatic Aberration GLSL Shader
  67560. // Author: Olivier Guyot
  67561. // Separates very slightly R, G and B colors on the edges of the screen
  67562. // Inspired by Francois Tarlier & Martins Upitis
  67563. var BABYLON;
  67564. (function (BABYLON) {
  67565. var LensRenderingPipeline = /** @class */ (function (_super) {
  67566. __extends(LensRenderingPipeline, _super);
  67567. /**
  67568. * @constructor
  67569. *
  67570. * Effect parameters are as follow:
  67571. * {
  67572. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67573. * edge_blur: number; // from 0 to x (1 for realism)
  67574. * distortion: number; // from 0 to x (1 for realism)
  67575. * grain_amount: number; // from 0 to 1
  67576. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67577. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67578. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67579. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67580. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67581. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67582. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67583. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67584. * }
  67585. * Note: if an effect parameter is unset, effect is disabled
  67586. *
  67587. * @param {string} name - The rendering pipeline name
  67588. * @param {object} parameters - An object containing all parameters (see above)
  67589. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67590. * @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)
  67591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67592. */
  67593. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67594. if (ratio === void 0) { ratio = 1.0; }
  67595. var _this = _super.call(this, scene.getEngine(), name) || this;
  67596. // Lens effects can be of the following:
  67597. // - chromatic aberration (slight shift of RGB colors)
  67598. // - blur on the edge of the lens
  67599. // - lens distortion
  67600. // - depth-of-field blur & highlights enhancing
  67601. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67602. // - grain effect (noise or custom texture)
  67603. // Two additional texture samplers are needed:
  67604. // - depth map (for depth-of-field)
  67605. // - grain texture
  67606. /**
  67607. * The chromatic aberration PostProcess id in the pipeline
  67608. * @type {string}
  67609. */
  67610. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67611. /**
  67612. * The highlights enhancing PostProcess id in the pipeline
  67613. * @type {string}
  67614. */
  67615. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67616. /**
  67617. * The depth-of-field PostProcess id in the pipeline
  67618. * @type {string}
  67619. */
  67620. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67621. _this._scene = scene;
  67622. // Fetch texture samplers
  67623. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67624. if (parameters.grain_texture) {
  67625. _this._grainTexture = parameters.grain_texture;
  67626. }
  67627. else {
  67628. _this._createGrainTexture();
  67629. }
  67630. // save parameters
  67631. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67632. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67633. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67634. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67635. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67636. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67637. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67638. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67639. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67640. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67641. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67642. // Create effects
  67643. _this._createChromaticAberrationPostProcess(ratio);
  67644. _this._createHighlightsPostProcess(ratio);
  67645. _this._createDepthOfFieldPostProcess(ratio / 4);
  67646. // Set up pipeline
  67647. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67648. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67649. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67650. if (_this._highlightsGain === -1) {
  67651. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67652. }
  67653. // Finish
  67654. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67655. if (cameras) {
  67656. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67657. }
  67658. return _this;
  67659. }
  67660. // public methods (self explanatory)
  67661. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67662. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67663. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67664. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67665. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67666. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67667. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67668. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67669. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67670. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67671. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67672. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67673. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67674. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67675. };
  67676. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67677. this._highlightsPostProcess.updateEffect();
  67678. };
  67679. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67680. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67681. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67682. this._highlightsGain = amount;
  67683. };
  67684. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67685. if (this._highlightsGain === -1) {
  67686. this._highlightsGain = 1.0;
  67687. }
  67688. this._highlightsThreshold = amount;
  67689. };
  67690. LensRenderingPipeline.prototype.disableHighlights = function () {
  67691. this._highlightsGain = -1;
  67692. };
  67693. /**
  67694. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67695. */
  67696. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67697. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67698. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67699. this._chromaticAberrationPostProcess = null;
  67700. this._highlightsPostProcess = null;
  67701. this._depthOfFieldPostProcess = null;
  67702. this._grainTexture.dispose();
  67703. if (disableDepthRender)
  67704. this._scene.disableDepthRenderer();
  67705. };
  67706. // colors shifting and distortion
  67707. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67708. var _this = this;
  67709. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67710. [], // samplers
  67711. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67712. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67713. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67714. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67715. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67716. effect.setFloat('radialIntensity', 1);
  67717. effect.setFloat2('direction', 17, 17);
  67718. effect.setFloat2('centerPosition', 0.5, 0.5);
  67719. };
  67720. };
  67721. // highlights enhancing
  67722. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67723. var _this = this;
  67724. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67725. [], // samplers
  67726. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67727. this._highlightsPostProcess.onApply = function (effect) {
  67728. effect.setFloat('gain', _this._highlightsGain);
  67729. effect.setFloat('threshold', _this._highlightsThreshold);
  67730. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67731. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67732. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67733. };
  67734. };
  67735. // colors shifting and distortion
  67736. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67737. var _this = this;
  67738. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67739. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67740. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67741. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67742. this._depthOfFieldPostProcess.onApply = function (effect) {
  67743. effect.setTexture("depthSampler", _this._depthTexture);
  67744. effect.setTexture("grainSampler", _this._grainTexture);
  67745. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67746. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67747. effect.setFloat('grain_amount', _this._grainAmount);
  67748. effect.setBool('blur_noise', _this._blurNoise);
  67749. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67750. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67751. effect.setFloat('distortion', _this._distortion);
  67752. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67753. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67754. effect.setFloat('aperture', _this._dofAperture);
  67755. effect.setFloat('darken', _this._dofDarken);
  67756. effect.setFloat('edge_blur', _this._edgeBlur);
  67757. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67758. if (_this._scene.activeCamera) {
  67759. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67760. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67761. }
  67762. };
  67763. };
  67764. // creates a black and white random noise texture, 512x512
  67765. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67766. var size = 512;
  67767. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67768. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67769. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67770. var context = this._grainTexture.getContext();
  67771. var rand = function (min, max) {
  67772. return Math.random() * (max - min) + min;
  67773. };
  67774. var value;
  67775. for (var x = 0; x < size; x++) {
  67776. for (var y = 0; y < size; y++) {
  67777. value = Math.floor(rand(0.42, 0.58) * 255);
  67778. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67779. context.fillRect(x, y, 1, 1);
  67780. }
  67781. }
  67782. this._grainTexture.update(false);
  67783. };
  67784. return LensRenderingPipeline;
  67785. }(BABYLON.PostProcessRenderPipeline));
  67786. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67787. })(BABYLON || (BABYLON = {}));
  67788. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67789. var BABYLON;
  67790. (function (BABYLON) {
  67791. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67792. __extends(StandardRenderingPipeline, _super);
  67793. /**
  67794. * @constructor
  67795. * @param {string} name - The rendering pipeline name
  67796. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67797. * @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)
  67798. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67799. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67800. */
  67801. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67802. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67803. var _this = _super.call(this, scene.getEngine(), name) || this;
  67804. _this.downSampleX4PostProcess = null;
  67805. _this.brightPassPostProcess = null;
  67806. _this.blurHPostProcesses = [];
  67807. _this.blurVPostProcesses = [];
  67808. _this.textureAdderPostProcess = null;
  67809. _this.volumetricLightPostProcess = null;
  67810. _this.volumetricLightSmoothXPostProcess = null;
  67811. _this.volumetricLightSmoothYPostProcess = null;
  67812. _this.volumetricLightMergePostProces = null;
  67813. _this.volumetricLightFinalPostProcess = null;
  67814. _this.luminancePostProcess = null;
  67815. _this.luminanceDownSamplePostProcesses = [];
  67816. _this.hdrPostProcess = null;
  67817. _this.textureAdderFinalPostProcess = null;
  67818. _this.lensFlareFinalPostProcess = null;
  67819. _this.hdrFinalPostProcess = null;
  67820. _this.lensFlarePostProcess = null;
  67821. _this.lensFlareComposePostProcess = null;
  67822. _this.motionBlurPostProcess = null;
  67823. _this.depthOfFieldPostProcess = null;
  67824. // Values
  67825. _this.brightThreshold = 1.0;
  67826. _this.blurWidth = 512.0;
  67827. _this.horizontalBlur = false;
  67828. _this.exposure = 1.0;
  67829. _this.lensTexture = null;
  67830. _this.volumetricLightCoefficient = 0.2;
  67831. _this.volumetricLightPower = 4.0;
  67832. _this.volumetricLightBlurScale = 64.0;
  67833. _this.sourceLight = null;
  67834. _this.hdrMinimumLuminance = 1.0;
  67835. _this.hdrDecreaseRate = 0.5;
  67836. _this.hdrIncreaseRate = 0.5;
  67837. _this.lensColorTexture = null;
  67838. _this.lensFlareStrength = 20.0;
  67839. _this.lensFlareGhostDispersal = 1.4;
  67840. _this.lensFlareHaloWidth = 0.7;
  67841. _this.lensFlareDistortionStrength = 16.0;
  67842. _this.lensStarTexture = null;
  67843. _this.lensFlareDirtTexture = null;
  67844. _this.depthOfFieldDistance = 10.0;
  67845. _this.depthOfFieldBlurWidth = 64.0;
  67846. _this.motionStrength = 1.0;
  67847. // IAnimatable
  67848. _this.animations = [];
  67849. _this._currentDepthOfFieldSource = null;
  67850. _this._hdrCurrentLuminance = 1.0;
  67851. // Getters and setters
  67852. _this._bloomEnabled = true;
  67853. _this._depthOfFieldEnabled = false;
  67854. _this._vlsEnabled = false;
  67855. _this._lensFlareEnabled = false;
  67856. _this._hdrEnabled = false;
  67857. _this._motionBlurEnabled = false;
  67858. _this._motionBlurSamples = 64.0;
  67859. _this._volumetricLightStepsCount = 50.0;
  67860. _this._cameras = cameras || [];
  67861. // Initialize
  67862. _this._scene = scene;
  67863. _this._basePostProcess = originalPostProcess;
  67864. _this._ratio = ratio;
  67865. // Misc
  67866. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67867. // Finish
  67868. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67869. _this._buildPipeline();
  67870. return _this;
  67871. }
  67872. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67873. get: function () {
  67874. return this._bloomEnabled;
  67875. },
  67876. set: function (enabled) {
  67877. if (this._bloomEnabled === enabled) {
  67878. return;
  67879. }
  67880. this._bloomEnabled = enabled;
  67881. this._buildPipeline();
  67882. },
  67883. enumerable: true,
  67884. configurable: true
  67885. });
  67886. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67887. get: function () {
  67888. return this._depthOfFieldEnabled;
  67889. },
  67890. set: function (enabled) {
  67891. if (this._depthOfFieldEnabled === enabled) {
  67892. return;
  67893. }
  67894. this._depthOfFieldEnabled = enabled;
  67895. this._buildPipeline();
  67896. },
  67897. enumerable: true,
  67898. configurable: true
  67899. });
  67900. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67901. get: function () {
  67902. return this._lensFlareEnabled;
  67903. },
  67904. set: function (enabled) {
  67905. if (this._lensFlareEnabled === enabled) {
  67906. return;
  67907. }
  67908. this._lensFlareEnabled = enabled;
  67909. this._buildPipeline();
  67910. },
  67911. enumerable: true,
  67912. configurable: true
  67913. });
  67914. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67915. get: function () {
  67916. return this._hdrEnabled;
  67917. },
  67918. set: function (enabled) {
  67919. if (this._hdrEnabled === enabled) {
  67920. return;
  67921. }
  67922. this._hdrEnabled = enabled;
  67923. this._buildPipeline();
  67924. },
  67925. enumerable: true,
  67926. configurable: true
  67927. });
  67928. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67929. get: function () {
  67930. return this._vlsEnabled;
  67931. },
  67932. set: function (enabled) {
  67933. if (this._vlsEnabled === enabled) {
  67934. return;
  67935. }
  67936. if (enabled) {
  67937. var geometry = this._scene.enableGeometryBufferRenderer();
  67938. if (!geometry) {
  67939. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67940. return;
  67941. }
  67942. }
  67943. this._vlsEnabled = enabled;
  67944. this._buildPipeline();
  67945. },
  67946. enumerable: true,
  67947. configurable: true
  67948. });
  67949. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67950. get: function () {
  67951. return this._motionBlurEnabled;
  67952. },
  67953. set: function (enabled) {
  67954. if (this._motionBlurEnabled === enabled) {
  67955. return;
  67956. }
  67957. this._motionBlurEnabled = enabled;
  67958. this._buildPipeline();
  67959. },
  67960. enumerable: true,
  67961. configurable: true
  67962. });
  67963. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67964. get: function () {
  67965. return this._volumetricLightStepsCount;
  67966. },
  67967. set: function (count) {
  67968. if (this.volumetricLightPostProcess) {
  67969. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67970. }
  67971. this._volumetricLightStepsCount = count;
  67972. },
  67973. enumerable: true,
  67974. configurable: true
  67975. });
  67976. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67977. get: function () {
  67978. return this._motionBlurSamples;
  67979. },
  67980. set: function (samples) {
  67981. if (this.motionBlurPostProcess) {
  67982. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67983. }
  67984. this._motionBlurSamples = samples;
  67985. },
  67986. enumerable: true,
  67987. configurable: true
  67988. });
  67989. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67990. var _this = this;
  67991. var ratio = this._ratio;
  67992. var scene = this._scene;
  67993. this._disposePostProcesses();
  67994. this._reset();
  67995. // Create pass post-process
  67996. if (!this._basePostProcess) {
  67997. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67998. this.originalPostProcess.onApply = function (effect) {
  67999. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68000. };
  68001. }
  68002. else {
  68003. this.originalPostProcess = this._basePostProcess;
  68004. }
  68005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68006. this._currentDepthOfFieldSource = this.originalPostProcess;
  68007. if (this._vlsEnabled) {
  68008. // Create volumetric light
  68009. this._createVolumetricLightPostProcess(scene, ratio);
  68010. // Create volumetric light final post-process
  68011. 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);
  68012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68013. }
  68014. if (this._bloomEnabled) {
  68015. // Create down sample X4 post-process
  68016. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68017. // Create bright pass post-process
  68018. this._createBrightPassPostProcess(scene, ratio / 2);
  68019. // Create gaussian blur post-processes (down sampling blurs)
  68020. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68021. // Create texture adder post-process
  68022. this._createTextureAdderPostProcess(scene, ratio);
  68023. // Create depth-of-field source post-process
  68024. 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);
  68025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68026. }
  68027. if (this._lensFlareEnabled) {
  68028. // Create lens flare post-process
  68029. this._createLensFlarePostProcess(scene, ratio);
  68030. // Create depth-of-field source post-process post lens-flare and disable it now
  68031. 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);
  68032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68033. }
  68034. if (this._hdrEnabled) {
  68035. // Create luminance
  68036. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68037. // Create HDR
  68038. this._createHdrPostProcess(scene, ratio);
  68039. // Create depth-of-field source post-process post hdr and disable it now
  68040. 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);
  68041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68042. }
  68043. if (this._depthOfFieldEnabled) {
  68044. // Create gaussian blur used by depth-of-field
  68045. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68046. // Create depth-of-field post-process
  68047. this._createDepthOfFieldPostProcess(scene, ratio);
  68048. }
  68049. if (this._motionBlurEnabled) {
  68050. // Create motion blur post-process
  68051. this._createMotionBlurPostProcess(scene, ratio);
  68052. }
  68053. if (this._cameras !== null) {
  68054. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68055. }
  68056. };
  68057. // Down Sample X4 Post-Processs
  68058. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68059. var _this = this;
  68060. var downSampleX4Offsets = new Array(32);
  68061. 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);
  68062. this.downSampleX4PostProcess.onApply = function (effect) {
  68063. var id = 0;
  68064. var width = _this.downSampleX4PostProcess.width;
  68065. var height = _this.downSampleX4PostProcess.height;
  68066. for (var i = -2; i < 2; i++) {
  68067. for (var j = -2; j < 2; j++) {
  68068. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68069. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68070. id += 2;
  68071. }
  68072. }
  68073. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68074. };
  68075. // Add to pipeline
  68076. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68077. };
  68078. // Brightpass Post-Process
  68079. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68080. var _this = this;
  68081. var brightOffsets = new Array(8);
  68082. 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);
  68083. this.brightPassPostProcess.onApply = function (effect) {
  68084. var sU = (1.0 / _this.brightPassPostProcess.width);
  68085. var sV = (1.0 / _this.brightPassPostProcess.height);
  68086. brightOffsets[0] = -0.5 * sU;
  68087. brightOffsets[1] = 0.5 * sV;
  68088. brightOffsets[2] = 0.5 * sU;
  68089. brightOffsets[3] = 0.5 * sV;
  68090. brightOffsets[4] = -0.5 * sU;
  68091. brightOffsets[5] = -0.5 * sV;
  68092. brightOffsets[6] = 0.5 * sU;
  68093. brightOffsets[7] = -0.5 * sV;
  68094. effect.setArray2("dsOffsets", brightOffsets);
  68095. effect.setFloat("brightThreshold", _this.brightThreshold);
  68096. };
  68097. // Add to pipeline
  68098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68099. };
  68100. // Create blur H&V post-processes
  68101. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68102. var _this = this;
  68103. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68104. var engine = scene.getEngine();
  68105. 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);
  68106. 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);
  68107. blurX.onActivateObservable.add(function () {
  68108. var dw = blurX.width / engine.getRenderWidth();
  68109. blurX.kernel = _this[blurWidthKey] * dw;
  68110. });
  68111. blurY.onActivateObservable.add(function () {
  68112. var dw = blurY.height / engine.getRenderHeight();
  68113. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68114. });
  68115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68117. this.blurHPostProcesses.push(blurX);
  68118. this.blurVPostProcesses.push(blurY);
  68119. };
  68120. // Create texture adder post-process
  68121. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68122. var _this = this;
  68123. 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);
  68124. this.textureAdderPostProcess.onApply = function (effect) {
  68125. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68126. effect.setTexture("lensSampler", _this.lensTexture);
  68127. effect.setFloat("exposure", _this.exposure);
  68128. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68129. };
  68130. // Add to pipeline
  68131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68132. };
  68133. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68134. var _this = this;
  68135. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68136. geometryRenderer.enablePosition = true;
  68137. var geometry = geometryRenderer.getGBuffer();
  68138. // Base post-process
  68139. 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));
  68140. var depthValues = BABYLON.Vector2.Zero();
  68141. this.volumetricLightPostProcess.onApply = function (effect) {
  68142. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68143. var generator = _this.sourceLight.getShadowGenerator();
  68144. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68145. effect.setTexture("positionSampler", geometry.textures[2]);
  68146. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68147. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68148. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68149. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68150. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68151. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68152. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68153. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68154. effect.setVector2("depthValues", depthValues);
  68155. }
  68156. };
  68157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68158. // Smooth
  68159. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68160. // Merge
  68161. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68162. this.volumetricLightMergePostProces.onApply = function (effect) {
  68163. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68164. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68165. };
  68166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68167. };
  68168. // Create luminance
  68169. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68170. var _this = this;
  68171. // Create luminance
  68172. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68173. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68174. var offsets = [];
  68175. this.luminancePostProcess.onApply = function (effect) {
  68176. var sU = (1.0 / _this.luminancePostProcess.width);
  68177. var sV = (1.0 / _this.luminancePostProcess.height);
  68178. offsets[0] = -0.5 * sU;
  68179. offsets[1] = 0.5 * sV;
  68180. offsets[2] = 0.5 * sU;
  68181. offsets[3] = 0.5 * sV;
  68182. offsets[4] = -0.5 * sU;
  68183. offsets[5] = -0.5 * sV;
  68184. offsets[6] = 0.5 * sU;
  68185. offsets[7] = -0.5 * sV;
  68186. effect.setArray2("lumOffsets", offsets);
  68187. };
  68188. // Add to pipeline
  68189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68190. // Create down sample luminance
  68191. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68192. var size = Math.pow(3, i);
  68193. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68194. if (i === 0) {
  68195. defines += "#define FINAL_DOWN_SAMPLER";
  68196. }
  68197. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68198. this.luminanceDownSamplePostProcesses.push(postProcess);
  68199. }
  68200. // Create callbacks and add effects
  68201. var lastLuminance = this.luminancePostProcess;
  68202. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68203. var downSampleOffsets = new Array(18);
  68204. pp.onApply = function (effect) {
  68205. if (!lastLuminance) {
  68206. return;
  68207. }
  68208. var id = 0;
  68209. for (var x = -1; x < 2; x++) {
  68210. for (var y = -1; y < 2; y++) {
  68211. downSampleOffsets[id] = x / lastLuminance.width;
  68212. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68213. id += 2;
  68214. }
  68215. }
  68216. effect.setArray2("dsOffsets", downSampleOffsets);
  68217. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68218. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68219. lastLuminance = _this.luminancePostProcess;
  68220. }
  68221. else {
  68222. lastLuminance = pp;
  68223. }
  68224. };
  68225. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68226. pp.onAfterRender = function (effect) {
  68227. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68228. 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);
  68229. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68230. };
  68231. }
  68232. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68233. });
  68234. };
  68235. // Create HDR post-process
  68236. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68237. var _this = this;
  68238. 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);
  68239. var outputLiminance = 1;
  68240. var time = 0;
  68241. var lastTime = 0;
  68242. this.hdrPostProcess.onApply = function (effect) {
  68243. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68244. time += scene.getEngine().getDeltaTime();
  68245. if (outputLiminance < 0) {
  68246. outputLiminance = _this._hdrCurrentLuminance;
  68247. }
  68248. else {
  68249. var dt = (lastTime - time) / 1000.0;
  68250. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68251. outputLiminance += _this.hdrDecreaseRate * dt;
  68252. }
  68253. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68254. outputLiminance -= _this.hdrIncreaseRate * dt;
  68255. }
  68256. else {
  68257. outputLiminance = _this._hdrCurrentLuminance;
  68258. }
  68259. }
  68260. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68261. effect.setFloat("averageLuminance", outputLiminance);
  68262. lastTime = time;
  68263. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68264. };
  68265. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68266. };
  68267. // Create lens flare post-process
  68268. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68269. var _this = this;
  68270. 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);
  68271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68272. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68273. 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);
  68274. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68275. var resolution = new BABYLON.Vector2(0, 0);
  68276. // Lens flare
  68277. this.lensFlarePostProcess.onApply = function (effect) {
  68278. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68279. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68280. effect.setFloat("strength", _this.lensFlareStrength);
  68281. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68282. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68283. // Shift
  68284. resolution.x = _this.lensFlarePostProcess.width;
  68285. resolution.y = _this.lensFlarePostProcess.height;
  68286. effect.setVector2("resolution", resolution);
  68287. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68288. };
  68289. // Compose
  68290. 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);
  68291. 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);
  68292. this.lensFlareComposePostProcess.onApply = function (effect) {
  68293. if (!_this._scene.activeCamera) {
  68294. return;
  68295. }
  68296. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68297. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68298. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68299. // Lens start rotation matrix
  68300. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68301. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68302. 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));
  68303. camRot *= 4.0;
  68304. 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);
  68305. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68306. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68307. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68308. };
  68309. };
  68310. // Create depth-of-field post-process
  68311. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68312. var _this = this;
  68313. 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);
  68314. this.depthOfFieldPostProcess.onApply = function (effect) {
  68315. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68316. effect.setTexture("depthSampler", _this._getDepthTexture());
  68317. effect.setFloat("distance", _this.depthOfFieldDistance);
  68318. };
  68319. // Add to pipeline
  68320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68321. };
  68322. // Create motion blur post-process
  68323. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68324. var _this = this;
  68325. 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);
  68326. var motionScale = 0;
  68327. var prevViewProjection = BABYLON.Matrix.Identity();
  68328. var invViewProjection = BABYLON.Matrix.Identity();
  68329. var viewProjection = BABYLON.Matrix.Identity();
  68330. var screenSize = BABYLON.Vector2.Zero();
  68331. this.motionBlurPostProcess.onApply = function (effect) {
  68332. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68333. viewProjection.invertToRef(invViewProjection);
  68334. effect.setMatrix("inverseViewProjection", invViewProjection);
  68335. effect.setMatrix("prevViewProjection", prevViewProjection);
  68336. prevViewProjection = viewProjection;
  68337. screenSize.x = _this.motionBlurPostProcess.width;
  68338. screenSize.y = _this.motionBlurPostProcess.height;
  68339. effect.setVector2("screenSize", screenSize);
  68340. motionScale = scene.getEngine().getFps() / 60.0;
  68341. effect.setFloat("motionScale", motionScale);
  68342. effect.setFloat("motionStrength", _this.motionStrength);
  68343. effect.setTexture("depthSampler", _this._getDepthTexture());
  68344. };
  68345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68346. };
  68347. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68348. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68349. var renderer = this._scene.enableGeometryBufferRenderer();
  68350. return renderer.getGBuffer().textures[0];
  68351. }
  68352. return this._scene.enableDepthRenderer().getDepthMap();
  68353. };
  68354. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68355. for (var i = 0; i < this._cameras.length; i++) {
  68356. var camera = this._cameras[i];
  68357. if (this.originalPostProcess) {
  68358. this.originalPostProcess.dispose(camera);
  68359. }
  68360. if (this.downSampleX4PostProcess) {
  68361. this.downSampleX4PostProcess.dispose(camera);
  68362. }
  68363. if (this.brightPassPostProcess) {
  68364. this.brightPassPostProcess.dispose(camera);
  68365. }
  68366. if (this.textureAdderPostProcess) {
  68367. this.textureAdderPostProcess.dispose(camera);
  68368. }
  68369. if (this.textureAdderFinalPostProcess) {
  68370. this.textureAdderFinalPostProcess.dispose(camera);
  68371. }
  68372. if (this.volumetricLightPostProcess) {
  68373. this.volumetricLightPostProcess.dispose(camera);
  68374. }
  68375. if (this.volumetricLightSmoothXPostProcess) {
  68376. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68377. }
  68378. if (this.volumetricLightSmoothYPostProcess) {
  68379. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68380. }
  68381. if (this.volumetricLightMergePostProces) {
  68382. this.volumetricLightMergePostProces.dispose(camera);
  68383. }
  68384. if (this.volumetricLightFinalPostProcess) {
  68385. this.volumetricLightFinalPostProcess.dispose(camera);
  68386. }
  68387. if (this.lensFlarePostProcess) {
  68388. this.lensFlarePostProcess.dispose(camera);
  68389. }
  68390. if (this.lensFlareComposePostProcess) {
  68391. this.lensFlareComposePostProcess.dispose(camera);
  68392. }
  68393. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68394. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68395. }
  68396. if (this.luminancePostProcess) {
  68397. this.luminancePostProcess.dispose(camera);
  68398. }
  68399. if (this.hdrPostProcess) {
  68400. this.hdrPostProcess.dispose(camera);
  68401. }
  68402. if (this.hdrFinalPostProcess) {
  68403. this.hdrFinalPostProcess.dispose(camera);
  68404. }
  68405. if (this.depthOfFieldPostProcess) {
  68406. this.depthOfFieldPostProcess.dispose(camera);
  68407. }
  68408. if (this.motionBlurPostProcess) {
  68409. this.motionBlurPostProcess.dispose(camera);
  68410. }
  68411. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68412. this.blurHPostProcesses[j].dispose(camera);
  68413. }
  68414. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68415. this.blurVPostProcesses[j].dispose(camera);
  68416. }
  68417. }
  68418. this.originalPostProcess = null;
  68419. this.downSampleX4PostProcess = null;
  68420. this.brightPassPostProcess = null;
  68421. this.textureAdderPostProcess = null;
  68422. this.textureAdderFinalPostProcess = null;
  68423. this.volumetricLightPostProcess = null;
  68424. this.volumetricLightSmoothXPostProcess = null;
  68425. this.volumetricLightSmoothYPostProcess = null;
  68426. this.volumetricLightMergePostProces = null;
  68427. this.volumetricLightFinalPostProcess = null;
  68428. this.lensFlarePostProcess = null;
  68429. this.lensFlareComposePostProcess = null;
  68430. this.luminancePostProcess = null;
  68431. this.hdrPostProcess = null;
  68432. this.hdrFinalPostProcess = null;
  68433. this.depthOfFieldPostProcess = null;
  68434. this.motionBlurPostProcess = null;
  68435. this.luminanceDownSamplePostProcesses = [];
  68436. this.blurHPostProcesses = [];
  68437. this.blurVPostProcesses = [];
  68438. };
  68439. // Dispose
  68440. StandardRenderingPipeline.prototype.dispose = function () {
  68441. this._disposePostProcesses();
  68442. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68443. _super.prototype.dispose.call(this);
  68444. };
  68445. // Serialize rendering pipeline
  68446. StandardRenderingPipeline.prototype.serialize = function () {
  68447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68448. serializationObject.customType = "StandardRenderingPipeline";
  68449. return serializationObject;
  68450. };
  68451. /**
  68452. * Static members
  68453. */
  68454. // Parse serialized pipeline
  68455. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68456. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68457. };
  68458. // Luminance steps
  68459. StandardRenderingPipeline.LuminanceSteps = 6;
  68460. __decorate([
  68461. BABYLON.serialize()
  68462. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68463. __decorate([
  68464. BABYLON.serialize()
  68465. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68466. __decorate([
  68467. BABYLON.serialize()
  68468. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68469. __decorate([
  68470. BABYLON.serialize()
  68471. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68472. __decorate([
  68473. BABYLON.serializeAsTexture("lensTexture")
  68474. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68475. __decorate([
  68476. BABYLON.serialize()
  68477. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68478. __decorate([
  68479. BABYLON.serialize()
  68480. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68481. __decorate([
  68482. BABYLON.serialize()
  68483. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68484. __decorate([
  68485. BABYLON.serialize()
  68486. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68487. __decorate([
  68488. BABYLON.serialize()
  68489. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68490. __decorate([
  68491. BABYLON.serialize()
  68492. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68493. __decorate([
  68494. BABYLON.serializeAsTexture("lensColorTexture")
  68495. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68496. __decorate([
  68497. BABYLON.serialize()
  68498. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68499. __decorate([
  68500. BABYLON.serialize()
  68501. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68502. __decorate([
  68503. BABYLON.serialize()
  68504. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68505. __decorate([
  68506. BABYLON.serialize()
  68507. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68508. __decorate([
  68509. BABYLON.serializeAsTexture("lensStarTexture")
  68510. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68511. __decorate([
  68512. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68513. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68514. __decorate([
  68515. BABYLON.serialize()
  68516. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68517. __decorate([
  68518. BABYLON.serialize()
  68519. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68520. __decorate([
  68521. BABYLON.serialize()
  68522. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68523. __decorate([
  68524. BABYLON.serialize()
  68525. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68526. __decorate([
  68527. BABYLON.serialize()
  68528. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68529. __decorate([
  68530. BABYLON.serialize()
  68531. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68532. __decorate([
  68533. BABYLON.serialize()
  68534. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68535. __decorate([
  68536. BABYLON.serialize()
  68537. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68538. __decorate([
  68539. BABYLON.serialize()
  68540. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68541. __decorate([
  68542. BABYLON.serialize()
  68543. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68544. __decorate([
  68545. BABYLON.serialize()
  68546. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68547. __decorate([
  68548. BABYLON.serialize()
  68549. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68550. return StandardRenderingPipeline;
  68551. }(BABYLON.PostProcessRenderPipeline));
  68552. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68553. })(BABYLON || (BABYLON = {}));
  68554. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68555. var BABYLON;
  68556. (function (BABYLON) {
  68557. var FxaaPostProcess = /** @class */ (function (_super) {
  68558. __extends(FxaaPostProcess, _super);
  68559. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68560. if (camera === void 0) { camera = null; }
  68561. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68562. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68563. _this.onApplyObservable.add(function (effect) {
  68564. var texelSize = _this.texelSize;
  68565. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68566. });
  68567. return _this;
  68568. }
  68569. return FxaaPostProcess;
  68570. }(BABYLON.PostProcess));
  68571. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68572. })(BABYLON || (BABYLON = {}));
  68573. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68574. var BABYLON;
  68575. (function (BABYLON) {
  68576. /**
  68577. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68578. */
  68579. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68580. __extends(ChromaticAberrationPostProcess, _super);
  68581. /**
  68582. * Creates a new instance of @see ChromaticAberrationPostProcess
  68583. * @param name The name of the effect.
  68584. * @param screenWidth The width of the screen to apply the effect on.
  68585. * @param screenHeight The height of the screen to apply the effect on.
  68586. * @param options The required width/height ratio to downsize to before computing the render pass.
  68587. * @param camera The camera to apply the render pass to.
  68588. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68589. * @param engine The engine which the post process will be applied. (default: current engine)
  68590. * @param reusable If the post process can be reused on the same frame. (default: false)
  68591. * @param textureType Type of textures used when performing the post process. (default: 0)
  68592. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68593. */
  68594. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68596. if (blockCompilation === void 0) { blockCompilation = false; }
  68597. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68598. /**
  68599. * The amount of seperation of rgb channels (default: 0)
  68600. */
  68601. _this.aberrationAmount = 0;
  68602. /**
  68603. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68604. */
  68605. _this.radialIntensity = 0;
  68606. /**
  68607. * 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))
  68608. */
  68609. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68610. /**
  68611. * 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))
  68612. */
  68613. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68614. _this.onApplyObservable.add(function (effect) {
  68615. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68616. effect.setFloat('screen_width', screenWidth);
  68617. effect.setFloat('screen_height', screenHeight);
  68618. effect.setFloat('radialIntensity', _this.radialIntensity);
  68619. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68620. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68621. });
  68622. return _this;
  68623. }
  68624. return ChromaticAberrationPostProcess;
  68625. }(BABYLON.PostProcess));
  68626. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68627. })(BABYLON || (BABYLON = {}));
  68628. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68629. var BABYLON;
  68630. (function (BABYLON) {
  68631. /**
  68632. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68633. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68634. */
  68635. var SharpenPostProcess = /** @class */ (function (_super) {
  68636. __extends(SharpenPostProcess, _super);
  68637. /**
  68638. * Creates a new instance of @see ConvolutionPostProcess
  68639. * @param name The name of the effect.
  68640. * @param options The required width/height ratio to downsize to before computing the render pass.
  68641. * @param camera The camera to apply the render pass to.
  68642. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68643. * @param engine The engine which the post process will be applied. (default: current engine)
  68644. * @param reusable If the post process can be reused on the same frame. (default: false)
  68645. * @param textureType Type of textures used when performing the post process. (default: 0)
  68646. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68647. */
  68648. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68650. if (blockCompilation === void 0) { blockCompilation = false; }
  68651. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68652. /**
  68653. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68654. */
  68655. _this.colorAmount = 1.0;
  68656. /**
  68657. * How much sharpness should be applied (default: 0.3)
  68658. */
  68659. _this.edgeAmount = 0.3;
  68660. _this.onApply = function (effect) {
  68661. effect.setFloat2("screenSize", _this.width, _this.height);
  68662. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68663. };
  68664. return _this;
  68665. }
  68666. return SharpenPostProcess;
  68667. }(BABYLON.PostProcess));
  68668. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68669. })(BABYLON || (BABYLON = {}));
  68670. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68671. var BABYLON;
  68672. (function (BABYLON) {
  68673. /**
  68674. * The Blur Post Process which blurs an image based on a kernel and direction.
  68675. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68676. */
  68677. var BlurPostProcess = /** @class */ (function (_super) {
  68678. __extends(BlurPostProcess, _super);
  68679. /**
  68680. * Creates a new instance of @see BlurPostProcess
  68681. * @param name The name of the effect.
  68682. * @param direction The direction in which to blur the image.
  68683. * @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.
  68684. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68685. * @param camera The camera to apply the render pass to.
  68686. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68687. * @param engine The engine which the post process will be applied. (default: current engine)
  68688. * @param reusable If the post process can be reused on the same frame. (default: false)
  68689. * @param textureType Type of textures used when performing the post process. (default: 0)
  68690. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68691. */
  68692. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68694. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68695. if (defines === void 0) { defines = ""; }
  68696. if (blockCompilation === void 0) { blockCompilation = false; }
  68697. 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;
  68698. _this.direction = direction;
  68699. _this.blockCompilation = blockCompilation;
  68700. _this._packedFloat = false;
  68701. _this._staticDefines = "";
  68702. _this._staticDefines = defines;
  68703. _this.onApplyObservable.add(function (effect) {
  68704. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68705. });
  68706. _this.kernel = kernel;
  68707. return _this;
  68708. }
  68709. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68710. /**
  68711. * Gets the length in pixels of the blur sample region
  68712. */
  68713. get: function () {
  68714. return this._idealKernel;
  68715. },
  68716. /**
  68717. * Sets the length in pixels of the blur sample region
  68718. */
  68719. set: function (v) {
  68720. if (this._idealKernel === v) {
  68721. return;
  68722. }
  68723. v = Math.max(v, 1);
  68724. this._idealKernel = v;
  68725. this._kernel = this._nearestBestKernel(v);
  68726. if (!this.blockCompilation) {
  68727. this._updateParameters();
  68728. }
  68729. },
  68730. enumerable: true,
  68731. configurable: true
  68732. });
  68733. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68734. /**
  68735. * Gets wether or not the blur is unpacking/repacking floats
  68736. */
  68737. get: function () {
  68738. return this._packedFloat;
  68739. },
  68740. /**
  68741. * Sets wether or not the blur needs to unpack/repack floats
  68742. */
  68743. set: function (v) {
  68744. if (this._packedFloat === v) {
  68745. return;
  68746. }
  68747. this._packedFloat = v;
  68748. if (!this.blockCompilation) {
  68749. this._updateParameters();
  68750. }
  68751. },
  68752. enumerable: true,
  68753. configurable: true
  68754. });
  68755. /**
  68756. * Updates the effect with the current post process compile time values and recompiles the shader.
  68757. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68758. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68759. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68760. * @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
  68761. * @param onCompiled Called when the shader has been compiled.
  68762. * @param onError Called if there is an error when compiling a shader.
  68763. */
  68764. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68765. if (defines === void 0) { defines = null; }
  68766. if (uniforms === void 0) { uniforms = null; }
  68767. if (samplers === void 0) { samplers = null; }
  68768. this._updateParameters(onCompiled, onError);
  68769. };
  68770. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68771. // Generate sampling offsets and weights
  68772. var N = this._kernel;
  68773. var centerIndex = (N - 1) / 2;
  68774. // Generate Gaussian sampling weights over kernel
  68775. var offsets = [];
  68776. var weights = [];
  68777. var totalWeight = 0;
  68778. for (var i = 0; i < N; i++) {
  68779. var u = i / (N - 1);
  68780. var w = this._gaussianWeight(u * 2.0 - 1);
  68781. offsets[i] = (i - centerIndex);
  68782. weights[i] = w;
  68783. totalWeight += w;
  68784. }
  68785. // Normalize weights
  68786. for (var i = 0; i < weights.length; i++) {
  68787. weights[i] /= totalWeight;
  68788. }
  68789. // Optimize: combine samples to take advantage of hardware linear sampling
  68790. // Walk from left to center, combining pairs (symmetrically)
  68791. var linearSamplingWeights = [];
  68792. var linearSamplingOffsets = [];
  68793. var linearSamplingMap = [];
  68794. for (var i = 0; i <= centerIndex; i += 2) {
  68795. var j = Math.min(i + 1, Math.floor(centerIndex));
  68796. var singleCenterSample = i === j;
  68797. if (singleCenterSample) {
  68798. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68799. }
  68800. else {
  68801. var sharedCell = j === centerIndex;
  68802. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68803. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68804. if (offsetLinear === 0) {
  68805. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68806. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68807. }
  68808. else {
  68809. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68810. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68811. }
  68812. }
  68813. }
  68814. for (var i = 0; i < linearSamplingMap.length; i++) {
  68815. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68816. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68817. }
  68818. // Replace with optimized
  68819. offsets = linearSamplingOffsets;
  68820. weights = linearSamplingWeights;
  68821. // Generate shaders
  68822. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68823. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68824. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68825. var defines = "";
  68826. defines += this._staticDefines;
  68827. for (var i = 0; i < varyingCount; i++) {
  68828. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68829. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68830. }
  68831. var depCount = 0;
  68832. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68833. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68834. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68835. depCount++;
  68836. }
  68837. if (this.packedFloat) {
  68838. defines += "#define PACKEDFLOAT 1";
  68839. }
  68840. _super.prototype.updateEffect.call(this, defines, null, null, {
  68841. varyingCount: varyingCount,
  68842. depCount: depCount
  68843. }, onCompiled, onError);
  68844. };
  68845. /**
  68846. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68847. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68848. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68849. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68850. * The gaps between physical kernels are compensated for in the weighting of the samples
  68851. * @param idealKernel Ideal blur kernel.
  68852. * @return Nearest best kernel.
  68853. */
  68854. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68855. var v = Math.round(idealKernel);
  68856. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68857. var k = _a[_i];
  68858. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68859. return Math.max(k, 3);
  68860. }
  68861. }
  68862. return Math.max(v, 3);
  68863. };
  68864. /**
  68865. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68866. * @param x The point on the Gaussian distribution to sample.
  68867. * @return the value of the Gaussian function at x.
  68868. */
  68869. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68870. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68871. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68872. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68873. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68874. // truncated at around 1.3% of peak strength.
  68875. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68876. var sigma = (1 / 3);
  68877. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68878. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68879. var weight = (1.0 / denominator) * Math.exp(exponent);
  68880. return weight;
  68881. };
  68882. /**
  68883. * Generates a string that can be used as a floating point number in GLSL.
  68884. * @param x Value to print.
  68885. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68886. * @return GLSL float string.
  68887. */
  68888. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68889. if (decimalFigures === void 0) { decimalFigures = 8; }
  68890. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68891. };
  68892. return BlurPostProcess;
  68893. }(BABYLON.PostProcess));
  68894. BABYLON.BlurPostProcess = BlurPostProcess;
  68895. })(BABYLON || (BABYLON = {}));
  68896. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68897. var BABYLON;
  68898. (function (BABYLON) {
  68899. /**
  68900. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68901. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68902. * based on samples that have a large difference in distance than the center pixel.
  68903. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68904. */
  68905. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68906. __extends(DepthOfFieldBlurPostProcess, _super);
  68907. /**
  68908. * Creates a new instance of @see CircleOfConfusionPostProcess
  68909. * @param name The name of the effect.
  68910. * @param scene The scene the effect belongs to.
  68911. * @param direction The direction the blur should be applied.
  68912. * @param kernel The size of the kernel used to blur.
  68913. * @param options The required width/height ratio to downsize to before computing the render pass.
  68914. * @param camera The camera to apply the render pass to.
  68915. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68916. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68917. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68918. * @param engine The engine which the post process will be applied. (default: current engine)
  68919. * @param reusable If the post process can be reused on the same frame. (default: false)
  68920. * @param textureType Type of textures used when performing the post process. (default: 0)
  68921. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68922. */
  68923. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68924. if (imageToBlur === void 0) { imageToBlur = null; }
  68925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68926. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68927. if (blockCompilation === void 0) { blockCompilation = false; }
  68928. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  68929. _this.direction = direction;
  68930. _this.onApplyObservable.add(function (effect) {
  68931. if (imageToBlur != null) {
  68932. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68933. }
  68934. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68935. if (scene.activeCamera) {
  68936. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68937. }
  68938. });
  68939. return _this;
  68940. }
  68941. return DepthOfFieldBlurPostProcess;
  68942. }(BABYLON.BlurPostProcess));
  68943. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68944. })(BABYLON || (BABYLON = {}));
  68945. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68946. var BABYLON;
  68947. (function (BABYLON) {
  68948. /**
  68949. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68950. */
  68951. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68952. __extends(DepthOfFieldMergePostProcess, _super);
  68953. /**
  68954. * Creates a new instance of @see CircleOfConfusionPostProcess
  68955. * @param name The name of the effect.
  68956. * @param original The non-blurred image to be modified
  68957. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68958. * @param blurSteps Incrimental bluring post processes.
  68959. * @param options The required width/height ratio to downsize to before computing the render pass.
  68960. * @param camera The camera to apply the render pass to.
  68961. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68962. * @param engine The engine which the post process will be applied. (default: current engine)
  68963. * @param reusable If the post process can be reused on the same frame. (default: false)
  68964. * @param textureType Type of textures used when performing the post process. (default: 0)
  68965. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68966. */
  68967. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68968. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68969. if (blockCompilation === void 0) { blockCompilation = false; }
  68970. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68971. _this.blurSteps = blurSteps;
  68972. _this.onApplyObservable.add(function (effect) {
  68973. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68974. effect.setTextureFromPostProcess("originalSampler", original);
  68975. blurSteps.forEach(function (step, index) {
  68976. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68977. });
  68978. });
  68979. if (!blockCompilation) {
  68980. _this.updateEffect();
  68981. }
  68982. return _this;
  68983. }
  68984. /**
  68985. * Updates the effect with the current post process compile time values and recompiles the shader.
  68986. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68987. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68988. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68989. * @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
  68990. * @param onCompiled Called when the shader has been compiled.
  68991. * @param onError Called if there is an error when compiling a shader.
  68992. */
  68993. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68994. if (defines === void 0) { defines = null; }
  68995. if (uniforms === void 0) { uniforms = null; }
  68996. if (samplers === void 0) { samplers = null; }
  68997. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  68998. };
  68999. return DepthOfFieldMergePostProcess;
  69000. }(BABYLON.PostProcess));
  69001. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69002. })(BABYLON || (BABYLON = {}));
  69003. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69004. var BABYLON;
  69005. (function (BABYLON) {
  69006. /**
  69007. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69008. */
  69009. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69010. __extends(CircleOfConfusionPostProcess, _super);
  69011. /**
  69012. * Creates a new instance of @see CircleOfConfusionPostProcess
  69013. * @param name The name of the effect.
  69014. * @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.
  69015. * @param options The required width/height ratio to downsize to before computing the render pass.
  69016. * @param camera The camera to apply the render pass to.
  69017. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69018. * @param engine The engine which the post process will be applied. (default: current engine)
  69019. * @param reusable If the post process can be reused on the same frame. (default: false)
  69020. * @param textureType Type of textures used when performing the post process. (default: 0)
  69021. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69022. */
  69023. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69024. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69025. if (blockCompilation === void 0) { blockCompilation = false; }
  69026. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69027. /**
  69028. * 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.
  69029. */
  69030. _this.lensSize = 50;
  69031. /**
  69032. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69033. */
  69034. _this.fStop = 1.4;
  69035. /**
  69036. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69037. */
  69038. _this.focusDistance = 2000;
  69039. /**
  69040. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69041. */
  69042. _this.focalLength = 50;
  69043. _this._depthTexture = null;
  69044. _this._depthTexture = depthTexture;
  69045. _this.onApplyObservable.add(function (effect) {
  69046. if (!_this._depthTexture) {
  69047. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69048. return;
  69049. }
  69050. effect.setTexture("depthSampler", _this._depthTexture);
  69051. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69052. var aperture = _this.lensSize / _this.fStop;
  69053. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69054. effect.setFloat('focusDistance', _this.focusDistance);
  69055. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69056. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69057. });
  69058. return _this;
  69059. }
  69060. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69061. /**
  69062. * 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.
  69063. */
  69064. set: function (value) {
  69065. this._depthTexture = value;
  69066. },
  69067. enumerable: true,
  69068. configurable: true
  69069. });
  69070. return CircleOfConfusionPostProcess;
  69071. }(BABYLON.PostProcess));
  69072. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69073. })(BABYLON || (BABYLON = {}));
  69074. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69075. var BABYLON;
  69076. (function (BABYLON) {
  69077. /**
  69078. * Specifies the level of max blur that should be applied when using the depth of field effect
  69079. */
  69080. var DepthOfFieldEffectBlurLevel;
  69081. (function (DepthOfFieldEffectBlurLevel) {
  69082. /**
  69083. * Subtle blur
  69084. */
  69085. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69086. /**
  69087. * Medium blur
  69088. */
  69089. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69090. /**
  69091. * Large blur
  69092. */
  69093. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69094. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69095. ;
  69096. /**
  69097. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69098. */
  69099. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69100. __extends(DepthOfFieldEffect, _super);
  69101. /**
  69102. * Creates a new instance of @see DepthOfFieldEffect
  69103. * @param scene The scene the effect belongs to.
  69104. * @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.
  69105. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69106. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69107. */
  69108. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69109. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69110. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69111. if (blockCompilation === void 0) { blockCompilation = false; }
  69112. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69113. return _this._effects;
  69114. }, true) || this;
  69115. _this._effects = [];
  69116. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69117. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69118. // Capture circle of confusion texture
  69119. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69120. _this._depthOfFieldPass.autoClear = false;
  69121. // 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)
  69122. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69123. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69124. _this._depthOfFieldBlurY = [];
  69125. _this._depthOfFieldBlurX = [];
  69126. var blurCount = 1;
  69127. var kernelSize = 15;
  69128. switch (blurLevel) {
  69129. case DepthOfFieldEffectBlurLevel.High: {
  69130. blurCount = 3;
  69131. kernelSize = 51;
  69132. break;
  69133. }
  69134. case DepthOfFieldEffectBlurLevel.Medium: {
  69135. blurCount = 2;
  69136. kernelSize = 31;
  69137. break;
  69138. }
  69139. default: {
  69140. kernelSize = 15;
  69141. blurCount = 1;
  69142. break;
  69143. }
  69144. }
  69145. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69146. for (var i = 0; i < blurCount; i++) {
  69147. 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, blockCompilation);
  69148. blurY.autoClear = false;
  69149. 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, blockCompilation);
  69150. blurX.autoClear = false;
  69151. _this._depthOfFieldBlurY.push(blurY);
  69152. _this._depthOfFieldBlurX.push(blurX);
  69153. }
  69154. // Merge blurred images with original image based on circleOfConfusion
  69155. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69156. _this._depthOfFieldMerge.autoClear = false;
  69157. // Set all post processes on the effect.
  69158. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69159. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69160. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69161. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69162. }
  69163. _this._effects.push(_this._depthOfFieldMerge);
  69164. return _this;
  69165. }
  69166. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69167. get: function () {
  69168. return this._circleOfConfusion.focalLength;
  69169. },
  69170. /**
  69171. * The focal the length of the camera used in the effect
  69172. */
  69173. set: function (value) {
  69174. this._circleOfConfusion.focalLength = value;
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69180. get: function () {
  69181. return this._circleOfConfusion.fStop;
  69182. },
  69183. /**
  69184. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69185. */
  69186. set: function (value) {
  69187. this._circleOfConfusion.fStop = value;
  69188. },
  69189. enumerable: true,
  69190. configurable: true
  69191. });
  69192. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69193. get: function () {
  69194. return this._circleOfConfusion.focusDistance;
  69195. },
  69196. /**
  69197. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69198. */
  69199. set: function (value) {
  69200. this._circleOfConfusion.focusDistance = value;
  69201. },
  69202. enumerable: true,
  69203. configurable: true
  69204. });
  69205. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69206. get: function () {
  69207. return this._circleOfConfusion.lensSize;
  69208. },
  69209. /**
  69210. * 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.
  69211. */
  69212. set: function (value) {
  69213. this._circleOfConfusion.lensSize = value;
  69214. },
  69215. enumerable: true,
  69216. configurable: true
  69217. });
  69218. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69219. /**
  69220. * 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.
  69221. */
  69222. set: function (value) {
  69223. this._circleOfConfusion.depthTexture = value;
  69224. },
  69225. enumerable: true,
  69226. configurable: true
  69227. });
  69228. /**
  69229. * Disposes each of the internal effects for a given camera.
  69230. * @param camera The camera to dispose the effect on.
  69231. */
  69232. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69233. this._depthOfFieldPass.dispose(camera);
  69234. this._circleOfConfusion.dispose(camera);
  69235. this._depthOfFieldBlurX.forEach(function (element) {
  69236. element.dispose(camera);
  69237. });
  69238. this._depthOfFieldBlurY.forEach(function (element) {
  69239. element.dispose(camera);
  69240. });
  69241. this._depthOfFieldMerge.dispose(camera);
  69242. };
  69243. /**
  69244. * Internal
  69245. */
  69246. DepthOfFieldEffect.prototype._updateEffects = function () {
  69247. for (var effect in this._effects) {
  69248. this._effects[effect].updateEffect();
  69249. }
  69250. };
  69251. /**
  69252. * Internal
  69253. * @returns if all the contained post processes are ready.
  69254. */
  69255. DepthOfFieldEffect.prototype._isReady = function () {
  69256. for (var effect in this._effects) {
  69257. if (!this._effects[effect].isReady()) {
  69258. return false;
  69259. }
  69260. }
  69261. return true;
  69262. };
  69263. return DepthOfFieldEffect;
  69264. }(BABYLON.PostProcessRenderEffect));
  69265. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69266. })(BABYLON || (BABYLON = {}));
  69267. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69268. var BABYLON;
  69269. (function (BABYLON) {
  69270. /**
  69271. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69272. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69273. */
  69274. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69275. __extends(DefaultRenderingPipeline, _super);
  69276. /**
  69277. * @constructor
  69278. * @param {string} name - The rendering pipeline name
  69279. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69280. * @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)
  69281. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69282. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69283. */
  69284. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69285. if (automaticBuild === void 0) { automaticBuild = true; }
  69286. var _this = _super.call(this, scene.getEngine(), name) || this;
  69287. _this._originalCameras = [];
  69288. /**
  69289. * ID of the sharpen post process,
  69290. */
  69291. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69292. /**
  69293. * ID of the pass post process used for bloom,
  69294. */
  69295. _this.PassPostProcessId = "PassPostProcessEffect";
  69296. /**
  69297. * ID of the highlight post process used for bloom,
  69298. */
  69299. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69300. /**
  69301. * ID of the blurX post process used for bloom,
  69302. */
  69303. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69304. /**
  69305. * ID of the blurY post process used for bloom,
  69306. */
  69307. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69308. /**
  69309. * ID of the copy back post process used for bloom,
  69310. */
  69311. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69312. /**
  69313. * ID of the image processing post process;
  69314. */
  69315. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69316. /**
  69317. * ID of the Fast Approximate Anti-Aliasing post process;
  69318. */
  69319. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69320. /**
  69321. * ID of the final merge post process;
  69322. */
  69323. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69324. /**
  69325. * ID of the chromatic aberration post process,
  69326. */
  69327. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69328. /**
  69329. * Animations which can be used to tweak settings over a period of time
  69330. */
  69331. _this.animations = [];
  69332. // Values
  69333. _this._sharpenEnabled = false;
  69334. _this._bloomEnabled = false;
  69335. _this._depthOfFieldEnabled = false;
  69336. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69337. _this._fxaaEnabled = false;
  69338. _this._msaaEnabled = false;
  69339. _this._imageProcessingEnabled = true;
  69340. _this._bloomScale = 0.6;
  69341. _this._chromaticAberrationEnabled = false;
  69342. _this._buildAllowed = true;
  69343. /**
  69344. * Specifies the size of the bloom blur kernel, relative to the final output size
  69345. */
  69346. _this.bloomKernel = 64;
  69347. /**
  69348. * Specifies the weight of the bloom in the final rendering
  69349. */
  69350. _this._bloomWeight = 0.15;
  69351. _this._prevPostProcess = null;
  69352. _this._prevPrevPostProcess = null;
  69353. _this._cameras = cameras || [];
  69354. _this._originalCameras = _this._cameras.slice();
  69355. _this._buildAllowed = automaticBuild;
  69356. // Initialize
  69357. _this._scene = scene;
  69358. var caps = _this._scene.getEngine().getCaps();
  69359. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69360. // Misc
  69361. if (_this._hdr) {
  69362. if (caps.textureHalfFloatRender) {
  69363. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69364. }
  69365. else if (caps.textureFloatRender) {
  69366. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69367. }
  69368. }
  69369. else {
  69370. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69371. }
  69372. // Attach
  69373. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69374. var engine = _this._scene.getEngine();
  69375. // Create post processes before hand so they can be modified before enabled.
  69376. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69377. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69378. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69379. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69380. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69381. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69382. _this._buildPipeline();
  69383. return _this;
  69384. }
  69385. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69386. get: function () {
  69387. return this._sharpenEnabled;
  69388. },
  69389. /**
  69390. * Enable or disable the sharpen process from the pipeline
  69391. */
  69392. set: function (enabled) {
  69393. if (this._sharpenEnabled === enabled) {
  69394. return;
  69395. }
  69396. this._sharpenEnabled = enabled;
  69397. this._buildPipeline();
  69398. },
  69399. enumerable: true,
  69400. configurable: true
  69401. });
  69402. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69403. get: function () {
  69404. return this._bloomWeight;
  69405. },
  69406. /**
  69407. * The strength of the bloom.
  69408. */
  69409. set: function (value) {
  69410. if (this._bloomWeight === value) {
  69411. return;
  69412. }
  69413. this._bloomWeight = value;
  69414. if (this._hdr && this.copyBack) {
  69415. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69416. }
  69417. },
  69418. enumerable: true,
  69419. configurable: true
  69420. });
  69421. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69422. get: function () {
  69423. return this._bloomScale;
  69424. },
  69425. /**
  69426. * The scale of the bloom, lower value will provide better performance.
  69427. */
  69428. set: function (value) {
  69429. if (this._bloomScale === value) {
  69430. return;
  69431. }
  69432. this._bloomScale = value;
  69433. this._buildPipeline();
  69434. },
  69435. enumerable: true,
  69436. configurable: true
  69437. });
  69438. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69439. get: function () {
  69440. return this._bloomEnabled;
  69441. },
  69442. /**
  69443. * Enable or disable the bloom from the pipeline
  69444. */
  69445. set: function (enabled) {
  69446. if (this._bloomEnabled === enabled) {
  69447. return;
  69448. }
  69449. this._bloomEnabled = enabled;
  69450. this._buildPipeline();
  69451. },
  69452. enumerable: true,
  69453. configurable: true
  69454. });
  69455. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69456. /**
  69457. * If the depth of field is enabled.
  69458. */
  69459. get: function () {
  69460. return this._depthOfFieldEnabled;
  69461. },
  69462. set: function (enabled) {
  69463. if (this._depthOfFieldEnabled === enabled) {
  69464. return;
  69465. }
  69466. this._depthOfFieldEnabled = enabled;
  69467. this._buildPipeline();
  69468. },
  69469. enumerable: true,
  69470. configurable: true
  69471. });
  69472. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69473. /**
  69474. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69475. */
  69476. get: function () {
  69477. return this._depthOfFieldBlurLevel;
  69478. },
  69479. set: function (value) {
  69480. if (this._depthOfFieldBlurLevel === value) {
  69481. return;
  69482. }
  69483. this._depthOfFieldBlurLevel = value;
  69484. // recreate dof and dispose old as this setting is not dynamic
  69485. var oldDof = this.depthOfField;
  69486. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69487. this.depthOfField.focalLength = oldDof.focalLength;
  69488. this.depthOfField.focusDistance = oldDof.focusDistance;
  69489. this.depthOfField.fStop = oldDof.fStop;
  69490. this.depthOfField.lensSize = oldDof.lensSize;
  69491. for (var i = 0; i < this._cameras.length; i++) {
  69492. oldDof.disposeEffects(this._cameras[i]);
  69493. }
  69494. this._buildPipeline();
  69495. },
  69496. enumerable: true,
  69497. configurable: true
  69498. });
  69499. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69500. get: function () {
  69501. return this._fxaaEnabled;
  69502. },
  69503. /**
  69504. * If the anti aliasing is enabled.
  69505. */
  69506. set: function (enabled) {
  69507. if (this._fxaaEnabled === enabled) {
  69508. return;
  69509. }
  69510. this._fxaaEnabled = enabled;
  69511. this._buildPipeline();
  69512. },
  69513. enumerable: true,
  69514. configurable: true
  69515. });
  69516. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69517. get: function () {
  69518. return this._msaaEnabled;
  69519. },
  69520. /**
  69521. * If the multisample anti-aliasing is enabled.
  69522. */
  69523. set: function (enabled) {
  69524. if (this._msaaEnabled === enabled) {
  69525. return;
  69526. }
  69527. this._msaaEnabled = enabled;
  69528. this._buildPipeline();
  69529. },
  69530. enumerable: true,
  69531. configurable: true
  69532. });
  69533. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69534. get: function () {
  69535. return this._imageProcessingEnabled;
  69536. },
  69537. /**
  69538. * If image processing is enabled.
  69539. */
  69540. set: function (enabled) {
  69541. if (this._imageProcessingEnabled === enabled) {
  69542. return;
  69543. }
  69544. this._imageProcessingEnabled = enabled;
  69545. this._buildPipeline();
  69546. },
  69547. enumerable: true,
  69548. configurable: true
  69549. });
  69550. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69551. get: function () {
  69552. return this._chromaticAberrationEnabled;
  69553. },
  69554. /**
  69555. * Enable or disable the chromaticAberration process from the pipeline
  69556. */
  69557. set: function (enabled) {
  69558. if (this._chromaticAberrationEnabled === enabled) {
  69559. return;
  69560. }
  69561. this._chromaticAberrationEnabled = enabled;
  69562. this._buildPipeline();
  69563. },
  69564. enumerable: true,
  69565. configurable: true
  69566. });
  69567. /**
  69568. * Force the compilation of the entire pipeline.
  69569. */
  69570. DefaultRenderingPipeline.prototype.prepare = function () {
  69571. var previousState = this._buildAllowed;
  69572. this._buildAllowed = true;
  69573. this._buildPipeline();
  69574. this._buildAllowed = previousState;
  69575. };
  69576. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69577. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69578. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69579. postProcess.autoClear = false;
  69580. }
  69581. else {
  69582. postProcess.autoClear = true;
  69583. }
  69584. if (!skipTextureSharing) {
  69585. if (this._prevPrevPostProcess) {
  69586. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69587. }
  69588. else {
  69589. postProcess.useOwnOutput();
  69590. }
  69591. if (this._prevPostProcess) {
  69592. this._prevPrevPostProcess = this._prevPostProcess;
  69593. }
  69594. this._prevPostProcess = postProcess;
  69595. }
  69596. };
  69597. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69598. var _this = this;
  69599. if (!this._buildAllowed) {
  69600. return;
  69601. }
  69602. var engine = this._scene.getEngine();
  69603. this._disposePostProcesses();
  69604. if (this._cameras !== null) {
  69605. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69606. // get back cameras to be used to reattach pipeline
  69607. this._cameras = this._originalCameras.slice();
  69608. }
  69609. this._reset();
  69610. this._prevPostProcess = null;
  69611. this._prevPrevPostProcess = null;
  69612. if (this.sharpenEnabled) {
  69613. if (!this.sharpen.isReady()) {
  69614. this.sharpen.updateEffect();
  69615. }
  69616. this.addEffect(this._sharpenEffect);
  69617. this._setAutoClearAndTextureSharing(this.sharpen);
  69618. }
  69619. if (this.depthOfFieldEnabled) {
  69620. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69621. this.depthOfField.depthTexture = depthTexture;
  69622. if (!this.depthOfField._isReady()) {
  69623. this.depthOfField._updateEffects();
  69624. }
  69625. this.addEffect(this.depthOfField);
  69626. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69627. }
  69628. if (this.bloomEnabled) {
  69629. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69630. this._setAutoClearAndTextureSharing(this.pass, true);
  69631. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69632. if (!this._hdr) {
  69633. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69634. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69635. this.highlights.autoClear = false;
  69636. this.highlights.alwaysForcePOT = true;
  69637. }
  69638. 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);
  69639. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69640. this.blurX.alwaysForcePOT = true;
  69641. this.blurX.autoClear = false;
  69642. this.blurX.onActivateObservable.add(function () {
  69643. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69644. _this.blurX.kernel = _this.bloomKernel * dw;
  69645. });
  69646. 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);
  69647. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69648. this.blurY.alwaysForcePOT = true;
  69649. this.blurY.autoClear = false;
  69650. this.blurY.onActivateObservable.add(function () {
  69651. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69652. _this.blurY.kernel = _this.bloomKernel * dh;
  69653. });
  69654. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69655. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69656. this.copyBack.alwaysForcePOT = true;
  69657. if (this._hdr) {
  69658. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69659. var w = this.bloomWeight;
  69660. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69661. }
  69662. else {
  69663. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69664. }
  69665. this.copyBack.autoClear = false;
  69666. }
  69667. if (this._imageProcessingEnabled) {
  69668. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69669. if (this._hdr) {
  69670. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69671. }
  69672. else {
  69673. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69674. }
  69675. }
  69676. if (this._hdr && this.imageProcessing) {
  69677. this.finalMerge = this.imageProcessing;
  69678. }
  69679. else {
  69680. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69681. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69682. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69683. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69684. }
  69685. if (this.bloomEnabled) {
  69686. if (this._hdr) {
  69687. this.copyBack.shareOutputWith(this.blurX);
  69688. if (this.imageProcessing) {
  69689. this.imageProcessing.shareOutputWith(this.pass);
  69690. this.imageProcessing.autoClear = false;
  69691. }
  69692. else {
  69693. this.finalMerge.shareOutputWith(this.pass);
  69694. }
  69695. }
  69696. else {
  69697. this.finalMerge.shareOutputWith(this.pass);
  69698. }
  69699. }
  69700. if (this.fxaaEnabled) {
  69701. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69702. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69703. this._setAutoClearAndTextureSharing(this.fxaa);
  69704. }
  69705. if (this.chromaticAberrationEnabled) {
  69706. if (!this.chromaticAberration.isReady()) {
  69707. this.chromaticAberration.updateEffect();
  69708. }
  69709. this.addEffect(this._chromaticAberrationEffect);
  69710. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69711. }
  69712. if (this._cameras !== null) {
  69713. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69714. }
  69715. if (this.msaaEnabled) {
  69716. if (!this._enableMSAAOnFirstPostProcess()) {
  69717. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69718. }
  69719. }
  69720. };
  69721. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69722. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69723. for (var i = 0; i < this._cameras.length; i++) {
  69724. var camera = this._cameras[i];
  69725. if (this.pass) {
  69726. this.pass.dispose(camera);
  69727. }
  69728. if (this.highlights) {
  69729. this.highlights.dispose(camera);
  69730. }
  69731. if (this.blurX) {
  69732. this.blurX.dispose(camera);
  69733. }
  69734. if (this.blurY) {
  69735. this.blurY.dispose(camera);
  69736. }
  69737. if (this.copyBack) {
  69738. this.copyBack.dispose(camera);
  69739. }
  69740. if (this.imageProcessing) {
  69741. this.imageProcessing.dispose(camera);
  69742. }
  69743. if (this.fxaa) {
  69744. this.fxaa.dispose(camera);
  69745. }
  69746. if (this.finalMerge) {
  69747. this.finalMerge.dispose(camera);
  69748. }
  69749. // These are created in the constructor and should not be disposed on every pipeline change
  69750. if (disposeNonRecreated) {
  69751. if (this.sharpen) {
  69752. this.sharpen.dispose(camera);
  69753. }
  69754. if (this.depthOfField) {
  69755. this.depthOfField.disposeEffects(camera);
  69756. }
  69757. if (this.chromaticAberration) {
  69758. this.chromaticAberration.dispose(camera);
  69759. }
  69760. }
  69761. }
  69762. this.pass = null;
  69763. this.highlights = null;
  69764. this.blurX = null;
  69765. this.blurY = null;
  69766. this.copyBack = null;
  69767. this.imageProcessing = null;
  69768. this.fxaa = null;
  69769. this.finalMerge = null;
  69770. if (disposeNonRecreated) {
  69771. this.sharpen = null;
  69772. this.depthOfField = null;
  69773. this.chromaticAberration = null;
  69774. }
  69775. };
  69776. /**
  69777. * Dispose of the pipeline and stop all post processes
  69778. */
  69779. DefaultRenderingPipeline.prototype.dispose = function () {
  69780. this._disposePostProcesses(true);
  69781. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69782. _super.prototype.dispose.call(this);
  69783. };
  69784. /**
  69785. * Serialize the rendering pipeline (Used when exporting)
  69786. * @returns the serialized object
  69787. */
  69788. DefaultRenderingPipeline.prototype.serialize = function () {
  69789. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69790. serializationObject.customType = "DefaultRenderingPipeline";
  69791. return serializationObject;
  69792. };
  69793. /**
  69794. * Parse the serialized pipeline
  69795. * @param source Source pipeline.
  69796. * @param scene The scene to load the pipeline to.
  69797. * @param rootUrl The URL of the serialized pipeline.
  69798. * @returns An instantiated pipeline from the serialized object.
  69799. */
  69800. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69801. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69802. };
  69803. __decorate([
  69804. BABYLON.serialize()
  69805. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69806. __decorate([
  69807. BABYLON.serialize()
  69808. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69809. __decorate([
  69810. BABYLON.serialize()
  69811. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69812. __decorate([
  69813. BABYLON.serialize()
  69814. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69815. __decorate([
  69816. BABYLON.serialize()
  69817. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69818. __decorate([
  69819. BABYLON.serialize()
  69820. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69821. __decorate([
  69822. BABYLON.serialize()
  69823. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69824. __decorate([
  69825. BABYLON.serialize()
  69826. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69827. __decorate([
  69828. BABYLON.serialize()
  69829. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69830. __decorate([
  69831. BABYLON.serialize()
  69832. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69833. __decorate([
  69834. BABYLON.serialize()
  69835. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69836. __decorate([
  69837. BABYLON.serialize()
  69838. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69839. __decorate([
  69840. BABYLON.serialize()
  69841. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69842. return DefaultRenderingPipeline;
  69843. }(BABYLON.PostProcessRenderPipeline));
  69844. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69845. })(BABYLON || (BABYLON = {}));
  69846. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69847. var BABYLON;
  69848. (function (BABYLON) {
  69849. /**
  69850. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69851. */
  69852. var GeometryBufferRenderer = /** @class */ (function () {
  69853. /**
  69854. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69855. * @param scene The scene the buffer belongs to
  69856. * @param ratio How big is the buffer related to the main canvas.
  69857. */
  69858. function GeometryBufferRenderer(scene, ratio) {
  69859. if (ratio === void 0) { ratio = 1; }
  69860. this._enablePosition = false;
  69861. this._scene = scene;
  69862. this._ratio = ratio;
  69863. // Render target
  69864. this._createRenderTargets();
  69865. }
  69866. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69867. /**
  69868. * Set the render list (meshes to be rendered) used in the G buffer.
  69869. */
  69870. set: function (meshes) {
  69871. this._multiRenderTarget.renderList = meshes;
  69872. },
  69873. enumerable: true,
  69874. configurable: true
  69875. });
  69876. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69877. /**
  69878. * Gets wether or not G buffer are supported by the running hardware.
  69879. * This requires draw buffer supports
  69880. */
  69881. get: function () {
  69882. return this._multiRenderTarget.isSupported;
  69883. },
  69884. enumerable: true,
  69885. configurable: true
  69886. });
  69887. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69888. /**
  69889. * Gets wether or not position are enabled for the G buffer.
  69890. */
  69891. get: function () {
  69892. return this._enablePosition;
  69893. },
  69894. /**
  69895. * Sets wether or not position are enabled for the G buffer.
  69896. */
  69897. set: function (enable) {
  69898. this._enablePosition = enable;
  69899. this.dispose();
  69900. this._createRenderTargets();
  69901. },
  69902. enumerable: true,
  69903. configurable: true
  69904. });
  69905. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69906. /**
  69907. * Gets the scene associated with the buffer.
  69908. */
  69909. get: function () {
  69910. return this._scene;
  69911. },
  69912. enumerable: true,
  69913. configurable: true
  69914. });
  69915. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69916. /**
  69917. * Gets the ratio used by the buffer during its creation.
  69918. * How big is the buffer related to the main canvas.
  69919. */
  69920. get: function () {
  69921. return this._ratio;
  69922. },
  69923. enumerable: true,
  69924. configurable: true
  69925. });
  69926. /**
  69927. * Checks wether everything is ready to render a submesh to the G buffer.
  69928. * @param subMesh the submesh to check readiness for
  69929. * @param useInstances is the mesh drawn using instance or not
  69930. * @returns true if ready otherwise false
  69931. */
  69932. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69933. var material = subMesh.getMaterial();
  69934. if (material && material.disableDepthWrite) {
  69935. return false;
  69936. }
  69937. var defines = [];
  69938. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69939. var mesh = subMesh.getMesh();
  69940. // Alpha test
  69941. if (material && material.needAlphaTesting()) {
  69942. defines.push("#define ALPHATEST");
  69943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69944. attribs.push(BABYLON.VertexBuffer.UVKind);
  69945. defines.push("#define UV1");
  69946. }
  69947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69949. defines.push("#define UV2");
  69950. }
  69951. }
  69952. // Buffers
  69953. if (this._enablePosition) {
  69954. defines.push("#define POSITION");
  69955. }
  69956. // Bones
  69957. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69960. if (mesh.numBoneInfluencers > 4) {
  69961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69963. }
  69964. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69965. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69966. }
  69967. else {
  69968. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69969. }
  69970. // Instances
  69971. if (useInstances) {
  69972. defines.push("#define INSTANCES");
  69973. attribs.push("world0");
  69974. attribs.push("world1");
  69975. attribs.push("world2");
  69976. attribs.push("world3");
  69977. }
  69978. // Get correct effect
  69979. var join = defines.join("\n");
  69980. if (this._cachedDefines !== join) {
  69981. this._cachedDefines = join;
  69982. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69983. }
  69984. return this._effect.isReady();
  69985. };
  69986. /**
  69987. * Gets the current underlying G Buffer.
  69988. * @returns the buffer
  69989. */
  69990. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69991. return this._multiRenderTarget;
  69992. };
  69993. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69994. /**
  69995. * Gets the number of samples used to render the buffer (anti aliasing).
  69996. */
  69997. get: function () {
  69998. return this._multiRenderTarget.samples;
  69999. },
  70000. /**
  70001. * Sets the number of samples used to render the buffer (anti aliasing).
  70002. */
  70003. set: function (value) {
  70004. this._multiRenderTarget.samples = value;
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. /**
  70010. * Disposes the renderer and frees up associated resources.
  70011. */
  70012. GeometryBufferRenderer.prototype.dispose = function () {
  70013. this.getGBuffer().dispose();
  70014. };
  70015. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70016. var _this = this;
  70017. var engine = this._scene.getEngine();
  70018. var count = this._enablePosition ? 3 : 2;
  70019. 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 });
  70020. if (!this.isSupported) {
  70021. return;
  70022. }
  70023. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70024. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70025. this._multiRenderTarget.refreshRate = 1;
  70026. this._multiRenderTarget.renderParticles = false;
  70027. this._multiRenderTarget.renderList = null;
  70028. // set default depth value to 1.0 (far away)
  70029. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70030. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70031. });
  70032. // Custom render function
  70033. var renderSubMesh = function (subMesh) {
  70034. var mesh = subMesh.getRenderingMesh();
  70035. var scene = _this._scene;
  70036. var engine = scene.getEngine();
  70037. var material = subMesh.getMaterial();
  70038. if (!material) {
  70039. return;
  70040. }
  70041. // Culling
  70042. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70043. // Managing instances
  70044. var batch = mesh._getInstancesRenderList(subMesh._id);
  70045. if (batch.mustReturn) {
  70046. return;
  70047. }
  70048. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70049. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70050. engine.enableEffect(_this._effect);
  70051. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70052. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70053. _this._effect.setMatrix("view", scene.getViewMatrix());
  70054. // Alpha test
  70055. if (material && material.needAlphaTesting()) {
  70056. var alphaTexture = material.getAlphaTestTexture();
  70057. if (alphaTexture) {
  70058. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70059. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70060. }
  70061. }
  70062. // Bones
  70063. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70064. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70065. }
  70066. // Draw
  70067. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70068. }
  70069. };
  70070. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70071. var index;
  70072. if (depthOnlySubMeshes.length) {
  70073. engine.setColorWrite(false);
  70074. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70075. renderSubMesh(depthOnlySubMeshes.data[index]);
  70076. }
  70077. engine.setColorWrite(true);
  70078. }
  70079. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70080. renderSubMesh(opaqueSubMeshes.data[index]);
  70081. }
  70082. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70083. renderSubMesh(alphaTestSubMeshes.data[index]);
  70084. }
  70085. };
  70086. };
  70087. return GeometryBufferRenderer;
  70088. }());
  70089. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70090. })(BABYLON || (BABYLON = {}));
  70091. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70092. var BABYLON;
  70093. (function (BABYLON) {
  70094. var RefractionPostProcess = /** @class */ (function (_super) {
  70095. __extends(RefractionPostProcess, _super);
  70096. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70097. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70098. _this.color = color;
  70099. _this.depth = depth;
  70100. _this.colorLevel = colorLevel;
  70101. _this._ownRefractionTexture = true;
  70102. _this.onActivateObservable.add(function (cam) {
  70103. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70104. });
  70105. _this.onApplyObservable.add(function (effect) {
  70106. effect.setColor3("baseColor", _this.color);
  70107. effect.setFloat("depth", _this.depth);
  70108. effect.setFloat("colorLevel", _this.colorLevel);
  70109. effect.setTexture("refractionSampler", _this._refTexture);
  70110. });
  70111. return _this;
  70112. }
  70113. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70114. /**
  70115. * Gets or sets the refraction texture
  70116. * Please note that you are responsible for disposing the texture if you set it manually
  70117. */
  70118. get: function () {
  70119. return this._refTexture;
  70120. },
  70121. set: function (value) {
  70122. if (this._refTexture && this._ownRefractionTexture) {
  70123. this._refTexture.dispose();
  70124. }
  70125. this._refTexture = value;
  70126. this._ownRefractionTexture = false;
  70127. },
  70128. enumerable: true,
  70129. configurable: true
  70130. });
  70131. // Methods
  70132. RefractionPostProcess.prototype.dispose = function (camera) {
  70133. if (this._refTexture && this._ownRefractionTexture) {
  70134. this._refTexture.dispose();
  70135. this._refTexture = null;
  70136. }
  70137. _super.prototype.dispose.call(this, camera);
  70138. };
  70139. return RefractionPostProcess;
  70140. }(BABYLON.PostProcess));
  70141. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70142. })(BABYLON || (BABYLON = {}));
  70143. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70144. var BABYLON;
  70145. (function (BABYLON) {
  70146. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70147. __extends(BlackAndWhitePostProcess, _super);
  70148. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70149. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70150. _this.degree = 1;
  70151. _this.onApplyObservable.add(function (effect) {
  70152. effect.setFloat("degree", _this.degree);
  70153. });
  70154. return _this;
  70155. }
  70156. return BlackAndWhitePostProcess;
  70157. }(BABYLON.PostProcess));
  70158. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70159. })(BABYLON || (BABYLON = {}));
  70160. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70161. var BABYLON;
  70162. (function (BABYLON) {
  70163. /**
  70164. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70165. * input texture to perform effects such as edge detection or sharpening
  70166. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70167. */
  70168. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70169. __extends(ConvolutionPostProcess, _super);
  70170. /**
  70171. * Creates a new instance of @see ConvolutionPostProcess
  70172. * @param name The name of the effect.
  70173. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70174. * @param options The required width/height ratio to downsize to before computing the render pass.
  70175. * @param camera The camera to apply the render pass to.
  70176. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70177. * @param engine The engine which the post process will be applied. (default: current engine)
  70178. * @param reusable If the post process can be reused on the same frame. (default: false)
  70179. * @param textureType Type of textures used when performing the post process. (default: 0)
  70180. */
  70181. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70182. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70183. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70184. _this.kernel = kernel;
  70185. _this.onApply = function (effect) {
  70186. effect.setFloat2("screenSize", _this.width, _this.height);
  70187. effect.setArray("kernel", _this.kernel);
  70188. };
  70189. return _this;
  70190. }
  70191. // Statics
  70192. /**
  70193. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70194. */
  70195. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70196. /**
  70197. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70198. */
  70199. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70200. /**
  70201. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70202. */
  70203. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70204. /**
  70205. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70206. */
  70207. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70208. /**
  70209. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70210. */
  70211. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70212. /**
  70213. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70214. */
  70215. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70216. return ConvolutionPostProcess;
  70217. }(BABYLON.PostProcess));
  70218. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70219. })(BABYLON || (BABYLON = {}));
  70220. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70221. var BABYLON;
  70222. (function (BABYLON) {
  70223. var FilterPostProcess = /** @class */ (function (_super) {
  70224. __extends(FilterPostProcess, _super);
  70225. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70226. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70227. _this.kernelMatrix = kernelMatrix;
  70228. _this.onApply = function (effect) {
  70229. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70230. };
  70231. return _this;
  70232. }
  70233. return FilterPostProcess;
  70234. }(BABYLON.PostProcess));
  70235. BABYLON.FilterPostProcess = FilterPostProcess;
  70236. })(BABYLON || (BABYLON = {}));
  70237. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70238. var BABYLON;
  70239. (function (BABYLON) {
  70240. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70241. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70242. __extends(VolumetricLightScatteringPostProcess, _super);
  70243. /**
  70244. * @constructor
  70245. * @param {string} name - The post-process name
  70246. * @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)
  70247. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70248. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70249. * @param {number} samples - The post-process quality, default 100
  70250. * @param {number} samplingMode - The post-process filtering mode
  70251. * @param {BABYLON.Engine} engine - The babylon engine
  70252. * @param {boolean} reusable - If the post-process is reusable
  70253. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70254. */
  70255. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70256. if (samples === void 0) { samples = 100; }
  70257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70258. 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;
  70259. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70260. /**
  70261. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70262. * @type {Vector3}
  70263. */
  70264. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70265. /**
  70266. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70267. * @type {boolean}
  70268. */
  70269. _this.useCustomMeshPosition = false;
  70270. /**
  70271. * If the post-process should inverse the light scattering direction
  70272. * @type {boolean}
  70273. */
  70274. _this.invert = true;
  70275. /**
  70276. * Array containing the excluded meshes not rendered in the internal pass
  70277. */
  70278. _this.excludedMeshes = new Array();
  70279. /**
  70280. * Controls the overall intensity of the post-process
  70281. * @type {number}
  70282. */
  70283. _this.exposure = 0.3;
  70284. /**
  70285. * Dissipates each sample's contribution in range [0, 1]
  70286. * @type {number}
  70287. */
  70288. _this.decay = 0.96815;
  70289. /**
  70290. * Controls the overall intensity of each sample
  70291. * @type {number}
  70292. */
  70293. _this.weight = 0.58767;
  70294. /**
  70295. * Controls the density of each sample
  70296. * @type {number}
  70297. */
  70298. _this.density = 0.926;
  70299. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70300. engine = scene.getEngine();
  70301. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70302. // Configure mesh
  70303. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70304. // Configure
  70305. _this._createPass(scene, ratio.passRatio || ratio);
  70306. _this.onActivate = function (camera) {
  70307. if (!_this.isSupported) {
  70308. _this.dispose(camera);
  70309. }
  70310. _this.onActivate = null;
  70311. };
  70312. _this.onApplyObservable.add(function (effect) {
  70313. _this._updateMeshScreenCoordinates(scene);
  70314. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70315. effect.setFloat("exposure", _this.exposure);
  70316. effect.setFloat("decay", _this.decay);
  70317. effect.setFloat("weight", _this.weight);
  70318. effect.setFloat("density", _this.density);
  70319. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70320. });
  70321. return _this;
  70322. }
  70323. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70324. get: function () {
  70325. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70326. return false;
  70327. },
  70328. set: function (useDiffuseColor) {
  70329. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70330. },
  70331. enumerable: true,
  70332. configurable: true
  70333. });
  70334. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70335. return "VolumetricLightScatteringPostProcess";
  70336. };
  70337. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70338. var mesh = subMesh.getMesh();
  70339. // Render this.mesh as default
  70340. if (mesh === this.mesh && mesh.material) {
  70341. return mesh.material.isReady(mesh);
  70342. }
  70343. var defines = [];
  70344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70345. var material = subMesh.getMaterial();
  70346. // Alpha test
  70347. if (material) {
  70348. if (material.needAlphaTesting()) {
  70349. defines.push("#define ALPHATEST");
  70350. }
  70351. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70352. attribs.push(BABYLON.VertexBuffer.UVKind);
  70353. defines.push("#define UV1");
  70354. }
  70355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70356. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70357. defines.push("#define UV2");
  70358. }
  70359. }
  70360. // Bones
  70361. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70364. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70365. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70366. }
  70367. else {
  70368. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70369. }
  70370. // Instances
  70371. if (useInstances) {
  70372. defines.push("#define INSTANCES");
  70373. attribs.push("world0");
  70374. attribs.push("world1");
  70375. attribs.push("world2");
  70376. attribs.push("world3");
  70377. }
  70378. // Get correct effect
  70379. var join = defines.join("\n");
  70380. if (this._cachedDefines !== join) {
  70381. this._cachedDefines = join;
  70382. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70383. }
  70384. return this._volumetricLightScatteringPass.isReady();
  70385. };
  70386. /**
  70387. * Sets the new light position for light scattering effect
  70388. * @param {BABYLON.Vector3} The new custom light position
  70389. */
  70390. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70391. this.customMeshPosition = position;
  70392. };
  70393. /**
  70394. * Returns the light position for light scattering effect
  70395. * @return {BABYLON.Vector3} The custom light position
  70396. */
  70397. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70398. return this.customMeshPosition;
  70399. };
  70400. /**
  70401. * Disposes the internal assets and detaches the post-process from the camera
  70402. */
  70403. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70404. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70405. if (rttIndex !== -1) {
  70406. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70407. }
  70408. this._volumetricLightScatteringRTT.dispose();
  70409. _super.prototype.dispose.call(this, camera);
  70410. };
  70411. /**
  70412. * Returns the render target texture used by the post-process
  70413. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70414. */
  70415. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70416. return this._volumetricLightScatteringRTT;
  70417. };
  70418. // Private methods
  70419. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70420. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70421. return true;
  70422. }
  70423. return false;
  70424. };
  70425. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70426. var _this = this;
  70427. var engine = scene.getEngine();
  70428. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70429. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70430. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70431. this._volumetricLightScatteringRTT.renderList = null;
  70432. this._volumetricLightScatteringRTT.renderParticles = false;
  70433. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70434. var camera = this.getCamera();
  70435. if (camera) {
  70436. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70437. }
  70438. else {
  70439. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70440. }
  70441. // Custom render function for submeshes
  70442. var renderSubMesh = function (subMesh) {
  70443. var mesh = subMesh.getRenderingMesh();
  70444. if (_this._meshExcluded(mesh)) {
  70445. return;
  70446. }
  70447. var material = subMesh.getMaterial();
  70448. if (!material) {
  70449. return;
  70450. }
  70451. var scene = mesh.getScene();
  70452. var engine = scene.getEngine();
  70453. // Culling
  70454. engine.setState(material.backFaceCulling);
  70455. // Managing instances
  70456. var batch = mesh._getInstancesRenderList(subMesh._id);
  70457. if (batch.mustReturn) {
  70458. return;
  70459. }
  70460. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70461. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70462. var effect = _this._volumetricLightScatteringPass;
  70463. if (mesh === _this.mesh) {
  70464. if (subMesh.effect) {
  70465. effect = subMesh.effect;
  70466. }
  70467. else {
  70468. effect = material.getEffect();
  70469. }
  70470. }
  70471. engine.enableEffect(effect);
  70472. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70473. if (mesh === _this.mesh) {
  70474. material.bind(mesh.getWorldMatrix(), mesh);
  70475. }
  70476. else {
  70477. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70478. // Alpha test
  70479. if (material && material.needAlphaTesting()) {
  70480. var alphaTexture = material.getAlphaTestTexture();
  70481. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70482. if (alphaTexture) {
  70483. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70484. }
  70485. }
  70486. // Bones
  70487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70488. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70489. }
  70490. }
  70491. // Draw
  70492. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70493. }
  70494. };
  70495. // Render target texture callbacks
  70496. var savedSceneClearColor;
  70497. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70498. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70499. savedSceneClearColor = scene.clearColor;
  70500. scene.clearColor = sceneClearColor;
  70501. });
  70502. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70503. scene.clearColor = savedSceneClearColor;
  70504. });
  70505. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70506. var engine = scene.getEngine();
  70507. var index;
  70508. if (depthOnlySubMeshes.length) {
  70509. engine.setColorWrite(false);
  70510. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70511. renderSubMesh(depthOnlySubMeshes.data[index]);
  70512. }
  70513. engine.setColorWrite(true);
  70514. }
  70515. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70516. renderSubMesh(opaqueSubMeshes.data[index]);
  70517. }
  70518. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70519. renderSubMesh(alphaTestSubMeshes.data[index]);
  70520. }
  70521. if (transparentSubMeshes.length) {
  70522. // Sort sub meshes
  70523. for (index = 0; index < transparentSubMeshes.length; index++) {
  70524. var submesh = transparentSubMeshes.data[index];
  70525. var boundingInfo = submesh.getBoundingInfo();
  70526. if (boundingInfo && scene.activeCamera) {
  70527. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70528. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70529. }
  70530. }
  70531. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70532. sortedArray.sort(function (a, b) {
  70533. // Alpha index first
  70534. if (a._alphaIndex > b._alphaIndex) {
  70535. return 1;
  70536. }
  70537. if (a._alphaIndex < b._alphaIndex) {
  70538. return -1;
  70539. }
  70540. // Then distance to camera
  70541. if (a._distanceToCamera < b._distanceToCamera) {
  70542. return 1;
  70543. }
  70544. if (a._distanceToCamera > b._distanceToCamera) {
  70545. return -1;
  70546. }
  70547. return 0;
  70548. });
  70549. // Render sub meshes
  70550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70551. for (index = 0; index < sortedArray.length; index++) {
  70552. renderSubMesh(sortedArray[index]);
  70553. }
  70554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70555. }
  70556. };
  70557. };
  70558. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70559. var transform = scene.getTransformMatrix();
  70560. var meshPosition;
  70561. if (this.useCustomMeshPosition) {
  70562. meshPosition = this.customMeshPosition;
  70563. }
  70564. else if (this.attachedNode) {
  70565. meshPosition = this.attachedNode.position;
  70566. }
  70567. else {
  70568. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70569. }
  70570. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70571. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70572. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70573. if (this.invert)
  70574. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70575. };
  70576. // Static methods
  70577. /**
  70578. * Creates a default mesh for the Volumeric Light Scattering post-process
  70579. * @param {string} The mesh name
  70580. * @param {BABYLON.Scene} The scene where to create the mesh
  70581. * @return {BABYLON.Mesh} the default mesh
  70582. */
  70583. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70584. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70585. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70586. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70587. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70588. mesh.material = material;
  70589. return mesh;
  70590. };
  70591. __decorate([
  70592. BABYLON.serializeAsVector3()
  70593. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70594. __decorate([
  70595. BABYLON.serialize()
  70596. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70597. __decorate([
  70598. BABYLON.serialize()
  70599. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70600. __decorate([
  70601. BABYLON.serializeAsMeshReference()
  70602. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70603. __decorate([
  70604. BABYLON.serialize()
  70605. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70606. __decorate([
  70607. BABYLON.serialize()
  70608. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70609. __decorate([
  70610. BABYLON.serialize()
  70611. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70612. __decorate([
  70613. BABYLON.serialize()
  70614. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70615. __decorate([
  70616. BABYLON.serialize()
  70617. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70618. return VolumetricLightScatteringPostProcess;
  70619. }(BABYLON.PostProcess));
  70620. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70621. })(BABYLON || (BABYLON = {}));
  70622. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70623. //
  70624. // This post-process allows the modification of rendered colors by using
  70625. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70626. //
  70627. // The object needs to be provided an url to a texture containing the color
  70628. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70629. // Use an image editing software to tweak the LUT to match your needs.
  70630. //
  70631. // For an example of a color LUT, see here:
  70632. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70633. // For explanations on color grading, see here:
  70634. // http://udn.epicgames.com/Three/ColorGrading.html
  70635. //
  70636. var BABYLON;
  70637. (function (BABYLON) {
  70638. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70639. __extends(ColorCorrectionPostProcess, _super);
  70640. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70641. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70642. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70643. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70644. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70645. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70646. _this.onApply = function (effect) {
  70647. effect.setTexture("colorTable", _this._colorTableTexture);
  70648. };
  70649. return _this;
  70650. }
  70651. return ColorCorrectionPostProcess;
  70652. }(BABYLON.PostProcess));
  70653. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70654. })(BABYLON || (BABYLON = {}));
  70655. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70656. var BABYLON;
  70657. (function (BABYLON) {
  70658. var TonemappingOperator;
  70659. (function (TonemappingOperator) {
  70660. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70661. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70662. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70663. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70664. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70665. ;
  70666. var TonemapPostProcess = /** @class */ (function (_super) {
  70667. __extends(TonemapPostProcess, _super);
  70668. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70670. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70671. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70672. _this._operator = _operator;
  70673. _this.exposureAdjustment = exposureAdjustment;
  70674. var defines = "#define ";
  70675. if (_this._operator === TonemappingOperator.Hable)
  70676. defines += "HABLE_TONEMAPPING";
  70677. else if (_this._operator === TonemappingOperator.Reinhard)
  70678. defines += "REINHARD_TONEMAPPING";
  70679. else if (_this._operator === TonemappingOperator.HejiDawson)
  70680. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70681. else if (_this._operator === TonemappingOperator.Photographic)
  70682. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70683. //sadly a second call to create the effect.
  70684. _this.updateEffect(defines);
  70685. _this.onApply = function (effect) {
  70686. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70687. };
  70688. return _this;
  70689. }
  70690. return TonemapPostProcess;
  70691. }(BABYLON.PostProcess));
  70692. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70693. })(BABYLON || (BABYLON = {}));
  70694. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70695. var BABYLON;
  70696. (function (BABYLON) {
  70697. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70698. __extends(DisplayPassPostProcess, _super);
  70699. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70700. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70701. }
  70702. return DisplayPassPostProcess;
  70703. }(BABYLON.PostProcess));
  70704. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70705. })(BABYLON || (BABYLON = {}));
  70706. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70707. var BABYLON;
  70708. (function (BABYLON) {
  70709. var HighlightsPostProcess = /** @class */ (function (_super) {
  70710. __extends(HighlightsPostProcess, _super);
  70711. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70712. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70713. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70714. }
  70715. return HighlightsPostProcess;
  70716. }(BABYLON.PostProcess));
  70717. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70718. })(BABYLON || (BABYLON = {}));
  70719. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70720. var BABYLON;
  70721. (function (BABYLON) {
  70722. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70723. __extends(ImageProcessingPostProcess, _super);
  70724. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70725. if (camera === void 0) { camera = null; }
  70726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70727. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70728. _this._fromLinearSpace = true;
  70729. /**
  70730. * Defines cache preventing GC.
  70731. */
  70732. _this._defines = {
  70733. IMAGEPROCESSING: false,
  70734. VIGNETTE: false,
  70735. VIGNETTEBLENDMODEMULTIPLY: false,
  70736. VIGNETTEBLENDMODEOPAQUE: false,
  70737. TONEMAPPING: false,
  70738. CONTRAST: false,
  70739. COLORCURVES: false,
  70740. COLORGRADING: false,
  70741. COLORGRADING3D: false,
  70742. FROMLINEARSPACE: false,
  70743. SAMPLER3DGREENDEPTH: false,
  70744. SAMPLER3DBGRMAP: false,
  70745. IMAGEPROCESSINGPOSTPROCESS: false,
  70746. EXPOSURE: false,
  70747. GRAIN: false,
  70748. };
  70749. // Setup the configuration as forced by the constructor. This would then not force the
  70750. // scene materials output in linear space and let untouched the default forward pass.
  70751. if (imageProcessingConfiguration) {
  70752. imageProcessingConfiguration.applyByPostProcess = true;
  70753. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70754. // This will cause the shader to be compiled
  70755. _this.fromLinearSpace = false;
  70756. }
  70757. else {
  70758. _this._attachImageProcessingConfiguration(null, true);
  70759. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70760. }
  70761. _this.onApply = function (effect) {
  70762. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70763. };
  70764. return _this;
  70765. }
  70766. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70767. /**
  70768. * Gets the image processing configuration used either in this material.
  70769. */
  70770. get: function () {
  70771. return this._imageProcessingConfiguration;
  70772. },
  70773. /**
  70774. * Sets the Default image processing configuration used either in the this material.
  70775. *
  70776. * If sets to null, the scene one is in use.
  70777. */
  70778. set: function (value) {
  70779. this._attachImageProcessingConfiguration(value);
  70780. },
  70781. enumerable: true,
  70782. configurable: true
  70783. });
  70784. /**
  70785. * Attaches a new image processing configuration to the PBR Material.
  70786. * @param configuration
  70787. */
  70788. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70789. var _this = this;
  70790. if (doNotBuild === void 0) { doNotBuild = false; }
  70791. if (configuration === this._imageProcessingConfiguration) {
  70792. return;
  70793. }
  70794. // Detaches observer.
  70795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70797. }
  70798. // Pick the scene configuration if needed.
  70799. if (!configuration) {
  70800. var scene = null;
  70801. var engine = this.getEngine();
  70802. var camera = this.getCamera();
  70803. if (camera) {
  70804. scene = camera.getScene();
  70805. }
  70806. else if (engine && engine.scenes) {
  70807. var scenes = engine.scenes;
  70808. scene = scenes[scenes.length - 1];
  70809. }
  70810. else {
  70811. scene = BABYLON.Engine.LastCreatedScene;
  70812. }
  70813. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70814. }
  70815. else {
  70816. this._imageProcessingConfiguration = configuration;
  70817. }
  70818. // Attaches observer.
  70819. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70820. _this._updateParameters();
  70821. });
  70822. // Ensure the effect will be rebuilt.
  70823. if (!doNotBuild) {
  70824. this._updateParameters();
  70825. }
  70826. };
  70827. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70828. /**
  70829. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70830. */
  70831. get: function () {
  70832. return this.imageProcessingConfiguration.colorCurves;
  70833. },
  70834. /**
  70835. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70836. */
  70837. set: function (value) {
  70838. this.imageProcessingConfiguration.colorCurves = value;
  70839. },
  70840. enumerable: true,
  70841. configurable: true
  70842. });
  70843. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70844. /**
  70845. * Gets wether the color curves effect is enabled.
  70846. */
  70847. get: function () {
  70848. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70849. },
  70850. /**
  70851. * Sets wether the color curves effect is enabled.
  70852. */
  70853. set: function (value) {
  70854. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70855. },
  70856. enumerable: true,
  70857. configurable: true
  70858. });
  70859. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70860. /**
  70861. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70862. */
  70863. get: function () {
  70864. return this.imageProcessingConfiguration.colorGradingTexture;
  70865. },
  70866. /**
  70867. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70868. */
  70869. set: function (value) {
  70870. this.imageProcessingConfiguration.colorGradingTexture = value;
  70871. },
  70872. enumerable: true,
  70873. configurable: true
  70874. });
  70875. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70876. /**
  70877. * Gets wether the color grading effect is enabled.
  70878. */
  70879. get: function () {
  70880. return this.imageProcessingConfiguration.colorGradingEnabled;
  70881. },
  70882. /**
  70883. * Gets wether the color grading effect is enabled.
  70884. */
  70885. set: function (value) {
  70886. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70887. },
  70888. enumerable: true,
  70889. configurable: true
  70890. });
  70891. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70892. /**
  70893. * Gets exposure used in the effect.
  70894. */
  70895. get: function () {
  70896. return this.imageProcessingConfiguration.exposure;
  70897. },
  70898. /**
  70899. * Sets exposure used in the effect.
  70900. */
  70901. set: function (value) {
  70902. this.imageProcessingConfiguration.exposure = value;
  70903. },
  70904. enumerable: true,
  70905. configurable: true
  70906. });
  70907. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70908. /**
  70909. * Gets wether tonemapping is enabled or not.
  70910. */
  70911. get: function () {
  70912. return this._imageProcessingConfiguration.toneMappingEnabled;
  70913. },
  70914. /**
  70915. * Sets wether tonemapping is enabled or not
  70916. */
  70917. set: function (value) {
  70918. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70919. },
  70920. enumerable: true,
  70921. configurable: true
  70922. });
  70923. ;
  70924. ;
  70925. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70926. /**
  70927. * Gets contrast used in the effect.
  70928. */
  70929. get: function () {
  70930. return this.imageProcessingConfiguration.contrast;
  70931. },
  70932. /**
  70933. * Sets contrast used in the effect.
  70934. */
  70935. set: function (value) {
  70936. this.imageProcessingConfiguration.contrast = value;
  70937. },
  70938. enumerable: true,
  70939. configurable: true
  70940. });
  70941. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70942. /**
  70943. * Gets Vignette stretch size.
  70944. */
  70945. get: function () {
  70946. return this.imageProcessingConfiguration.vignetteStretch;
  70947. },
  70948. /**
  70949. * Sets Vignette stretch size.
  70950. */
  70951. set: function (value) {
  70952. this.imageProcessingConfiguration.vignetteStretch = value;
  70953. },
  70954. enumerable: true,
  70955. configurable: true
  70956. });
  70957. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70958. /**
  70959. * Gets Vignette centre X Offset.
  70960. */
  70961. get: function () {
  70962. return this.imageProcessingConfiguration.vignetteCentreX;
  70963. },
  70964. /**
  70965. * Sets Vignette centre X Offset.
  70966. */
  70967. set: function (value) {
  70968. this.imageProcessingConfiguration.vignetteCentreX = value;
  70969. },
  70970. enumerable: true,
  70971. configurable: true
  70972. });
  70973. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70974. /**
  70975. * Gets Vignette centre Y Offset.
  70976. */
  70977. get: function () {
  70978. return this.imageProcessingConfiguration.vignetteCentreY;
  70979. },
  70980. /**
  70981. * Sets Vignette centre Y Offset.
  70982. */
  70983. set: function (value) {
  70984. this.imageProcessingConfiguration.vignetteCentreY = value;
  70985. },
  70986. enumerable: true,
  70987. configurable: true
  70988. });
  70989. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70990. /**
  70991. * Gets Vignette weight or intensity of the vignette effect.
  70992. */
  70993. get: function () {
  70994. return this.imageProcessingConfiguration.vignetteWeight;
  70995. },
  70996. /**
  70997. * Sets Vignette weight or intensity of the vignette effect.
  70998. */
  70999. set: function (value) {
  71000. this.imageProcessingConfiguration.vignetteWeight = value;
  71001. },
  71002. enumerable: true,
  71003. configurable: true
  71004. });
  71005. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71006. /**
  71007. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71008. * if vignetteEnabled is set to true.
  71009. */
  71010. get: function () {
  71011. return this.imageProcessingConfiguration.vignetteColor;
  71012. },
  71013. /**
  71014. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71015. * if vignetteEnabled is set to true.
  71016. */
  71017. set: function (value) {
  71018. this.imageProcessingConfiguration.vignetteColor = value;
  71019. },
  71020. enumerable: true,
  71021. configurable: true
  71022. });
  71023. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71024. /**
  71025. * Gets Camera field of view used by the Vignette effect.
  71026. */
  71027. get: function () {
  71028. return this.imageProcessingConfiguration.vignetteCameraFov;
  71029. },
  71030. /**
  71031. * Sets Camera field of view used by the Vignette effect.
  71032. */
  71033. set: function (value) {
  71034. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71040. /**
  71041. * Gets the vignette blend mode allowing different kind of effect.
  71042. */
  71043. get: function () {
  71044. return this.imageProcessingConfiguration.vignetteBlendMode;
  71045. },
  71046. /**
  71047. * Sets the vignette blend mode allowing different kind of effect.
  71048. */
  71049. set: function (value) {
  71050. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71051. },
  71052. enumerable: true,
  71053. configurable: true
  71054. });
  71055. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71056. /**
  71057. * Gets wether the vignette effect is enabled.
  71058. */
  71059. get: function () {
  71060. return this.imageProcessingConfiguration.vignetteEnabled;
  71061. },
  71062. /**
  71063. * Sets wether the vignette effect is enabled.
  71064. */
  71065. set: function (value) {
  71066. this.imageProcessingConfiguration.vignetteEnabled = value;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71072. /**
  71073. * Gets wether the grain effect is enabled.
  71074. */
  71075. get: function () {
  71076. return this.imageProcessingConfiguration.grainEnabled;
  71077. },
  71078. /**
  71079. * Sets wether the grain effect is enabled.
  71080. */
  71081. set: function (value) {
  71082. this.imageProcessingConfiguration.grainEnabled = value;
  71083. },
  71084. enumerable: true,
  71085. configurable: true
  71086. });
  71087. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71088. /**
  71089. * Gets the grain effect's intensity.
  71090. */
  71091. get: function () {
  71092. return this.imageProcessingConfiguration.grainIntensity;
  71093. },
  71094. /**
  71095. * Sets the grain effect's intensity.
  71096. */
  71097. set: function (value) {
  71098. this.imageProcessingConfiguration.grainIntensity = value;
  71099. },
  71100. enumerable: true,
  71101. configurable: true
  71102. });
  71103. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71104. /**
  71105. * Gets wether the grain effect is animated.
  71106. */
  71107. get: function () {
  71108. return this.imageProcessingConfiguration.grainAnimated;
  71109. },
  71110. /**
  71111. * Sets wether the grain effect is animated.
  71112. */
  71113. set: function (value) {
  71114. this.imageProcessingConfiguration.grainAnimated = value;
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71120. /**
  71121. * Gets wether the input of the processing is in Gamma or Linear Space.
  71122. */
  71123. get: function () {
  71124. return this._fromLinearSpace;
  71125. },
  71126. /**
  71127. * Sets wether the input of the processing is in Gamma or Linear Space.
  71128. */
  71129. set: function (value) {
  71130. if (this._fromLinearSpace === value) {
  71131. return;
  71132. }
  71133. this._fromLinearSpace = value;
  71134. this._updateParameters();
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. ImageProcessingPostProcess.prototype.getClassName = function () {
  71140. return "ImageProcessingPostProcess";
  71141. };
  71142. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71143. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71144. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71145. var defines = "";
  71146. for (var define in this._defines) {
  71147. if (this._defines[define]) {
  71148. defines += "#define " + define + ";\r\n";
  71149. }
  71150. }
  71151. var samplers = ["textureSampler"];
  71152. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71153. var uniforms = ["scale"];
  71154. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71155. this.updateEffect(defines, uniforms, samplers);
  71156. };
  71157. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71158. _super.prototype.dispose.call(this, camera);
  71159. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71160. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71161. }
  71162. this.imageProcessingConfiguration.applyByPostProcess = false;
  71163. };
  71164. __decorate([
  71165. BABYLON.serialize()
  71166. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71167. return ImageProcessingPostProcess;
  71168. }(BABYLON.PostProcess));
  71169. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71170. })(BABYLON || (BABYLON = {}));
  71171. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71172. var BABYLON;
  71173. (function (BABYLON) {
  71174. var Bone = /** @class */ (function (_super) {
  71175. __extends(Bone, _super);
  71176. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71177. if (parentBone === void 0) { parentBone = null; }
  71178. if (localMatrix === void 0) { localMatrix = null; }
  71179. if (restPose === void 0) { restPose = null; }
  71180. if (baseMatrix === void 0) { baseMatrix = null; }
  71181. if (index === void 0) { index = null; }
  71182. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71183. _this.name = name;
  71184. _this.children = new Array();
  71185. _this.animations = new Array();
  71186. // Set this value to map this bone to a different index in the transform matrices.
  71187. // Set this value to -1 to exclude the bone from the transform matrices.
  71188. _this._index = null;
  71189. _this._worldTransform = new BABYLON.Matrix();
  71190. _this._absoluteTransform = new BABYLON.Matrix();
  71191. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71192. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71193. _this._scaleVector = BABYLON.Vector3.One();
  71194. _this._negateScaleChildren = BABYLON.Vector3.One();
  71195. _this._scalingDeterminant = 1;
  71196. _this._skeleton = skeleton;
  71197. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71198. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71199. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71200. _this._index = index;
  71201. skeleton.bones.push(_this);
  71202. _this.setParent(parentBone, false);
  71203. _this._updateDifferenceMatrix();
  71204. return _this;
  71205. }
  71206. Object.defineProperty(Bone.prototype, "_matrix", {
  71207. get: function () {
  71208. return this._localMatrix;
  71209. },
  71210. set: function (val) {
  71211. if (this._localMatrix) {
  71212. this._localMatrix.copyFrom(val);
  71213. }
  71214. else {
  71215. this._localMatrix = val;
  71216. }
  71217. },
  71218. enumerable: true,
  71219. configurable: true
  71220. });
  71221. // Members
  71222. Bone.prototype.getSkeleton = function () {
  71223. return this._skeleton;
  71224. };
  71225. Bone.prototype.getParent = function () {
  71226. return this._parent;
  71227. };
  71228. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71229. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71230. if (this._parent === parent) {
  71231. return;
  71232. }
  71233. if (this._parent) {
  71234. var index = this._parent.children.indexOf(this);
  71235. if (index !== -1) {
  71236. this._parent.children.splice(index, 1);
  71237. }
  71238. }
  71239. this._parent = parent;
  71240. if (this._parent) {
  71241. this._parent.children.push(this);
  71242. }
  71243. if (updateDifferenceMatrix) {
  71244. this._updateDifferenceMatrix();
  71245. }
  71246. };
  71247. Bone.prototype.getLocalMatrix = function () {
  71248. return this._localMatrix;
  71249. };
  71250. Bone.prototype.getBaseMatrix = function () {
  71251. return this._baseMatrix;
  71252. };
  71253. Bone.prototype.getRestPose = function () {
  71254. return this._restPose;
  71255. };
  71256. Bone.prototype.returnToRest = function () {
  71257. this.updateMatrix(this._restPose.clone());
  71258. };
  71259. Bone.prototype.getWorldMatrix = function () {
  71260. return this._worldTransform;
  71261. };
  71262. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71263. return this._invertedAbsoluteTransform;
  71264. };
  71265. Bone.prototype.getAbsoluteTransform = function () {
  71266. return this._absoluteTransform;
  71267. };
  71268. Object.defineProperty(Bone.prototype, "position", {
  71269. // Properties (matches AbstractMesh properties)
  71270. get: function () {
  71271. return this.getPosition();
  71272. },
  71273. set: function (newPosition) {
  71274. this.setPosition(newPosition);
  71275. },
  71276. enumerable: true,
  71277. configurable: true
  71278. });
  71279. Object.defineProperty(Bone.prototype, "rotation", {
  71280. get: function () {
  71281. return this.getRotation();
  71282. },
  71283. set: function (newRotation) {
  71284. this.setRotation(newRotation);
  71285. },
  71286. enumerable: true,
  71287. configurable: true
  71288. });
  71289. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71290. get: function () {
  71291. return this.getRotationQuaternion();
  71292. },
  71293. set: function (newRotation) {
  71294. this.setRotationQuaternion(newRotation);
  71295. },
  71296. enumerable: true,
  71297. configurable: true
  71298. });
  71299. Object.defineProperty(Bone.prototype, "scaling", {
  71300. get: function () {
  71301. return this.getScale();
  71302. },
  71303. set: function (newScaling) {
  71304. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71305. },
  71306. enumerable: true,
  71307. configurable: true
  71308. });
  71309. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71310. /**
  71311. * Gets the animation properties override
  71312. */
  71313. get: function () {
  71314. return this._skeleton.animationPropertiesOverride;
  71315. },
  71316. enumerable: true,
  71317. configurable: true
  71318. });
  71319. // Methods
  71320. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71321. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71322. this._baseMatrix = matrix.clone();
  71323. this._localMatrix = matrix.clone();
  71324. this._skeleton._markAsDirty();
  71325. if (updateDifferenceMatrix) {
  71326. this._updateDifferenceMatrix();
  71327. }
  71328. };
  71329. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71330. if (!rootMatrix) {
  71331. rootMatrix = this._baseMatrix;
  71332. }
  71333. if (this._parent) {
  71334. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71335. }
  71336. else {
  71337. this._absoluteTransform.copyFrom(rootMatrix);
  71338. }
  71339. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71340. for (var index = 0; index < this.children.length; index++) {
  71341. this.children[index]._updateDifferenceMatrix();
  71342. }
  71343. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71344. };
  71345. Bone.prototype.markAsDirty = function () {
  71346. this._currentRenderId++;
  71347. this._skeleton._markAsDirty();
  71348. };
  71349. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71350. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71351. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71352. // all animation may be coming from a library skeleton, so may need to create animation
  71353. if (this.animations.length === 0) {
  71354. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71355. this.animations[0].setKeys([]);
  71356. }
  71357. // get animation info / verify there is such a range from the source bone
  71358. var sourceRange = source.animations[0].getRange(rangeName);
  71359. if (!sourceRange) {
  71360. return false;
  71361. }
  71362. var from = sourceRange.from;
  71363. var to = sourceRange.to;
  71364. var sourceKeys = source.animations[0].getKeys();
  71365. // rescaling prep
  71366. var sourceBoneLength = source.length;
  71367. var sourceParent = source.getParent();
  71368. var parent = this.getParent();
  71369. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71370. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71371. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71372. var destKeys = this.animations[0].getKeys();
  71373. // loop vars declaration
  71374. var orig;
  71375. var origTranslation;
  71376. var mat;
  71377. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71378. orig = sourceKeys[key];
  71379. if (orig.frame >= from && orig.frame <= to) {
  71380. if (rescaleAsRequired) {
  71381. mat = orig.value.clone();
  71382. // scale based on parent ratio, when bone has parent
  71383. if (parentScalingReqd) {
  71384. origTranslation = mat.getTranslation();
  71385. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71386. // scale based on skeleton dimension ratio when root bone, and value is passed
  71387. }
  71388. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71389. origTranslation = mat.getTranslation();
  71390. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71391. // use original when root bone, and no data for skelDimensionsRatio
  71392. }
  71393. else {
  71394. mat = orig.value;
  71395. }
  71396. }
  71397. else {
  71398. mat = orig.value;
  71399. }
  71400. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71401. }
  71402. }
  71403. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71404. return true;
  71405. };
  71406. /**
  71407. * Translate the bone in local or world space.
  71408. * @param vec The amount to translate the bone.
  71409. * @param space The space that the translation is in.
  71410. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71411. */
  71412. Bone.prototype.translate = function (vec, space, mesh) {
  71413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71414. var lm = this.getLocalMatrix();
  71415. if (space == BABYLON.Space.LOCAL) {
  71416. lm.m[12] += vec.x;
  71417. lm.m[13] += vec.y;
  71418. lm.m[14] += vec.z;
  71419. }
  71420. else {
  71421. var wm = null;
  71422. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71423. if (mesh) {
  71424. wm = mesh.getWorldMatrix();
  71425. }
  71426. this._skeleton.computeAbsoluteTransforms();
  71427. var tmat = Bone._tmpMats[0];
  71428. var tvec = Bone._tmpVecs[0];
  71429. if (this._parent) {
  71430. if (mesh && wm) {
  71431. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71432. tmat.multiplyToRef(wm, tmat);
  71433. }
  71434. else {
  71435. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71436. }
  71437. }
  71438. tmat.m[12] = 0;
  71439. tmat.m[13] = 0;
  71440. tmat.m[14] = 0;
  71441. tmat.invert();
  71442. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71443. lm.m[12] += tvec.x;
  71444. lm.m[13] += tvec.y;
  71445. lm.m[14] += tvec.z;
  71446. }
  71447. this.markAsDirty();
  71448. };
  71449. /**
  71450. * Set the postion of the bone in local or world space.
  71451. * @param position The position to set the bone.
  71452. * @param space The space that the position is in.
  71453. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71454. */
  71455. Bone.prototype.setPosition = function (position, space, mesh) {
  71456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71457. var lm = this.getLocalMatrix();
  71458. if (space == BABYLON.Space.LOCAL) {
  71459. lm.m[12] = position.x;
  71460. lm.m[13] = position.y;
  71461. lm.m[14] = position.z;
  71462. }
  71463. else {
  71464. var wm = null;
  71465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71466. if (mesh) {
  71467. wm = mesh.getWorldMatrix();
  71468. }
  71469. this._skeleton.computeAbsoluteTransforms();
  71470. var tmat = Bone._tmpMats[0];
  71471. var vec = Bone._tmpVecs[0];
  71472. if (this._parent) {
  71473. if (mesh && wm) {
  71474. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71475. tmat.multiplyToRef(wm, tmat);
  71476. }
  71477. else {
  71478. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71479. }
  71480. }
  71481. tmat.invert();
  71482. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71483. lm.m[12] = vec.x;
  71484. lm.m[13] = vec.y;
  71485. lm.m[14] = vec.z;
  71486. }
  71487. this.markAsDirty();
  71488. };
  71489. /**
  71490. * Set the absolute postion of the bone (world space).
  71491. * @param position The position to set the bone.
  71492. * @param mesh The mesh that this bone is attached to.
  71493. */
  71494. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71495. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71496. };
  71497. /**
  71498. * Set the scale of the bone on the x, y and z axes.
  71499. * @param x The scale of the bone on the x axis.
  71500. * @param x The scale of the bone on the y axis.
  71501. * @param z The scale of the bone on the z axis.
  71502. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71503. */
  71504. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71505. if (scaleChildren === void 0) { scaleChildren = false; }
  71506. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71507. if (!scaleChildren) {
  71508. this._negateScaleChildren.x = 1 / x;
  71509. this._negateScaleChildren.y = 1 / y;
  71510. this._negateScaleChildren.z = 1 / z;
  71511. }
  71512. this._syncScaleVector();
  71513. }
  71514. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71515. };
  71516. /**
  71517. * Scale the bone on the x, y and z axes.
  71518. * @param x The amount to scale the bone on the x axis.
  71519. * @param x The amount to scale the bone on the y axis.
  71520. * @param z The amount to scale the bone on the z axis.
  71521. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71522. */
  71523. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71524. if (scaleChildren === void 0) { scaleChildren = false; }
  71525. var locMat = this.getLocalMatrix();
  71526. var origLocMat = Bone._tmpMats[0];
  71527. origLocMat.copyFrom(locMat);
  71528. var origLocMatInv = Bone._tmpMats[1];
  71529. origLocMatInv.copyFrom(origLocMat);
  71530. origLocMatInv.invert();
  71531. var scaleMat = Bone._tmpMats[2];
  71532. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71533. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71534. this._scaleVector.x *= x;
  71535. this._scaleVector.y *= y;
  71536. this._scaleVector.z *= z;
  71537. locMat.multiplyToRef(origLocMatInv, locMat);
  71538. locMat.multiplyToRef(scaleMat, locMat);
  71539. locMat.multiplyToRef(origLocMat, locMat);
  71540. var parent = this.getParent();
  71541. if (parent) {
  71542. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71543. }
  71544. else {
  71545. this.getAbsoluteTransform().copyFrom(locMat);
  71546. }
  71547. var len = this.children.length;
  71548. scaleMat.invert();
  71549. for (var i = 0; i < len; i++) {
  71550. var child = this.children[i];
  71551. var cm = child.getLocalMatrix();
  71552. cm.multiplyToRef(scaleMat, cm);
  71553. var lm = child.getLocalMatrix();
  71554. lm.m[12] *= x;
  71555. lm.m[13] *= y;
  71556. lm.m[14] *= z;
  71557. }
  71558. this.computeAbsoluteTransforms();
  71559. if (scaleChildren) {
  71560. for (var i = 0; i < len; i++) {
  71561. this.children[i].scale(x, y, z, scaleChildren);
  71562. }
  71563. }
  71564. this.markAsDirty();
  71565. };
  71566. /**
  71567. * Set the yaw, pitch, and roll of the bone in local or world space.
  71568. * @param yaw The rotation of the bone on the y axis.
  71569. * @param pitch The rotation of the bone on the x axis.
  71570. * @param roll The rotation of the bone on the z axis.
  71571. * @param space The space that the axes of rotation are in.
  71572. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71573. */
  71574. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71576. var rotMat = Bone._tmpMats[0];
  71577. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71578. var rotMatInv = Bone._tmpMats[1];
  71579. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71580. rotMatInv.multiplyToRef(rotMat, rotMat);
  71581. this._rotateWithMatrix(rotMat, space, mesh);
  71582. };
  71583. /**
  71584. * Rotate the bone on an axis in local or world space.
  71585. * @param axis The axis to rotate the bone on.
  71586. * @param amount The amount to rotate the bone.
  71587. * @param space The space that the axis is in.
  71588. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71589. */
  71590. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71592. var rmat = Bone._tmpMats[0];
  71593. rmat.m[12] = 0;
  71594. rmat.m[13] = 0;
  71595. rmat.m[14] = 0;
  71596. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71597. this._rotateWithMatrix(rmat, space, mesh);
  71598. };
  71599. /**
  71600. * Set the rotation of the bone to a particular axis angle in local or world space.
  71601. * @param axis The axis to rotate the bone on.
  71602. * @param angle The angle that the bone should be rotated to.
  71603. * @param space The space that the axis is in.
  71604. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71605. */
  71606. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71608. var rotMat = Bone._tmpMats[0];
  71609. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71610. var rotMatInv = Bone._tmpMats[1];
  71611. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71612. rotMatInv.multiplyToRef(rotMat, rotMat);
  71613. this._rotateWithMatrix(rotMat, space, mesh);
  71614. };
  71615. /**
  71616. * Set the euler rotation of the bone in local of world space.
  71617. * @param rotation The euler rotation that the bone should be set to.
  71618. * @param space The space that the rotation is in.
  71619. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71620. */
  71621. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71623. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71624. };
  71625. /**
  71626. * Set the quaternion rotation of the bone in local of world space.
  71627. * @param quat The quaternion rotation that the bone should be set to.
  71628. * @param space The space that the rotation is in.
  71629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71630. */
  71631. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71633. var rotMatInv = Bone._tmpMats[0];
  71634. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71635. var rotMat = Bone._tmpMats[1];
  71636. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71637. rotMatInv.multiplyToRef(rotMat, rotMat);
  71638. this._rotateWithMatrix(rotMat, space, mesh);
  71639. };
  71640. /**
  71641. * Set the rotation matrix of the bone in local of world space.
  71642. * @param rotMat The rotation matrix that the bone should be set to.
  71643. * @param space The space that the rotation is in.
  71644. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71645. */
  71646. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71648. var rotMatInv = Bone._tmpMats[0];
  71649. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71650. var rotMat2 = Bone._tmpMats[1];
  71651. rotMat2.copyFrom(rotMat);
  71652. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71653. this._rotateWithMatrix(rotMat2, space, mesh);
  71654. };
  71655. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71657. var lmat = this.getLocalMatrix();
  71658. var lx = lmat.m[12];
  71659. var ly = lmat.m[13];
  71660. var lz = lmat.m[14];
  71661. var parent = this.getParent();
  71662. var parentScale = Bone._tmpMats[3];
  71663. var parentScaleInv = Bone._tmpMats[4];
  71664. if (parent) {
  71665. if (space == BABYLON.Space.WORLD) {
  71666. if (mesh) {
  71667. parentScale.copyFrom(mesh.getWorldMatrix());
  71668. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71669. }
  71670. else {
  71671. parentScale.copyFrom(parent.getAbsoluteTransform());
  71672. }
  71673. }
  71674. else {
  71675. parentScale = parent._scaleMatrix;
  71676. }
  71677. parentScaleInv.copyFrom(parentScale);
  71678. parentScaleInv.invert();
  71679. lmat.multiplyToRef(parentScale, lmat);
  71680. lmat.multiplyToRef(rmat, lmat);
  71681. lmat.multiplyToRef(parentScaleInv, lmat);
  71682. }
  71683. else {
  71684. if (space == BABYLON.Space.WORLD && mesh) {
  71685. parentScale.copyFrom(mesh.getWorldMatrix());
  71686. parentScaleInv.copyFrom(parentScale);
  71687. parentScaleInv.invert();
  71688. lmat.multiplyToRef(parentScale, lmat);
  71689. lmat.multiplyToRef(rmat, lmat);
  71690. lmat.multiplyToRef(parentScaleInv, lmat);
  71691. }
  71692. else {
  71693. lmat.multiplyToRef(rmat, lmat);
  71694. }
  71695. }
  71696. lmat.m[12] = lx;
  71697. lmat.m[13] = ly;
  71698. lmat.m[14] = lz;
  71699. this.computeAbsoluteTransforms();
  71700. this.markAsDirty();
  71701. };
  71702. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71704. if (space == BABYLON.Space.WORLD) {
  71705. var scaleMatrix = Bone._tmpMats[2];
  71706. scaleMatrix.copyFrom(this._scaleMatrix);
  71707. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71708. if (mesh) {
  71709. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71710. var meshScale = Bone._tmpMats[3];
  71711. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71712. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71713. }
  71714. rotMatInv.invert();
  71715. scaleMatrix.m[0] *= this._scalingDeterminant;
  71716. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71717. }
  71718. else {
  71719. rotMatInv.copyFrom(this.getLocalMatrix());
  71720. rotMatInv.invert();
  71721. var scaleMatrix = Bone._tmpMats[2];
  71722. scaleMatrix.copyFrom(this._scaleMatrix);
  71723. if (this._parent) {
  71724. var pscaleMatrix = Bone._tmpMats[3];
  71725. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71726. pscaleMatrix.invert();
  71727. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71728. }
  71729. else {
  71730. scaleMatrix.m[0] *= this._scalingDeterminant;
  71731. }
  71732. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71733. }
  71734. };
  71735. /**
  71736. * Get the scale of the bone
  71737. * @returns the scale of the bone
  71738. */
  71739. Bone.prototype.getScale = function () {
  71740. return this._scaleVector.clone();
  71741. };
  71742. /**
  71743. * Copy the scale of the bone to a vector3.
  71744. * @param result The vector3 to copy the scale to
  71745. */
  71746. Bone.prototype.getScaleToRef = function (result) {
  71747. result.copyFrom(this._scaleVector);
  71748. };
  71749. /**
  71750. * Get the position of the bone in local or world space.
  71751. * @param space The space that the returned position is in.
  71752. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71753. * @returns The position of the bone
  71754. */
  71755. Bone.prototype.getPosition = function (space, mesh) {
  71756. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71757. if (mesh === void 0) { mesh = null; }
  71758. var pos = BABYLON.Vector3.Zero();
  71759. this.getPositionToRef(space, mesh, pos);
  71760. return pos;
  71761. };
  71762. /**
  71763. * Copy the position of the bone to a vector3 in local or world space.
  71764. * @param space The space that the returned position is in.
  71765. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71766. * @param result The vector3 to copy the position to.
  71767. */
  71768. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71769. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71770. if (space == BABYLON.Space.LOCAL) {
  71771. var lm = this.getLocalMatrix();
  71772. result.x = lm.m[12];
  71773. result.y = lm.m[13];
  71774. result.z = lm.m[14];
  71775. }
  71776. else {
  71777. var wm = null;
  71778. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71779. if (mesh) {
  71780. wm = mesh.getWorldMatrix();
  71781. }
  71782. this._skeleton.computeAbsoluteTransforms();
  71783. var tmat = Bone._tmpMats[0];
  71784. if (mesh && wm) {
  71785. tmat.copyFrom(this.getAbsoluteTransform());
  71786. tmat.multiplyToRef(wm, tmat);
  71787. }
  71788. else {
  71789. tmat = this.getAbsoluteTransform();
  71790. }
  71791. result.x = tmat.m[12];
  71792. result.y = tmat.m[13];
  71793. result.z = tmat.m[14];
  71794. }
  71795. };
  71796. /**
  71797. * Get the absolute position of the bone (world space).
  71798. * @param mesh The mesh that this bone is attached to.
  71799. * @returns The absolute position of the bone
  71800. */
  71801. Bone.prototype.getAbsolutePosition = function (mesh) {
  71802. if (mesh === void 0) { mesh = null; }
  71803. var pos = BABYLON.Vector3.Zero();
  71804. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71805. return pos;
  71806. };
  71807. /**
  71808. * Copy the absolute position of the bone (world space) to the result param.
  71809. * @param mesh The mesh that this bone is attached to.
  71810. * @param result The vector3 to copy the absolute position to.
  71811. */
  71812. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71813. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71814. };
  71815. /**
  71816. * Compute the absolute transforms of this bone and its children.
  71817. */
  71818. Bone.prototype.computeAbsoluteTransforms = function () {
  71819. if (this._parent) {
  71820. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71821. }
  71822. else {
  71823. this._absoluteTransform.copyFrom(this._localMatrix);
  71824. var poseMatrix = this._skeleton.getPoseMatrix();
  71825. if (poseMatrix) {
  71826. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71827. }
  71828. }
  71829. var children = this.children;
  71830. var len = children.length;
  71831. for (var i = 0; i < len; i++) {
  71832. children[i].computeAbsoluteTransforms();
  71833. }
  71834. };
  71835. Bone.prototype._syncScaleVector = function () {
  71836. var lm = this.getLocalMatrix();
  71837. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71838. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71839. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71840. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71841. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71842. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71843. this._scaleVector.x = xs * Math.sqrt(xsq);
  71844. this._scaleVector.y = ys * Math.sqrt(ysq);
  71845. this._scaleVector.z = zs * Math.sqrt(zsq);
  71846. if (this._parent) {
  71847. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71848. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71849. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71850. }
  71851. 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);
  71852. };
  71853. /**
  71854. * Get the world direction from an axis that is in the local space of the bone.
  71855. * @param localAxis The local direction that is used to compute the world direction.
  71856. * @param mesh The mesh that this bone is attached to.
  71857. * @returns The world direction
  71858. */
  71859. Bone.prototype.getDirection = function (localAxis, mesh) {
  71860. if (mesh === void 0) { mesh = null; }
  71861. var result = BABYLON.Vector3.Zero();
  71862. this.getDirectionToRef(localAxis, mesh, result);
  71863. return result;
  71864. };
  71865. /**
  71866. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71867. * @param localAxis The local direction that is used to compute the world direction.
  71868. * @param mesh The mesh that this bone is attached to.
  71869. * @param result The vector3 that the world direction will be copied to.
  71870. */
  71871. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71872. if (mesh === void 0) { mesh = null; }
  71873. var wm = null;
  71874. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71875. if (mesh) {
  71876. wm = mesh.getWorldMatrix();
  71877. }
  71878. this._skeleton.computeAbsoluteTransforms();
  71879. var mat = Bone._tmpMats[0];
  71880. mat.copyFrom(this.getAbsoluteTransform());
  71881. if (mesh && wm) {
  71882. mat.multiplyToRef(wm, mat);
  71883. }
  71884. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71885. result.normalize();
  71886. };
  71887. /**
  71888. * Get the euler rotation of the bone in local or world space.
  71889. * @param space The space that the rotation should be in.
  71890. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71891. * @returns The euler rotation
  71892. */
  71893. Bone.prototype.getRotation = function (space, mesh) {
  71894. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71895. if (mesh === void 0) { mesh = null; }
  71896. var result = BABYLON.Vector3.Zero();
  71897. this.getRotationToRef(space, mesh, result);
  71898. return result;
  71899. };
  71900. /**
  71901. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71902. * @param space The space that the rotation should be in.
  71903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71904. * @param result The vector3 that the rotation should be copied to.
  71905. */
  71906. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71908. if (mesh === void 0) { mesh = null; }
  71909. var quat = Bone._tmpQuat;
  71910. this.getRotationQuaternionToRef(space, mesh, quat);
  71911. quat.toEulerAnglesToRef(result);
  71912. };
  71913. /**
  71914. * Get the quaternion rotation of the bone in either local or world space.
  71915. * @param space The space that the rotation should be in.
  71916. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71917. * @returns The quaternion rotation
  71918. */
  71919. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71921. if (mesh === void 0) { mesh = null; }
  71922. var result = BABYLON.Quaternion.Identity();
  71923. this.getRotationQuaternionToRef(space, mesh, result);
  71924. return result;
  71925. };
  71926. /**
  71927. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71928. * @param space The space that the rotation should be in.
  71929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71930. * @param result The quaternion that the rotation should be copied to.
  71931. */
  71932. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71934. if (mesh === void 0) { mesh = null; }
  71935. if (space == BABYLON.Space.LOCAL) {
  71936. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71937. }
  71938. else {
  71939. var mat = Bone._tmpMats[0];
  71940. var amat = this.getAbsoluteTransform();
  71941. if (mesh) {
  71942. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71943. }
  71944. else {
  71945. mat.copyFrom(amat);
  71946. }
  71947. mat.m[0] *= this._scalingDeterminant;
  71948. mat.m[1] *= this._scalingDeterminant;
  71949. mat.m[2] *= this._scalingDeterminant;
  71950. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71951. }
  71952. };
  71953. /**
  71954. * Get the rotation matrix of the bone in local or world space.
  71955. * @param space The space that the rotation should be in.
  71956. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71957. * @returns The rotation matrix
  71958. */
  71959. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71961. var result = BABYLON.Matrix.Identity();
  71962. this.getRotationMatrixToRef(space, mesh, result);
  71963. return result;
  71964. };
  71965. /**
  71966. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71967. * @param space The space that the rotation should be in.
  71968. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71969. * @param result The quaternion that the rotation should be copied to.
  71970. */
  71971. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71973. if (space == BABYLON.Space.LOCAL) {
  71974. this.getLocalMatrix().getRotationMatrixToRef(result);
  71975. }
  71976. else {
  71977. var mat = Bone._tmpMats[0];
  71978. var amat = this.getAbsoluteTransform();
  71979. if (mesh) {
  71980. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71981. }
  71982. else {
  71983. mat.copyFrom(amat);
  71984. }
  71985. mat.m[0] *= this._scalingDeterminant;
  71986. mat.m[1] *= this._scalingDeterminant;
  71987. mat.m[2] *= this._scalingDeterminant;
  71988. mat.getRotationMatrixToRef(result);
  71989. }
  71990. };
  71991. /**
  71992. * Get the world position of a point that is in the local space of the bone.
  71993. * @param position The local position
  71994. * @param mesh The mesh that this bone is attached to.
  71995. * @returns The world position
  71996. */
  71997. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71998. if (mesh === void 0) { mesh = null; }
  71999. var result = BABYLON.Vector3.Zero();
  72000. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72001. return result;
  72002. };
  72003. /**
  72004. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72005. * @param position The local position
  72006. * @param mesh The mesh that this bone is attached to.
  72007. * @param result The vector3 that the world position should be copied to.
  72008. */
  72009. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72010. if (mesh === void 0) { mesh = null; }
  72011. var wm = null;
  72012. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72013. if (mesh) {
  72014. wm = mesh.getWorldMatrix();
  72015. }
  72016. this._skeleton.computeAbsoluteTransforms();
  72017. var tmat = Bone._tmpMats[0];
  72018. if (mesh && wm) {
  72019. tmat.copyFrom(this.getAbsoluteTransform());
  72020. tmat.multiplyToRef(wm, tmat);
  72021. }
  72022. else {
  72023. tmat = this.getAbsoluteTransform();
  72024. }
  72025. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72026. };
  72027. /**
  72028. * Get the local position of a point that is in world space.
  72029. * @param position The world position
  72030. * @param mesh The mesh that this bone is attached to.
  72031. * @returns The local position
  72032. */
  72033. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72034. if (mesh === void 0) { mesh = null; }
  72035. var result = BABYLON.Vector3.Zero();
  72036. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72037. return result;
  72038. };
  72039. /**
  72040. * Get the local position of a point that is in world space and copy it to the result param.
  72041. * @param position The world position
  72042. * @param mesh The mesh that this bone is attached to.
  72043. * @param result The vector3 that the local position should be copied to.
  72044. */
  72045. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72046. if (mesh === void 0) { mesh = null; }
  72047. var wm = null;
  72048. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72049. if (mesh) {
  72050. wm = mesh.getWorldMatrix();
  72051. }
  72052. this._skeleton.computeAbsoluteTransforms();
  72053. var tmat = Bone._tmpMats[0];
  72054. tmat.copyFrom(this.getAbsoluteTransform());
  72055. if (mesh && wm) {
  72056. tmat.multiplyToRef(wm, tmat);
  72057. }
  72058. tmat.invert();
  72059. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72060. };
  72061. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72062. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72063. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72064. return Bone;
  72065. }(BABYLON.Node));
  72066. BABYLON.Bone = Bone;
  72067. })(BABYLON || (BABYLON = {}));
  72068. //# sourceMappingURL=babylon.bone.js.map
  72069. var BABYLON;
  72070. (function (BABYLON) {
  72071. var BoneIKController = /** @class */ (function () {
  72072. function BoneIKController(mesh, bone, options) {
  72073. this.targetPosition = BABYLON.Vector3.Zero();
  72074. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72075. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72076. this.poleAngle = 0;
  72077. this.slerpAmount = 1;
  72078. this._bone1Quat = BABYLON.Quaternion.Identity();
  72079. this._bone1Mat = BABYLON.Matrix.Identity();
  72080. this._bone2Ang = Math.PI;
  72081. this._maxAngle = Math.PI;
  72082. this._rightHandedSystem = false;
  72083. this._bendAxis = BABYLON.Vector3.Right();
  72084. this._slerping = false;
  72085. this._adjustRoll = 0;
  72086. this._bone2 = bone;
  72087. this._bone1 = bone.getParent();
  72088. if (!this._bone1) {
  72089. return;
  72090. }
  72091. this.mesh = mesh;
  72092. var bonePos = bone.getPosition();
  72093. if (bone.getAbsoluteTransform().determinant() > 0) {
  72094. this._rightHandedSystem = true;
  72095. this._bendAxis.x = 0;
  72096. this._bendAxis.y = 0;
  72097. this._bendAxis.z = -1;
  72098. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72099. this._adjustRoll = Math.PI * .5;
  72100. this._bendAxis.z = 1;
  72101. }
  72102. }
  72103. if (this._bone1.length) {
  72104. var boneScale1 = this._bone1.getScale();
  72105. var boneScale2 = this._bone2.getScale();
  72106. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72107. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72108. }
  72109. else if (this._bone1.children[0]) {
  72110. mesh.computeWorldMatrix(true);
  72111. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72112. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72113. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72114. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72115. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72116. }
  72117. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72118. this.maxAngle = Math.PI;
  72119. if (options) {
  72120. if (options.targetMesh) {
  72121. this.targetMesh = options.targetMesh;
  72122. this.targetMesh.computeWorldMatrix(true);
  72123. }
  72124. if (options.poleTargetMesh) {
  72125. this.poleTargetMesh = options.poleTargetMesh;
  72126. this.poleTargetMesh.computeWorldMatrix(true);
  72127. }
  72128. else if (options.poleTargetBone) {
  72129. this.poleTargetBone = options.poleTargetBone;
  72130. }
  72131. else if (this._bone1.getParent()) {
  72132. this.poleTargetBone = this._bone1.getParent();
  72133. }
  72134. if (options.poleTargetLocalOffset) {
  72135. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72136. }
  72137. if (options.poleAngle) {
  72138. this.poleAngle = options.poleAngle;
  72139. }
  72140. if (options.bendAxis) {
  72141. this._bendAxis.copyFrom(options.bendAxis);
  72142. }
  72143. if (options.maxAngle) {
  72144. this.maxAngle = options.maxAngle;
  72145. }
  72146. if (options.slerpAmount) {
  72147. this.slerpAmount = options.slerpAmount;
  72148. }
  72149. }
  72150. }
  72151. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72152. get: function () {
  72153. return this._maxAngle;
  72154. },
  72155. set: function (value) {
  72156. this._setMaxAngle(value);
  72157. },
  72158. enumerable: true,
  72159. configurable: true
  72160. });
  72161. BoneIKController.prototype._setMaxAngle = function (ang) {
  72162. if (ang < 0) {
  72163. ang = 0;
  72164. }
  72165. if (ang > Math.PI || ang == undefined) {
  72166. ang = Math.PI;
  72167. }
  72168. this._maxAngle = ang;
  72169. var a = this._bone1Length;
  72170. var b = this._bone2Length;
  72171. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72172. };
  72173. BoneIKController.prototype.update = function () {
  72174. var bone1 = this._bone1;
  72175. if (!bone1) {
  72176. return;
  72177. }
  72178. var target = this.targetPosition;
  72179. var poleTarget = this.poleTargetPosition;
  72180. var mat1 = BoneIKController._tmpMats[0];
  72181. var mat2 = BoneIKController._tmpMats[1];
  72182. if (this.targetMesh) {
  72183. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72184. }
  72185. if (this.poleTargetBone) {
  72186. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72187. }
  72188. else if (this.poleTargetMesh) {
  72189. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72190. }
  72191. var bonePos = BoneIKController._tmpVecs[0];
  72192. var zaxis = BoneIKController._tmpVecs[1];
  72193. var xaxis = BoneIKController._tmpVecs[2];
  72194. var yaxis = BoneIKController._tmpVecs[3];
  72195. var upAxis = BoneIKController._tmpVecs[4];
  72196. var _tmpQuat = BoneIKController._tmpQuat;
  72197. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72198. poleTarget.subtractToRef(bonePos, upAxis);
  72199. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72200. upAxis.y = 1;
  72201. }
  72202. else {
  72203. upAxis.normalize();
  72204. }
  72205. target.subtractToRef(bonePos, yaxis);
  72206. yaxis.normalize();
  72207. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72208. zaxis.normalize();
  72209. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72210. xaxis.normalize();
  72211. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72212. var a = this._bone1Length;
  72213. var b = this._bone2Length;
  72214. var c = BABYLON.Vector3.Distance(bonePos, target);
  72215. if (this._maxReach > 0) {
  72216. c = Math.min(this._maxReach, c);
  72217. }
  72218. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72219. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72220. if (acosa > 1) {
  72221. acosa = 1;
  72222. }
  72223. if (acosb > 1) {
  72224. acosb = 1;
  72225. }
  72226. if (acosa < -1) {
  72227. acosa = -1;
  72228. }
  72229. if (acosb < -1) {
  72230. acosb = -1;
  72231. }
  72232. var angA = Math.acos(acosa);
  72233. var angB = Math.acos(acosb);
  72234. var angC = -angA - angB;
  72235. if (this._rightHandedSystem) {
  72236. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72237. mat2.multiplyToRef(mat1, mat1);
  72238. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72239. mat2.multiplyToRef(mat1, mat1);
  72240. }
  72241. else {
  72242. var _tmpVec = BoneIKController._tmpVecs[5];
  72243. _tmpVec.copyFrom(this._bendAxis);
  72244. _tmpVec.x *= -1;
  72245. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72246. mat2.multiplyToRef(mat1, mat1);
  72247. }
  72248. if (this.poleAngle) {
  72249. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72250. mat1.multiplyToRef(mat2, mat1);
  72251. }
  72252. if (this._bone1) {
  72253. if (this.slerpAmount < 1) {
  72254. if (!this._slerping) {
  72255. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72256. }
  72257. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72258. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72259. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72260. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72261. this._slerping = true;
  72262. }
  72263. else {
  72264. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72265. this._bone1Mat.copyFrom(mat1);
  72266. this._slerping = false;
  72267. }
  72268. }
  72269. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72270. this._bone2Ang = angC;
  72271. };
  72272. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72273. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72274. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72275. return BoneIKController;
  72276. }());
  72277. BABYLON.BoneIKController = BoneIKController;
  72278. })(BABYLON || (BABYLON = {}));
  72279. //# sourceMappingURL=babylon.boneIKController.js.map
  72280. var BABYLON;
  72281. (function (BABYLON) {
  72282. var BoneLookController = /** @class */ (function () {
  72283. /**
  72284. * Create a BoneLookController
  72285. * @param mesh the mesh that the bone belongs to
  72286. * @param bone the bone that will be looking to the target
  72287. * @param target the target Vector3 to look at
  72288. * @param settings optional settings:
  72289. * - maxYaw: the maximum angle the bone will yaw to
  72290. * - minYaw: the minimum angle the bone will yaw to
  72291. * - maxPitch: the maximum angle the bone will pitch to
  72292. * - minPitch: the minimum angle the bone will yaw to
  72293. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72294. * - upAxis: the up axis of the coordinate system
  72295. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72296. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72297. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72298. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72299. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72300. * - adjustRoll: used to make an adjustment to the roll of the bone
  72301. **/
  72302. function BoneLookController(mesh, bone, target, options) {
  72303. /**
  72304. * The up axis of the coordinate system that is used when the bone is rotated.
  72305. */
  72306. this.upAxis = BABYLON.Vector3.Up();
  72307. /**
  72308. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72309. */
  72310. this.upAxisSpace = BABYLON.Space.LOCAL;
  72311. /**
  72312. * Used to make an adjustment to the yaw of the bone.
  72313. */
  72314. this.adjustYaw = 0;
  72315. /**
  72316. * Used to make an adjustment to the pitch of the bone.
  72317. */
  72318. this.adjustPitch = 0;
  72319. /**
  72320. * Used to make an adjustment to the roll of the bone.
  72321. */
  72322. this.adjustRoll = 0;
  72323. /**
  72324. * 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).
  72325. */
  72326. this.slerpAmount = 1;
  72327. this._boneQuat = BABYLON.Quaternion.Identity();
  72328. this._slerping = false;
  72329. this._firstFrameSkipped = false;
  72330. this._fowardAxis = BABYLON.Vector3.Forward();
  72331. this.mesh = mesh;
  72332. this.bone = bone;
  72333. this.target = target;
  72334. if (options) {
  72335. if (options.adjustYaw) {
  72336. this.adjustYaw = options.adjustYaw;
  72337. }
  72338. if (options.adjustPitch) {
  72339. this.adjustPitch = options.adjustPitch;
  72340. }
  72341. if (options.adjustRoll) {
  72342. this.adjustRoll = options.adjustRoll;
  72343. }
  72344. if (options.maxYaw != null) {
  72345. this.maxYaw = options.maxYaw;
  72346. }
  72347. else {
  72348. this.maxYaw = Math.PI;
  72349. }
  72350. if (options.minYaw != null) {
  72351. this.minYaw = options.minYaw;
  72352. }
  72353. else {
  72354. this.minYaw = -Math.PI;
  72355. }
  72356. if (options.maxPitch != null) {
  72357. this.maxPitch = options.maxPitch;
  72358. }
  72359. else {
  72360. this.maxPitch = Math.PI;
  72361. }
  72362. if (options.minPitch != null) {
  72363. this.minPitch = options.minPitch;
  72364. }
  72365. else {
  72366. this.minPitch = -Math.PI;
  72367. }
  72368. if (options.slerpAmount != null) {
  72369. this.slerpAmount = options.slerpAmount;
  72370. }
  72371. if (options.upAxis != null) {
  72372. this.upAxis = options.upAxis;
  72373. }
  72374. if (options.upAxisSpace != null) {
  72375. this.upAxisSpace = options.upAxisSpace;
  72376. }
  72377. if (options.yawAxis != null || options.pitchAxis != null) {
  72378. var newYawAxis = BABYLON.Axis.Y;
  72379. var newPitchAxis = BABYLON.Axis.X;
  72380. if (options.yawAxis != null) {
  72381. newYawAxis = options.yawAxis.clone();
  72382. newYawAxis.normalize();
  72383. }
  72384. if (options.pitchAxis != null) {
  72385. newPitchAxis = options.pitchAxis.clone();
  72386. newPitchAxis.normalize();
  72387. }
  72388. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72389. this._transformYawPitch = BABYLON.Matrix.Identity();
  72390. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72391. this._transformYawPitchInv = this._transformYawPitch.clone();
  72392. this._transformYawPitch.invert();
  72393. }
  72394. }
  72395. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72396. this.upAxisSpace = BABYLON.Space.LOCAL;
  72397. }
  72398. }
  72399. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72400. /**
  72401. * Get/set the minimum yaw angle that the bone can look to.
  72402. */
  72403. get: function () {
  72404. return this._minYaw;
  72405. },
  72406. set: function (value) {
  72407. this._minYaw = value;
  72408. this._minYawSin = Math.sin(value);
  72409. this._minYawCos = Math.cos(value);
  72410. if (this._maxYaw != null) {
  72411. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72412. this._yawRange = this._maxYaw - this._minYaw;
  72413. }
  72414. },
  72415. enumerable: true,
  72416. configurable: true
  72417. });
  72418. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72419. /**
  72420. * Get/set the maximum yaw angle that the bone can look to.
  72421. */
  72422. get: function () {
  72423. return this._maxYaw;
  72424. },
  72425. set: function (value) {
  72426. this._maxYaw = value;
  72427. this._maxYawSin = Math.sin(value);
  72428. this._maxYawCos = Math.cos(value);
  72429. if (this._minYaw != null) {
  72430. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72431. this._yawRange = this._maxYaw - this._minYaw;
  72432. }
  72433. },
  72434. enumerable: true,
  72435. configurable: true
  72436. });
  72437. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72438. /**
  72439. * Get/set the minimum pitch angle that the bone can look to.
  72440. */
  72441. get: function () {
  72442. return this._minPitch;
  72443. },
  72444. set: function (value) {
  72445. this._minPitch = value;
  72446. this._minPitchTan = Math.tan(value);
  72447. },
  72448. enumerable: true,
  72449. configurable: true
  72450. });
  72451. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72452. /**
  72453. * Get/set the maximum pitch angle that the bone can look to.
  72454. */
  72455. get: function () {
  72456. return this._maxPitch;
  72457. },
  72458. set: function (value) {
  72459. this._maxPitch = value;
  72460. this._maxPitchTan = Math.tan(value);
  72461. },
  72462. enumerable: true,
  72463. configurable: true
  72464. });
  72465. /**
  72466. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72467. */
  72468. BoneLookController.prototype.update = function () {
  72469. //skip the first frame when slerping so that the mesh rotation is correct
  72470. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72471. this._firstFrameSkipped = true;
  72472. return;
  72473. }
  72474. var bone = this.bone;
  72475. var bonePos = BoneLookController._tmpVecs[0];
  72476. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72477. var target = this.target;
  72478. var _tmpMat1 = BoneLookController._tmpMats[0];
  72479. var _tmpMat2 = BoneLookController._tmpMats[1];
  72480. var mesh = this.mesh;
  72481. var parentBone = bone.getParent();
  72482. var upAxis = BoneLookController._tmpVecs[1];
  72483. upAxis.copyFrom(this.upAxis);
  72484. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72485. if (this._transformYawPitch) {
  72486. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72487. }
  72488. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72489. }
  72490. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72491. mesh.getDirectionToRef(upAxis, upAxis);
  72492. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72493. upAxis.normalize();
  72494. }
  72495. }
  72496. var checkYaw = false;
  72497. var checkPitch = false;
  72498. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72499. checkYaw = true;
  72500. }
  72501. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72502. checkPitch = true;
  72503. }
  72504. if (checkYaw || checkPitch) {
  72505. var spaceMat = BoneLookController._tmpMats[2];
  72506. var spaceMatInv = BoneLookController._tmpMats[3];
  72507. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72508. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72509. }
  72510. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72511. spaceMat.copyFrom(mesh.getWorldMatrix());
  72512. }
  72513. else {
  72514. var forwardAxis = BoneLookController._tmpVecs[2];
  72515. forwardAxis.copyFrom(this._fowardAxis);
  72516. if (this._transformYawPitch) {
  72517. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72518. }
  72519. if (parentBone) {
  72520. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72521. }
  72522. else {
  72523. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72524. }
  72525. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72526. rightAxis.normalize();
  72527. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72528. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72529. }
  72530. spaceMat.invertToRef(spaceMatInv);
  72531. var xzlen = null;
  72532. if (checkPitch) {
  72533. var localTarget = BoneLookController._tmpVecs[3];
  72534. target.subtractToRef(bonePos, localTarget);
  72535. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72536. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72537. var pitch = Math.atan2(localTarget.y, xzlen);
  72538. var newPitch = pitch;
  72539. if (pitch > this._maxPitch) {
  72540. localTarget.y = this._maxPitchTan * xzlen;
  72541. newPitch = this._maxPitch;
  72542. }
  72543. else if (pitch < this._minPitch) {
  72544. localTarget.y = this._minPitchTan * xzlen;
  72545. newPitch = this._minPitch;
  72546. }
  72547. if (pitch != newPitch) {
  72548. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72549. localTarget.addInPlace(bonePos);
  72550. target = localTarget;
  72551. }
  72552. }
  72553. if (checkYaw) {
  72554. var localTarget = BoneLookController._tmpVecs[4];
  72555. target.subtractToRef(bonePos, localTarget);
  72556. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72557. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72558. var newYaw = yaw;
  72559. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72560. if (xzlen == null) {
  72561. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72562. }
  72563. if (this._yawRange > Math.PI) {
  72564. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72565. localTarget.z = this._maxYawCos * xzlen;
  72566. localTarget.x = this._maxYawSin * xzlen;
  72567. newYaw = this._maxYaw;
  72568. }
  72569. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72570. localTarget.z = this._minYawCos * xzlen;
  72571. localTarget.x = this._minYawSin * xzlen;
  72572. newYaw = this._minYaw;
  72573. }
  72574. }
  72575. else {
  72576. if (yaw > this._maxYaw) {
  72577. localTarget.z = this._maxYawCos * xzlen;
  72578. localTarget.x = this._maxYawSin * xzlen;
  72579. newYaw = this._maxYaw;
  72580. }
  72581. else if (yaw < this._minYaw) {
  72582. localTarget.z = this._minYawCos * xzlen;
  72583. localTarget.x = this._minYawSin * xzlen;
  72584. newYaw = this._minYaw;
  72585. }
  72586. }
  72587. }
  72588. if (this._slerping && this._yawRange > Math.PI) {
  72589. //are we going to be crossing into the min/max region?
  72590. var boneFwd = BoneLookController._tmpVecs[8];
  72591. boneFwd.copyFrom(BABYLON.Axis.Z);
  72592. if (this._transformYawPitch) {
  72593. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72594. }
  72595. var boneRotMat = BoneLookController._tmpMats[4];
  72596. this._boneQuat.toRotationMatrix(boneRotMat);
  72597. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72598. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72599. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72600. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72601. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72602. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72603. if (angBtwTar > angBtwMidYaw) {
  72604. if (xzlen == null) {
  72605. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72606. }
  72607. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72608. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72609. if (angBtwMin < angBtwMax) {
  72610. newYaw = boneYaw + Math.PI * .75;
  72611. localTarget.z = Math.cos(newYaw) * xzlen;
  72612. localTarget.x = Math.sin(newYaw) * xzlen;
  72613. }
  72614. else {
  72615. newYaw = boneYaw - Math.PI * .75;
  72616. localTarget.z = Math.cos(newYaw) * xzlen;
  72617. localTarget.x = Math.sin(newYaw) * xzlen;
  72618. }
  72619. }
  72620. }
  72621. if (yaw != newYaw) {
  72622. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72623. localTarget.addInPlace(bonePos);
  72624. target = localTarget;
  72625. }
  72626. }
  72627. }
  72628. var zaxis = BoneLookController._tmpVecs[5];
  72629. var xaxis = BoneLookController._tmpVecs[6];
  72630. var yaxis = BoneLookController._tmpVecs[7];
  72631. var _tmpQuat = BoneLookController._tmpQuat;
  72632. target.subtractToRef(bonePos, zaxis);
  72633. zaxis.normalize();
  72634. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72635. xaxis.normalize();
  72636. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72637. yaxis.normalize();
  72638. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72639. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72640. return;
  72641. }
  72642. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72643. return;
  72644. }
  72645. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72646. return;
  72647. }
  72648. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72649. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72650. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72651. }
  72652. if (this.slerpAmount < 1) {
  72653. if (!this._slerping) {
  72654. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72655. }
  72656. if (this._transformYawPitch) {
  72657. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72658. }
  72659. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72660. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72661. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72662. this._slerping = true;
  72663. }
  72664. else {
  72665. if (this._transformYawPitch) {
  72666. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72667. }
  72668. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72669. this._slerping = false;
  72670. }
  72671. };
  72672. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72673. var angDiff = ang2 - ang1;
  72674. angDiff %= Math.PI * 2;
  72675. if (angDiff > Math.PI) {
  72676. angDiff -= Math.PI * 2;
  72677. }
  72678. else if (angDiff < -Math.PI) {
  72679. angDiff += Math.PI * 2;
  72680. }
  72681. return angDiff;
  72682. };
  72683. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72684. ang1 %= (2 * Math.PI);
  72685. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72686. ang2 %= (2 * Math.PI);
  72687. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72688. var ab = 0;
  72689. if (ang1 < ang2) {
  72690. ab = ang2 - ang1;
  72691. }
  72692. else {
  72693. ab = ang1 - ang2;
  72694. }
  72695. if (ab > Math.PI) {
  72696. ab = Math.PI * 2 - ab;
  72697. }
  72698. return ab;
  72699. };
  72700. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72701. ang %= (2 * Math.PI);
  72702. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72703. ang1 %= (2 * Math.PI);
  72704. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72705. ang2 %= (2 * Math.PI);
  72706. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72707. if (ang1 < ang2) {
  72708. if (ang > ang1 && ang < ang2) {
  72709. return true;
  72710. }
  72711. }
  72712. else {
  72713. if (ang > ang2 && ang < ang1) {
  72714. return true;
  72715. }
  72716. }
  72717. return false;
  72718. };
  72719. 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()];
  72720. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72721. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72722. return BoneLookController;
  72723. }());
  72724. BABYLON.BoneLookController = BoneLookController;
  72725. })(BABYLON || (BABYLON = {}));
  72726. //# sourceMappingURL=babylon.boneLookController.js.map
  72727. var BABYLON;
  72728. (function (BABYLON) {
  72729. var Skeleton = /** @class */ (function () {
  72730. function Skeleton(name, id, scene) {
  72731. this.name = name;
  72732. this.id = id;
  72733. this.bones = new Array();
  72734. this.needInitialSkinMatrix = false;
  72735. this._isDirty = true;
  72736. this._meshesWithPoseMatrix = new Array();
  72737. this._identity = BABYLON.Matrix.Identity();
  72738. this._ranges = {};
  72739. this._lastAbsoluteTransformsUpdateId = -1;
  72740. /**
  72741. * Specifies if the skeleton should be serialized.
  72742. */
  72743. this.doNotSerialize = false;
  72744. // Events
  72745. /**
  72746. * An event triggered before computing the skeleton's matrices
  72747. * @type {BABYLON.Observable}
  72748. */
  72749. this.onBeforeComputeObservable = new BABYLON.Observable();
  72750. this.bones = [];
  72751. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72752. scene.skeletons.push(this);
  72753. //make sure it will recalculate the matrix next time prepare is called.
  72754. this._isDirty = true;
  72755. }
  72756. // Members
  72757. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72758. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72759. return mesh._bonesTransformMatrices;
  72760. }
  72761. if (!this._transformMatrices) {
  72762. this.prepare();
  72763. }
  72764. return this._transformMatrices;
  72765. };
  72766. Skeleton.prototype.getScene = function () {
  72767. return this._scene;
  72768. };
  72769. // Methods
  72770. /**
  72771. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72772. */
  72773. Skeleton.prototype.toString = function (fullDetails) {
  72774. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72775. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72776. if (fullDetails) {
  72777. ret += ", Ranges: {";
  72778. var first = true;
  72779. for (var name_1 in this._ranges) {
  72780. if (first) {
  72781. ret += ", ";
  72782. first = false;
  72783. }
  72784. ret += name_1;
  72785. }
  72786. ret += "}";
  72787. }
  72788. return ret;
  72789. };
  72790. /**
  72791. * Get bone's index searching by name
  72792. * @param {string} name is bone's name to search for
  72793. * @return {number} Indice of the bone. Returns -1 if not found
  72794. */
  72795. Skeleton.prototype.getBoneIndexByName = function (name) {
  72796. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72797. if (this.bones[boneIndex].name === name) {
  72798. return boneIndex;
  72799. }
  72800. }
  72801. return -1;
  72802. };
  72803. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72804. // check name not already in use
  72805. if (!this._ranges[name]) {
  72806. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72807. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72808. if (this.bones[i].animations[0]) {
  72809. this.bones[i].animations[0].createRange(name, from, to);
  72810. }
  72811. }
  72812. }
  72813. };
  72814. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72815. if (deleteFrames === void 0) { deleteFrames = true; }
  72816. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72817. if (this.bones[i].animations[0]) {
  72818. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72819. }
  72820. }
  72821. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72822. };
  72823. Skeleton.prototype.getAnimationRange = function (name) {
  72824. return this._ranges[name];
  72825. };
  72826. /**
  72827. * Returns as an Array, all AnimationRanges defined on this skeleton
  72828. */
  72829. Skeleton.prototype.getAnimationRanges = function () {
  72830. var animationRanges = [];
  72831. var name;
  72832. var i = 0;
  72833. for (name in this._ranges) {
  72834. animationRanges[i] = this._ranges[name];
  72835. i++;
  72836. }
  72837. return animationRanges;
  72838. };
  72839. /**
  72840. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72841. */
  72842. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72843. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72844. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72845. return false;
  72846. }
  72847. var ret = true;
  72848. var frameOffset = this._getHighestAnimationFrame() + 1;
  72849. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72850. var boneDict = {};
  72851. var sourceBones = source.bones;
  72852. var nBones;
  72853. var i;
  72854. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72855. boneDict[sourceBones[i].name] = sourceBones[i];
  72856. }
  72857. if (this.bones.length !== sourceBones.length) {
  72858. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72859. ret = false;
  72860. }
  72861. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72862. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72863. var boneName = this.bones[i].name;
  72864. var sourceBone = boneDict[boneName];
  72865. if (sourceBone) {
  72866. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72867. }
  72868. else {
  72869. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72870. ret = false;
  72871. }
  72872. }
  72873. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72874. var range = source.getAnimationRange(name);
  72875. if (range) {
  72876. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72877. }
  72878. return ret;
  72879. };
  72880. Skeleton.prototype.returnToRest = function () {
  72881. for (var index = 0; index < this.bones.length; index++) {
  72882. this.bones[index].returnToRest();
  72883. }
  72884. };
  72885. Skeleton.prototype._getHighestAnimationFrame = function () {
  72886. var ret = 0;
  72887. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72888. if (this.bones[i].animations[0]) {
  72889. var highest = this.bones[i].animations[0].getHighestFrame();
  72890. if (ret < highest) {
  72891. ret = highest;
  72892. }
  72893. }
  72894. }
  72895. return ret;
  72896. };
  72897. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72898. var range = this.getAnimationRange(name);
  72899. if (!range) {
  72900. return null;
  72901. }
  72902. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72903. };
  72904. Skeleton.prototype._markAsDirty = function () {
  72905. this._isDirty = true;
  72906. };
  72907. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72908. this._meshesWithPoseMatrix.push(mesh);
  72909. };
  72910. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72911. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72912. if (index > -1) {
  72913. this._meshesWithPoseMatrix.splice(index, 1);
  72914. }
  72915. };
  72916. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72917. this.onBeforeComputeObservable.notifyObservers(this);
  72918. for (var index = 0; index < this.bones.length; index++) {
  72919. var bone = this.bones[index];
  72920. var parentBone = bone.getParent();
  72921. if (parentBone) {
  72922. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72923. }
  72924. else {
  72925. if (initialSkinMatrix) {
  72926. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72927. }
  72928. else {
  72929. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72930. }
  72931. }
  72932. if (bone._index !== -1) {
  72933. var mappedIndex = bone._index === null ? index : bone._index;
  72934. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72935. }
  72936. }
  72937. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72938. };
  72939. Skeleton.prototype.prepare = function () {
  72940. if (!this._isDirty) {
  72941. return;
  72942. }
  72943. if (this.needInitialSkinMatrix) {
  72944. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72945. var mesh = this._meshesWithPoseMatrix[index];
  72946. var poseMatrix = mesh.getPoseMatrix();
  72947. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72948. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72949. }
  72950. if (this._synchronizedWithMesh !== mesh) {
  72951. this._synchronizedWithMesh = mesh;
  72952. // Prepare bones
  72953. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72954. var bone = this.bones[boneIndex];
  72955. if (!bone.getParent()) {
  72956. var matrix = bone.getBaseMatrix();
  72957. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72958. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72959. }
  72960. }
  72961. }
  72962. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72963. }
  72964. }
  72965. else {
  72966. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72967. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72968. }
  72969. this._computeTransformMatrices(this._transformMatrices, null);
  72970. }
  72971. this._isDirty = false;
  72972. this._scene._activeBones.addCount(this.bones.length, false);
  72973. };
  72974. Skeleton.prototype.getAnimatables = function () {
  72975. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72976. this._animatables = [];
  72977. for (var index = 0; index < this.bones.length; index++) {
  72978. this._animatables.push(this.bones[index]);
  72979. }
  72980. }
  72981. return this._animatables;
  72982. };
  72983. Skeleton.prototype.clone = function (name, id) {
  72984. var result = new Skeleton(name, id || name, this._scene);
  72985. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72986. for (var index = 0; index < this.bones.length; index++) {
  72987. var source = this.bones[index];
  72988. var parentBone = null;
  72989. var parent_1 = source.getParent();
  72990. if (parent_1) {
  72991. var parentIndex = this.bones.indexOf(parent_1);
  72992. parentBone = result.bones[parentIndex];
  72993. }
  72994. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72995. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72996. }
  72997. if (this._ranges) {
  72998. result._ranges = {};
  72999. for (var rangeName in this._ranges) {
  73000. var range = this._ranges[rangeName];
  73001. if (range) {
  73002. result._ranges[rangeName] = range.clone();
  73003. }
  73004. }
  73005. }
  73006. this._isDirty = true;
  73007. return result;
  73008. };
  73009. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73010. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73011. this.bones.forEach(function (bone) {
  73012. bone.animations.forEach(function (animation) {
  73013. animation.enableBlending = true;
  73014. animation.blendingSpeed = blendingSpeed;
  73015. });
  73016. });
  73017. };
  73018. Skeleton.prototype.dispose = function () {
  73019. this._meshesWithPoseMatrix = [];
  73020. // Animations
  73021. this.getScene().stopAnimation(this);
  73022. // Remove from scene
  73023. this.getScene().removeSkeleton(this);
  73024. };
  73025. Skeleton.prototype.serialize = function () {
  73026. var serializationObject = {};
  73027. serializationObject.name = this.name;
  73028. serializationObject.id = this.id;
  73029. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73030. serializationObject.bones = [];
  73031. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73032. for (var index = 0; index < this.bones.length; index++) {
  73033. var bone = this.bones[index];
  73034. var parent_2 = bone.getParent();
  73035. var serializedBone = {
  73036. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73037. name: bone.name,
  73038. matrix: bone.getBaseMatrix().toArray(),
  73039. rest: bone.getRestPose().toArray()
  73040. };
  73041. serializationObject.bones.push(serializedBone);
  73042. if (bone.length) {
  73043. serializedBone.length = bone.length;
  73044. }
  73045. if (bone.animations && bone.animations.length > 0) {
  73046. serializedBone.animation = bone.animations[0].serialize();
  73047. }
  73048. serializationObject.ranges = [];
  73049. for (var name in this._ranges) {
  73050. var source = this._ranges[name];
  73051. if (!source) {
  73052. continue;
  73053. }
  73054. var range = {};
  73055. range.name = name;
  73056. range.from = source.from;
  73057. range.to = source.to;
  73058. serializationObject.ranges.push(range);
  73059. }
  73060. }
  73061. return serializationObject;
  73062. };
  73063. Skeleton.Parse = function (parsedSkeleton, scene) {
  73064. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73065. if (parsedSkeleton.dimensionsAtRest) {
  73066. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73067. }
  73068. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73069. var index;
  73070. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73071. var parsedBone = parsedSkeleton.bones[index];
  73072. var parentBone = null;
  73073. if (parsedBone.parentBoneIndex > -1) {
  73074. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73075. }
  73076. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73077. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73078. if (parsedBone.length) {
  73079. bone.length = parsedBone.length;
  73080. }
  73081. if (parsedBone.animation) {
  73082. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73083. }
  73084. }
  73085. // placed after bones, so createAnimationRange can cascade down
  73086. if (parsedSkeleton.ranges) {
  73087. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73088. var data = parsedSkeleton.ranges[index];
  73089. skeleton.createAnimationRange(data.name, data.from, data.to);
  73090. }
  73091. }
  73092. return skeleton;
  73093. };
  73094. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73095. if (forceUpdate === void 0) { forceUpdate = false; }
  73096. var renderId = this._scene.getRenderId();
  73097. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73098. this.bones[0].computeAbsoluteTransforms();
  73099. this._lastAbsoluteTransformsUpdateId = renderId;
  73100. }
  73101. };
  73102. Skeleton.prototype.getPoseMatrix = function () {
  73103. var poseMatrix = null;
  73104. if (this._meshesWithPoseMatrix.length > 0) {
  73105. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73106. }
  73107. return poseMatrix;
  73108. };
  73109. Skeleton.prototype.sortBones = function () {
  73110. var bones = new Array();
  73111. var visited = new Array(this.bones.length);
  73112. for (var index = 0; index < this.bones.length; index++) {
  73113. this._sortBones(index, bones, visited);
  73114. }
  73115. this.bones = bones;
  73116. };
  73117. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73118. if (visited[index]) {
  73119. return;
  73120. }
  73121. visited[index] = true;
  73122. var bone = this.bones[index];
  73123. if (bone._index === undefined) {
  73124. bone._index = index;
  73125. }
  73126. var parentBone = bone.getParent();
  73127. if (parentBone) {
  73128. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73129. }
  73130. bones.push(bone);
  73131. };
  73132. return Skeleton;
  73133. }());
  73134. BABYLON.Skeleton = Skeleton;
  73135. })(BABYLON || (BABYLON = {}));
  73136. //# sourceMappingURL=babylon.skeleton.js.map
  73137. var BABYLON;
  73138. (function (BABYLON) {
  73139. var SphericalPolynomial = /** @class */ (function () {
  73140. function SphericalPolynomial() {
  73141. this.x = BABYLON.Vector3.Zero();
  73142. this.y = BABYLON.Vector3.Zero();
  73143. this.z = BABYLON.Vector3.Zero();
  73144. this.xx = BABYLON.Vector3.Zero();
  73145. this.yy = BABYLON.Vector3.Zero();
  73146. this.zz = BABYLON.Vector3.Zero();
  73147. this.xy = BABYLON.Vector3.Zero();
  73148. this.yz = BABYLON.Vector3.Zero();
  73149. this.zx = BABYLON.Vector3.Zero();
  73150. }
  73151. SphericalPolynomial.prototype.addAmbient = function (color) {
  73152. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73153. this.xx = this.xx.add(colorVector);
  73154. this.yy = this.yy.add(colorVector);
  73155. this.zz = this.zz.add(colorVector);
  73156. };
  73157. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73158. var result = new SphericalPolynomial();
  73159. result.x = harmonics.L11.scale(1.02333);
  73160. result.y = harmonics.L1_1.scale(1.02333);
  73161. result.z = harmonics.L10.scale(1.02333);
  73162. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73163. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73164. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73165. result.yz = harmonics.L2_1.scale(0.858086);
  73166. result.zx = harmonics.L21.scale(0.858086);
  73167. result.xy = harmonics.L2_2.scale(0.858086);
  73168. result.scale(1.0 / Math.PI);
  73169. return result;
  73170. };
  73171. SphericalPolynomial.prototype.scale = function (scale) {
  73172. this.x = this.x.scale(scale);
  73173. this.y = this.y.scale(scale);
  73174. this.z = this.z.scale(scale);
  73175. this.xx = this.xx.scale(scale);
  73176. this.yy = this.yy.scale(scale);
  73177. this.zz = this.zz.scale(scale);
  73178. this.yz = this.yz.scale(scale);
  73179. this.zx = this.zx.scale(scale);
  73180. this.xy = this.xy.scale(scale);
  73181. };
  73182. return SphericalPolynomial;
  73183. }());
  73184. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73185. var SphericalHarmonics = /** @class */ (function () {
  73186. function SphericalHarmonics() {
  73187. this.L00 = BABYLON.Vector3.Zero();
  73188. this.L1_1 = BABYLON.Vector3.Zero();
  73189. this.L10 = BABYLON.Vector3.Zero();
  73190. this.L11 = BABYLON.Vector3.Zero();
  73191. this.L2_2 = BABYLON.Vector3.Zero();
  73192. this.L2_1 = BABYLON.Vector3.Zero();
  73193. this.L20 = BABYLON.Vector3.Zero();
  73194. this.L21 = BABYLON.Vector3.Zero();
  73195. this.L22 = BABYLON.Vector3.Zero();
  73196. }
  73197. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73198. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73199. var c = colorVector.scale(deltaSolidAngle);
  73200. this.L00 = this.L00.add(c.scale(0.282095));
  73201. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73202. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73203. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73204. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73205. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73206. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73207. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73208. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73209. };
  73210. SphericalHarmonics.prototype.scale = function (scale) {
  73211. this.L00 = this.L00.scale(scale);
  73212. this.L1_1 = this.L1_1.scale(scale);
  73213. this.L10 = this.L10.scale(scale);
  73214. this.L11 = this.L11.scale(scale);
  73215. this.L2_2 = this.L2_2.scale(scale);
  73216. this.L2_1 = this.L2_1.scale(scale);
  73217. this.L20 = this.L20.scale(scale);
  73218. this.L21 = this.L21.scale(scale);
  73219. this.L22 = this.L22.scale(scale);
  73220. };
  73221. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73222. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73223. //
  73224. // E_lm = A_l * L_lm
  73225. //
  73226. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73227. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73228. // the scaling factors are given in equation 9.
  73229. // Constant (Band 0)
  73230. this.L00 = this.L00.scale(3.141593);
  73231. // Linear (Band 1)
  73232. this.L1_1 = this.L1_1.scale(2.094395);
  73233. this.L10 = this.L10.scale(2.094395);
  73234. this.L11 = this.L11.scale(2.094395);
  73235. // Quadratic (Band 2)
  73236. this.L2_2 = this.L2_2.scale(0.785398);
  73237. this.L2_1 = this.L2_1.scale(0.785398);
  73238. this.L20 = this.L20.scale(0.785398);
  73239. this.L21 = this.L21.scale(0.785398);
  73240. this.L22 = this.L22.scale(0.785398);
  73241. };
  73242. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73243. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73244. // L = (1/pi) * E * rho
  73245. //
  73246. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73247. this.scale(1.0 / Math.PI);
  73248. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73249. // (The pixel shader must apply albedo after texture fetches, etc).
  73250. };
  73251. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73252. var result = new SphericalHarmonics();
  73253. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73254. result.L1_1 = polynomial.y.scale(0.977204);
  73255. result.L10 = polynomial.z.scale(0.977204);
  73256. result.L11 = polynomial.x.scale(0.977204);
  73257. result.L2_2 = polynomial.xy.scale(1.16538);
  73258. result.L2_1 = polynomial.yz.scale(1.16538);
  73259. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73260. result.L21 = polynomial.zx.scale(1.16538);
  73261. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73262. result.scale(Math.PI);
  73263. return result;
  73264. };
  73265. return SphericalHarmonics;
  73266. }());
  73267. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73268. })(BABYLON || (BABYLON = {}));
  73269. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73270. var BABYLON;
  73271. (function (BABYLON) {
  73272. var FileFaceOrientation = /** @class */ (function () {
  73273. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73274. this.name = name;
  73275. this.worldAxisForNormal = worldAxisForNormal;
  73276. this.worldAxisForFileX = worldAxisForFileX;
  73277. this.worldAxisForFileY = worldAxisForFileY;
  73278. }
  73279. return FileFaceOrientation;
  73280. }());
  73281. ;
  73282. /**
  73283. * Helper class dealing with the extraction of spherical polynomial dataArray
  73284. * from a cube map.
  73285. */
  73286. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73287. function CubeMapToSphericalPolynomialTools() {
  73288. }
  73289. /**
  73290. * Converts a texture to the according Spherical Polynomial data.
  73291. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73292. *
  73293. * @param texture The texture to extract the information from.
  73294. * @return The Spherical Polynomial data.
  73295. */
  73296. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73297. if (!texture.isCube) {
  73298. // Only supports cube Textures currently.
  73299. return null;
  73300. }
  73301. var size = texture.getSize().width;
  73302. var right = texture.readPixels(0);
  73303. var left = texture.readPixels(1);
  73304. var up;
  73305. var down;
  73306. if (texture.isRenderTarget) {
  73307. up = texture.readPixels(3);
  73308. down = texture.readPixels(2);
  73309. }
  73310. else {
  73311. up = texture.readPixels(2);
  73312. down = texture.readPixels(3);
  73313. }
  73314. var front = texture.readPixels(4);
  73315. var back = texture.readPixels(5);
  73316. var gammaSpace = texture.gammaSpace;
  73317. // Always read as RGBA.
  73318. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73319. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73320. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73321. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73322. }
  73323. var cubeInfo = {
  73324. size: size,
  73325. right: right,
  73326. left: left,
  73327. up: up,
  73328. down: down,
  73329. front: front,
  73330. back: back,
  73331. format: format,
  73332. type: type,
  73333. gammaSpace: gammaSpace,
  73334. };
  73335. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73336. };
  73337. /**
  73338. * Converts a cubemap to the according Spherical Polynomial data.
  73339. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73340. *
  73341. * @param cubeInfo The Cube map to extract the information from.
  73342. * @return The Spherical Polynomial data.
  73343. */
  73344. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73345. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73346. var totalSolidAngle = 0.0;
  73347. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73348. var du = 2.0 / cubeInfo.size;
  73349. var dv = du;
  73350. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73351. var minUV = du * 0.5 - 1.0;
  73352. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73353. var fileFace = this.FileFaces[faceIndex];
  73354. var dataArray = cubeInfo[fileFace.name];
  73355. var v = minUV;
  73356. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73357. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73358. // Because SP is still linear, so summation is fine in that basis.
  73359. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73360. for (var y = 0; y < cubeInfo.size; y++) {
  73361. var u = minUV;
  73362. for (var x = 0; x < cubeInfo.size; x++) {
  73363. // World direction (not normalised)
  73364. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73365. worldDirection.normalize();
  73366. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73367. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73368. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73369. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73370. // Handle Integer types.
  73371. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73372. r /= 255;
  73373. g /= 255;
  73374. b /= 255;
  73375. }
  73376. // Handle Gamma space textures.
  73377. if (cubeInfo.gammaSpace) {
  73378. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73379. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73380. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73381. }
  73382. var color = new BABYLON.Color3(r, g, b);
  73383. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73384. totalSolidAngle += deltaSolidAngle;
  73385. u += du;
  73386. }
  73387. v += dv;
  73388. }
  73389. }
  73390. // Solid angle for entire sphere is 4*pi
  73391. var sphereSolidAngle = 4.0 * Math.PI;
  73392. // Adjust the solid angle to allow for how many faces we processed.
  73393. var facesProcessed = 6.0;
  73394. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73395. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73396. // This is needed because the numerical integration over the cube uses a
  73397. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73398. // and also to compensate for accumulative error due to float precision in the summation.
  73399. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73400. sphericalHarmonics.scale(correctionFactor);
  73401. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73402. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73403. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73404. };
  73405. CubeMapToSphericalPolynomialTools.FileFaces = [
  73406. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73407. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73408. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73409. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73410. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73411. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73412. ];
  73413. return CubeMapToSphericalPolynomialTools;
  73414. }());
  73415. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73416. })(BABYLON || (BABYLON = {}));
  73417. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73418. var BABYLON;
  73419. (function (BABYLON) {
  73420. /**
  73421. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73422. */
  73423. var PanoramaToCubeMapTools = /** @class */ (function () {
  73424. function PanoramaToCubeMapTools() {
  73425. }
  73426. /**
  73427. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73428. *
  73429. * @param float32Array The source data.
  73430. * @param inputWidth The width of the input panorama.
  73431. * @param inputhHeight The height of the input panorama.
  73432. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73433. * @return The cubemap data
  73434. */
  73435. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73436. if (!float32Array) {
  73437. throw "ConvertPanoramaToCubemap: input cannot be null";
  73438. }
  73439. if (float32Array.length != inputWidth * inputHeight * 3) {
  73440. throw "ConvertPanoramaToCubemap: input size is wrong";
  73441. }
  73442. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73443. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73444. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73445. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73446. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73447. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73448. return {
  73449. front: textureFront,
  73450. back: textureBack,
  73451. left: textureLeft,
  73452. right: textureRight,
  73453. up: textureUp,
  73454. down: textureDown,
  73455. size: size,
  73456. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73457. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73458. gammaSpace: false,
  73459. };
  73460. };
  73461. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73462. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73463. var textureArray = new Float32Array(buffer);
  73464. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73465. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73466. var dy = 1 / texSize;
  73467. var fy = 0;
  73468. for (var y = 0; y < texSize; y++) {
  73469. var xv1 = faceData[0];
  73470. var xv2 = faceData[2];
  73471. for (var x = 0; x < texSize; x++) {
  73472. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73473. v.normalize();
  73474. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73475. // 3 channels per pixels
  73476. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73477. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73478. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73479. xv1 = xv1.add(rotDX1);
  73480. xv2 = xv2.add(rotDX2);
  73481. }
  73482. fy += dy;
  73483. }
  73484. return textureArray;
  73485. };
  73486. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73487. var theta = Math.atan2(vDir.z, vDir.x);
  73488. var phi = Math.acos(vDir.y);
  73489. while (theta < -Math.PI)
  73490. theta += 2 * Math.PI;
  73491. while (theta > Math.PI)
  73492. theta -= 2 * Math.PI;
  73493. var dx = theta / Math.PI;
  73494. var dy = phi / Math.PI;
  73495. // recenter.
  73496. dx = dx * 0.5 + 0.5;
  73497. var px = Math.round(dx * inputWidth);
  73498. if (px < 0)
  73499. px = 0;
  73500. else if (px >= inputWidth)
  73501. px = inputWidth - 1;
  73502. var py = Math.round(dy * inputHeight);
  73503. if (py < 0)
  73504. py = 0;
  73505. else if (py >= inputHeight)
  73506. py = inputHeight - 1;
  73507. var inputY = (inputHeight - py - 1);
  73508. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73509. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73510. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73511. return {
  73512. r: r,
  73513. g: g,
  73514. b: b
  73515. };
  73516. };
  73517. PanoramaToCubeMapTools.FACE_FRONT = [
  73518. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73519. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73520. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73521. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73522. ];
  73523. PanoramaToCubeMapTools.FACE_BACK = [
  73524. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73525. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73526. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73527. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73528. ];
  73529. PanoramaToCubeMapTools.FACE_RIGHT = [
  73530. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73531. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73532. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73533. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73534. ];
  73535. PanoramaToCubeMapTools.FACE_LEFT = [
  73536. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73537. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73538. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73539. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73540. ];
  73541. PanoramaToCubeMapTools.FACE_DOWN = [
  73542. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73543. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73544. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73545. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73546. ];
  73547. PanoramaToCubeMapTools.FACE_UP = [
  73548. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73549. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73550. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73551. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73552. ];
  73553. return PanoramaToCubeMapTools;
  73554. }());
  73555. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73556. })(BABYLON || (BABYLON = {}));
  73557. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73558. var BABYLON;
  73559. (function (BABYLON) {
  73560. ;
  73561. /**
  73562. * This groups tools to convert HDR texture to native colors array.
  73563. */
  73564. var HDRTools = /** @class */ (function () {
  73565. function HDRTools() {
  73566. }
  73567. HDRTools.Ldexp = function (mantissa, exponent) {
  73568. if (exponent > 1023) {
  73569. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73570. }
  73571. if (exponent < -1074) {
  73572. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73573. }
  73574. return mantissa * Math.pow(2, exponent);
  73575. };
  73576. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73577. if (exponent > 0) {
  73578. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73579. float32array[index + 0] = red * exponent;
  73580. float32array[index + 1] = green * exponent;
  73581. float32array[index + 2] = blue * exponent;
  73582. }
  73583. else {
  73584. float32array[index + 0] = 0;
  73585. float32array[index + 1] = 0;
  73586. float32array[index + 2] = 0;
  73587. }
  73588. };
  73589. HDRTools.readStringLine = function (uint8array, startIndex) {
  73590. var line = "";
  73591. var character = "";
  73592. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73593. character = String.fromCharCode(uint8array[i]);
  73594. if (character == "\n") {
  73595. break;
  73596. }
  73597. line += character;
  73598. }
  73599. return line;
  73600. };
  73601. /**
  73602. * Reads header information from an RGBE texture stored in a native array.
  73603. * More information on this format are available here:
  73604. * https://en.wikipedia.org/wiki/RGBE_image_format
  73605. *
  73606. * @param uint8array The binary file stored in native array.
  73607. * @return The header information.
  73608. */
  73609. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73610. var height = 0;
  73611. var width = 0;
  73612. var line = this.readStringLine(uint8array, 0);
  73613. if (line[0] != '#' || line[1] != '?') {
  73614. throw "Bad HDR Format.";
  73615. }
  73616. var endOfHeader = false;
  73617. var findFormat = false;
  73618. var lineIndex = 0;
  73619. do {
  73620. lineIndex += (line.length + 1);
  73621. line = this.readStringLine(uint8array, lineIndex);
  73622. if (line == "FORMAT=32-bit_rle_rgbe") {
  73623. findFormat = true;
  73624. }
  73625. else if (line.length == 0) {
  73626. endOfHeader = true;
  73627. }
  73628. } while (!endOfHeader);
  73629. if (!findFormat) {
  73630. throw "HDR Bad header format, unsupported FORMAT";
  73631. }
  73632. lineIndex += (line.length + 1);
  73633. line = this.readStringLine(uint8array, lineIndex);
  73634. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73635. var match = sizeRegexp.exec(line);
  73636. // TODO. Support +Y and -X if needed.
  73637. if (!match || match.length < 3) {
  73638. throw "HDR Bad header format, no size";
  73639. }
  73640. width = parseInt(match[2]);
  73641. height = parseInt(match[1]);
  73642. if (width < 8 || width > 0x7fff) {
  73643. throw "HDR Bad header format, unsupported size";
  73644. }
  73645. lineIndex += (line.length + 1);
  73646. return {
  73647. height: height,
  73648. width: width,
  73649. dataPosition: lineIndex
  73650. };
  73651. };
  73652. /**
  73653. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73654. * This RGBE texture needs to store the information as a panorama.
  73655. *
  73656. * More information on this format are available here:
  73657. * https://en.wikipedia.org/wiki/RGBE_image_format
  73658. *
  73659. * @param buffer The binary file stored in an array buffer.
  73660. * @param size The expected size of the extracted cubemap.
  73661. * @return The Cube Map information.
  73662. */
  73663. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73664. var uint8array = new Uint8Array(buffer);
  73665. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73666. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73667. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73668. return cubeMapData;
  73669. };
  73670. /**
  73671. * Returns the pixels data extracted from an RGBE texture.
  73672. * This pixels will be stored left to right up to down in the R G B order in one array.
  73673. *
  73674. * More information on this format are available here:
  73675. * https://en.wikipedia.org/wiki/RGBE_image_format
  73676. *
  73677. * @param uint8array The binary file stored in an array buffer.
  73678. * @param hdrInfo The header information of the file.
  73679. * @return The pixels data in RGB right to left up to down order.
  73680. */
  73681. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73682. // Keep for multi format supports.
  73683. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73684. };
  73685. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73686. var num_scanlines = hdrInfo.height;
  73687. var scanline_width = hdrInfo.width;
  73688. var a, b, c, d, count;
  73689. var dataIndex = hdrInfo.dataPosition;
  73690. var index = 0, endIndex = 0, i = 0;
  73691. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73692. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73693. // 3 channels of 4 bytes per pixel in float.
  73694. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73695. var resultArray = new Float32Array(resultBuffer);
  73696. // read in each successive scanline
  73697. while (num_scanlines > 0) {
  73698. a = uint8array[dataIndex++];
  73699. b = uint8array[dataIndex++];
  73700. c = uint8array[dataIndex++];
  73701. d = uint8array[dataIndex++];
  73702. if (a != 2 || b != 2 || (c & 0x80)) {
  73703. // this file is not run length encoded
  73704. throw "HDR Bad header format, not RLE";
  73705. }
  73706. if (((c << 8) | d) != scanline_width) {
  73707. throw "HDR Bad header format, wrong scan line width";
  73708. }
  73709. index = 0;
  73710. // read each of the four channels for the scanline into the buffer
  73711. for (i = 0; i < 4; i++) {
  73712. endIndex = (i + 1) * scanline_width;
  73713. while (index < endIndex) {
  73714. a = uint8array[dataIndex++];
  73715. b = uint8array[dataIndex++];
  73716. if (a > 128) {
  73717. // a run of the same value
  73718. count = a - 128;
  73719. if ((count == 0) || (count > endIndex - index)) {
  73720. throw "HDR Bad Format, bad scanline data (run)";
  73721. }
  73722. while (count-- > 0) {
  73723. scanLineArray[index++] = b;
  73724. }
  73725. }
  73726. else {
  73727. // a non-run
  73728. count = a;
  73729. if ((count == 0) || (count > endIndex - index)) {
  73730. throw "HDR Bad Format, bad scanline data (non-run)";
  73731. }
  73732. scanLineArray[index++] = b;
  73733. if (--count > 0) {
  73734. for (var j = 0; j < count; j++) {
  73735. scanLineArray[index++] = uint8array[dataIndex++];
  73736. }
  73737. }
  73738. }
  73739. }
  73740. }
  73741. // now convert data from buffer into floats
  73742. for (i = 0; i < scanline_width; i++) {
  73743. a = scanLineArray[i];
  73744. b = scanLineArray[i + scanline_width];
  73745. c = scanLineArray[i + 2 * scanline_width];
  73746. d = scanLineArray[i + 3 * scanline_width];
  73747. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73748. }
  73749. num_scanlines--;
  73750. }
  73751. return resultArray;
  73752. };
  73753. return HDRTools;
  73754. }());
  73755. BABYLON.HDRTools = HDRTools;
  73756. })(BABYLON || (BABYLON = {}));
  73757. //# sourceMappingURL=babylon.hdr.js.map
  73758. var BABYLON;
  73759. (function (BABYLON) {
  73760. /**
  73761. * This represents a texture coming from an HDR input.
  73762. *
  73763. * The only supported format is currently panorama picture stored in RGBE format.
  73764. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73765. */
  73766. var HDRCubeTexture = /** @class */ (function (_super) {
  73767. __extends(HDRCubeTexture, _super);
  73768. /**
  73769. * Instantiates an HDRTexture from the following parameters.
  73770. *
  73771. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73772. * @param scene The scene the texture will be used in
  73773. * @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.
  73774. * @param noMipmap Forces to not generate the mipmap if true
  73775. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73776. * @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)
  73777. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73778. */
  73779. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73780. if (noMipmap === void 0) { noMipmap = false; }
  73781. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73782. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73783. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73784. if (onLoad === void 0) { onLoad = null; }
  73785. if (onError === void 0) { onError = null; }
  73786. var _this = _super.call(this, scene) || this;
  73787. _this._useInGammaSpace = false;
  73788. _this._generateHarmonics = true;
  73789. _this._isBABYLONPreprocessed = false;
  73790. _this._onLoad = null;
  73791. _this._onError = null;
  73792. /**
  73793. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73794. */
  73795. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73796. /**
  73797. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73798. * This is usefull at run time to apply the good shader.
  73799. */
  73800. _this.isPMREM = false;
  73801. _this._isBlocking = true;
  73802. /**
  73803. * Gets or sets the center of the bounding box associated with the cube texture
  73804. * It must define where the camera used to render the texture was set
  73805. */
  73806. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73807. if (!url) {
  73808. return _this;
  73809. }
  73810. _this.name = url;
  73811. _this.url = url;
  73812. _this.hasAlpha = false;
  73813. _this.isCube = true;
  73814. _this._textureMatrix = BABYLON.Matrix.Identity();
  73815. _this._onLoad = onLoad;
  73816. _this._onError = onError;
  73817. _this.gammaSpace = false;
  73818. var caps = scene.getEngine().getCaps();
  73819. if (size) {
  73820. _this._isBABYLONPreprocessed = false;
  73821. _this._noMipmap = noMipmap;
  73822. _this._size = size;
  73823. _this._useInGammaSpace = useInGammaSpace;
  73824. _this._usePMREMGenerator = usePMREMGenerator &&
  73825. caps.textureLOD &&
  73826. caps.textureFloat &&
  73827. !_this._useInGammaSpace;
  73828. }
  73829. else {
  73830. _this._isBABYLONPreprocessed = true;
  73831. _this._noMipmap = false;
  73832. _this._useInGammaSpace = false;
  73833. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73834. !_this._useInGammaSpace;
  73835. }
  73836. _this.isPMREM = _this._usePMREMGenerator;
  73837. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73838. if (!_this._texture) {
  73839. if (!scene.useDelayedTextureLoading) {
  73840. _this.loadTexture();
  73841. }
  73842. else {
  73843. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73844. }
  73845. }
  73846. return _this;
  73847. }
  73848. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73849. /**
  73850. * Gets wether or not the texture is blocking during loading.
  73851. */
  73852. get: function () {
  73853. return this._isBlocking;
  73854. },
  73855. /**
  73856. * Sets wether or not the texture is blocking during loading.
  73857. */
  73858. set: function (value) {
  73859. this._isBlocking = value;
  73860. },
  73861. enumerable: true,
  73862. configurable: true
  73863. });
  73864. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73865. get: function () {
  73866. return this._boundingBoxSize;
  73867. },
  73868. /**
  73869. * Gets or sets the size of the bounding box associated with the cube texture
  73870. * When defined, the cubemap will switch to local mode
  73871. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73872. * @example https://www.babylonjs-playground.com/#RNASML
  73873. */
  73874. set: function (value) {
  73875. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73876. return;
  73877. }
  73878. this._boundingBoxSize = value;
  73879. var scene = this.getScene();
  73880. if (scene) {
  73881. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73882. }
  73883. },
  73884. enumerable: true,
  73885. configurable: true
  73886. });
  73887. /**
  73888. * Occurs when the file is a preprocessed .babylon.hdr file.
  73889. */
  73890. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73891. var _this = this;
  73892. var mipLevels = 0;
  73893. var floatArrayView = null;
  73894. var scene = this.getScene();
  73895. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73896. var mips = new Array();
  73897. if (!floatArrayView) {
  73898. return mips;
  73899. }
  73900. var startIndex = 30;
  73901. for (var level = 0; level < mipLevels; level++) {
  73902. mips.push([]);
  73903. // Fill each pixel of the mip level.
  73904. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73905. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73906. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73907. mips[level].push(faceData);
  73908. startIndex += faceSize;
  73909. }
  73910. }
  73911. return mips;
  73912. } : null;
  73913. var callback = function (buffer) {
  73914. var scene = _this.getScene();
  73915. if (!scene) {
  73916. return null;
  73917. }
  73918. // Create Native Array Views
  73919. var intArrayView = new Int32Array(buffer);
  73920. floatArrayView = new Float32Array(buffer);
  73921. // Fill header.
  73922. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73923. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73924. // Update Texture Information.
  73925. if (!_this._texture) {
  73926. return null;
  73927. }
  73928. _this._texture.updateSize(_this._size, _this._size);
  73929. // Fill polynomial information.
  73930. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73931. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73932. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73933. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73934. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73935. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73936. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73937. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73938. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73939. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73940. _this.sphericalPolynomial = sphericalPolynomial;
  73941. // Fill pixel data.
  73942. mipLevels = intArrayView[29]; // Number of mip levels.
  73943. var startIndex = 30;
  73944. var data = [];
  73945. var faceSize = Math.pow(_this._size, 2) * 3;
  73946. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73947. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73948. startIndex += faceSize;
  73949. }
  73950. var results = [];
  73951. var byteArray = null;
  73952. // Push each faces.
  73953. for (var k = 0; k < 6; k++) {
  73954. var dataFace = null;
  73955. // To be deprecated.
  73956. if (version === 1) {
  73957. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73958. dataFace = data[j];
  73959. }
  73960. // If special cases.
  73961. if (!mipmapGenerator && dataFace) {
  73962. if (!scene.getEngine().getCaps().textureFloat) {
  73963. // 3 channels of 1 bytes per pixel in bytes.
  73964. var byteBuffer = new ArrayBuffer(faceSize);
  73965. byteArray = new Uint8Array(byteBuffer);
  73966. }
  73967. for (var i = 0; i < _this._size * _this._size; i++) {
  73968. // Put in gamma space if requested.
  73969. if (_this._useInGammaSpace) {
  73970. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73971. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73972. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73973. }
  73974. // Convert to int texture for fallback.
  73975. if (byteArray) {
  73976. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73977. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73978. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73979. // May use luminance instead if the result is not accurate.
  73980. var max = Math.max(Math.max(r, g), b);
  73981. if (max > 255) {
  73982. var scale = 255 / max;
  73983. r *= scale;
  73984. g *= scale;
  73985. b *= scale;
  73986. }
  73987. byteArray[(i * 3) + 0] = r;
  73988. byteArray[(i * 3) + 1] = g;
  73989. byteArray[(i * 3) + 2] = b;
  73990. }
  73991. }
  73992. }
  73993. // Fill the array accordingly.
  73994. if (byteArray) {
  73995. results.push(byteArray);
  73996. }
  73997. else {
  73998. results.push(dataFace);
  73999. }
  74000. }
  74001. return results;
  74002. };
  74003. if (scene) {
  74004. 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);
  74005. }
  74006. };
  74007. /**
  74008. * Occurs when the file is raw .hdr file.
  74009. */
  74010. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74011. var _this = this;
  74012. var callback = function (buffer) {
  74013. var scene = _this.getScene();
  74014. if (!scene) {
  74015. return null;
  74016. }
  74017. // Extract the raw linear data.
  74018. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74019. // Generate harmonics if needed.
  74020. if (_this._generateHarmonics) {
  74021. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74022. _this.sphericalPolynomial = sphericalPolynomial;
  74023. }
  74024. var results = [];
  74025. var byteArray = null;
  74026. // Push each faces.
  74027. for (var j = 0; j < 6; j++) {
  74028. // Create uintarray fallback.
  74029. if (!scene.getEngine().getCaps().textureFloat) {
  74030. // 3 channels of 1 bytes per pixel in bytes.
  74031. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74032. byteArray = new Uint8Array(byteBuffer);
  74033. }
  74034. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74035. // If special cases.
  74036. if (_this._useInGammaSpace || byteArray) {
  74037. for (var i = 0; i < _this._size * _this._size; i++) {
  74038. // Put in gamma space if requested.
  74039. if (_this._useInGammaSpace) {
  74040. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74041. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74042. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74043. }
  74044. // Convert to int texture for fallback.
  74045. if (byteArray) {
  74046. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74047. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74048. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74049. // May use luminance instead if the result is not accurate.
  74050. var max = Math.max(Math.max(r, g), b);
  74051. if (max > 255) {
  74052. var scale = 255 / max;
  74053. r *= scale;
  74054. g *= scale;
  74055. b *= scale;
  74056. }
  74057. byteArray[(i * 3) + 0] = r;
  74058. byteArray[(i * 3) + 1] = g;
  74059. byteArray[(i * 3) + 2] = b;
  74060. }
  74061. }
  74062. }
  74063. if (byteArray) {
  74064. results.push(byteArray);
  74065. }
  74066. else {
  74067. results.push(dataFace);
  74068. }
  74069. }
  74070. return results;
  74071. };
  74072. var mipmapGenerator = null;
  74073. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74074. // if (!this._noMipmap &&
  74075. // this._usePMREMGenerator) {
  74076. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74077. // // Custom setup of the generator matching with the PBR shader values.
  74078. // var generator = new BABYLON.PMREMGenerator(data,
  74079. // this._size,
  74080. // this._size,
  74081. // 0,
  74082. // 3,
  74083. // this.getScene().getEngine().getCaps().textureFloat,
  74084. // 2048,
  74085. // 0.25,
  74086. // false,
  74087. // true);
  74088. // return generator.filterCubeMap();
  74089. // };
  74090. // }
  74091. var scene = this.getScene();
  74092. if (scene) {
  74093. 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);
  74094. }
  74095. };
  74096. /**
  74097. * Starts the loading process of the texture.
  74098. */
  74099. HDRCubeTexture.prototype.loadTexture = function () {
  74100. if (this._isBABYLONPreprocessed) {
  74101. this.loadBabylonTexture();
  74102. }
  74103. else {
  74104. this.loadHDRTexture();
  74105. }
  74106. };
  74107. HDRCubeTexture.prototype.clone = function () {
  74108. var scene = this.getScene();
  74109. if (!scene) {
  74110. return this;
  74111. }
  74112. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74113. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74114. // Base texture
  74115. newTexture.level = this.level;
  74116. newTexture.wrapU = this.wrapU;
  74117. newTexture.wrapV = this.wrapV;
  74118. newTexture.coordinatesIndex = this.coordinatesIndex;
  74119. newTexture.coordinatesMode = this.coordinatesMode;
  74120. return newTexture;
  74121. };
  74122. // Methods
  74123. HDRCubeTexture.prototype.delayLoad = function () {
  74124. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74125. return;
  74126. }
  74127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74128. this._texture = this._getFromCache(this.url, this._noMipmap);
  74129. if (!this._texture) {
  74130. this.loadTexture();
  74131. }
  74132. };
  74133. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74134. return this._textureMatrix;
  74135. };
  74136. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74137. this._textureMatrix = value;
  74138. };
  74139. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74140. var texture = null;
  74141. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74142. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74143. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74144. texture.name = parsedTexture.name;
  74145. texture.hasAlpha = parsedTexture.hasAlpha;
  74146. texture.level = parsedTexture.level;
  74147. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74148. texture.isBlocking = parsedTexture.isBlocking;
  74149. }
  74150. if (texture) {
  74151. if (parsedTexture.boundingBoxPosition) {
  74152. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74153. }
  74154. if (parsedTexture.boundingBoxSize) {
  74155. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74156. }
  74157. }
  74158. return texture;
  74159. };
  74160. HDRCubeTexture.prototype.serialize = function () {
  74161. if (!this.name) {
  74162. return null;
  74163. }
  74164. var serializationObject = {};
  74165. serializationObject.name = this.name;
  74166. serializationObject.hasAlpha = this.hasAlpha;
  74167. serializationObject.isCube = true;
  74168. serializationObject.level = this.level;
  74169. serializationObject.size = this._size;
  74170. serializationObject.coordinatesMode = this.coordinatesMode;
  74171. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74172. serializationObject.generateHarmonics = this._generateHarmonics;
  74173. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74174. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74175. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74176. serializationObject.noMipmap = this._noMipmap;
  74177. serializationObject.isBlocking = this._isBlocking;
  74178. return serializationObject;
  74179. };
  74180. /**
  74181. * Saves as a file the data contained in the texture in a binary format.
  74182. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74183. * as the spherical used in the lighting.
  74184. * @param url The HDR file url.
  74185. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74186. * @param onError Method called if any error happens during download.
  74187. * @return The packed binary data.
  74188. */
  74189. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74190. if (onError === void 0) { onError = null; }
  74191. var callback = function (buffer) {
  74192. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74193. // Returns a URL you can use as a href.
  74194. var objUrl = window.URL.createObjectURL(data);
  74195. // Simulates a link to it and click to dowload.
  74196. var a = document.createElement("a");
  74197. document.body.appendChild(a);
  74198. a.style.display = "none";
  74199. a.href = objUrl;
  74200. a.download = "envmap.babylon.hdr";
  74201. a.click();
  74202. };
  74203. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74204. };
  74205. /**
  74206. * Serializes the data contained in the texture in a binary format.
  74207. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74208. * as the spherical used in the lighting.
  74209. * @param url The HDR file url.
  74210. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74211. * @param onError Method called if any error happens during download.
  74212. * @return The packed binary data.
  74213. */
  74214. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74215. if (onError === void 0) { onError = null; }
  74216. // Needs the url tho create the texture.
  74217. if (!url) {
  74218. return;
  74219. }
  74220. // Check Power of two size.
  74221. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74222. return;
  74223. }
  74224. // Coming Back in 3.x.
  74225. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74226. };
  74227. HDRCubeTexture._facesMapping = [
  74228. "right",
  74229. "left",
  74230. "up",
  74231. "down",
  74232. "front",
  74233. "back"
  74234. ];
  74235. return HDRCubeTexture;
  74236. }(BABYLON.BaseTexture));
  74237. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74238. })(BABYLON || (BABYLON = {}));
  74239. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74240. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74241. // Huge respect for a such great lib.
  74242. // Earcut license:
  74243. // Copyright (c) 2016, Mapbox
  74244. //
  74245. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74246. // with or without fee is hereby granted, provided that the above copyright notice
  74247. // and this permission notice appear in all copies.
  74248. //
  74249. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74250. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74251. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74252. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74253. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74254. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74255. // THIS SOFTWARE.
  74256. var Earcut;
  74257. (function (Earcut) {
  74258. /**
  74259. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74260. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74261. * @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).
  74262. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74263. */
  74264. function earcut(data, holeIndices, dim) {
  74265. dim = dim || 2;
  74266. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74267. if (!outerNode)
  74268. return triangles;
  74269. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74270. if (hasHoles)
  74271. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74272. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74273. if (data.length > 80 * dim) {
  74274. minX = maxX = data[0];
  74275. minY = maxY = data[1];
  74276. for (var i = dim; i < outerLen; i += dim) {
  74277. x = data[i];
  74278. y = data[i + 1];
  74279. if (x < minX)
  74280. minX = x;
  74281. if (y < minY)
  74282. minY = y;
  74283. if (x > maxX)
  74284. maxX = x;
  74285. if (y > maxY)
  74286. maxY = y;
  74287. }
  74288. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74289. size = Math.max(maxX - minX, maxY - minY);
  74290. }
  74291. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74292. return triangles;
  74293. }
  74294. Earcut.earcut = earcut;
  74295. var Node = /** @class */ (function () {
  74296. function Node(i, x, y) {
  74297. this.i = i;
  74298. this.x = x;
  74299. this.y = y;
  74300. this.prev = null;
  74301. this.next = null;
  74302. this.z = null;
  74303. this.prevZ = null;
  74304. this.nextZ = null;
  74305. this.steiner = false;
  74306. }
  74307. return Node;
  74308. }());
  74309. // create a circular doubly linked list from polygon points in the specified winding order
  74310. function linkedList(data, start, end, dim, clockwise) {
  74311. var i, last = null;
  74312. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74313. for (i = start; i < end; i += dim)
  74314. last = insertNode(i, data[i], data[i + 1], last);
  74315. }
  74316. else {
  74317. for (i = end - dim; i >= start; i -= dim)
  74318. last = insertNode(i, data[i], data[i + 1], last);
  74319. }
  74320. if (last && equals(last, last.next)) {
  74321. removeNode(last);
  74322. last = last.next;
  74323. }
  74324. return last;
  74325. }
  74326. // eliminate colinear or duplicate points
  74327. function filterPoints(start, end) {
  74328. if (!start)
  74329. return start;
  74330. if (!end)
  74331. end = start;
  74332. var p = start, again;
  74333. do {
  74334. again = false;
  74335. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74336. removeNode(p);
  74337. p = end = p.prev;
  74338. if (p === p.next)
  74339. return undefined;
  74340. again = true;
  74341. }
  74342. else {
  74343. p = p.next;
  74344. }
  74345. } while (again || p !== end);
  74346. return end;
  74347. }
  74348. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74349. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74350. if (!ear)
  74351. return;
  74352. // interlink polygon nodes in z-order
  74353. if (!pass && size)
  74354. indexCurve(ear, minX, minY, size);
  74355. var stop = ear, prev, next;
  74356. // iterate through ears, slicing them one by one
  74357. while (ear.prev !== ear.next) {
  74358. prev = ear.prev;
  74359. next = ear.next;
  74360. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74361. // cut off the triangle
  74362. triangles.push(prev.i / dim);
  74363. triangles.push(ear.i / dim);
  74364. triangles.push(next.i / dim);
  74365. removeNode(ear);
  74366. // skipping the next vertice leads to less sliver triangles
  74367. ear = next.next;
  74368. stop = next.next;
  74369. continue;
  74370. }
  74371. ear = next;
  74372. // if we looped through the whole remaining polygon and can't find any more ears
  74373. if (ear === stop) {
  74374. // try filtering points and slicing again
  74375. if (!pass) {
  74376. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74377. // if this didn't work, try curing all small self-intersections locally
  74378. }
  74379. else if (pass === 1) {
  74380. ear = cureLocalIntersections(ear, triangles, dim);
  74381. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74382. // as a last resort, try splitting the remaining polygon into two
  74383. }
  74384. else if (pass === 2) {
  74385. splitEarcut(ear, triangles, dim, minX, minY, size);
  74386. }
  74387. break;
  74388. }
  74389. }
  74390. }
  74391. // check whether a polygon node forms a valid ear with adjacent nodes
  74392. function isEar(ear) {
  74393. var a = ear.prev, b = ear, c = ear.next;
  74394. if (area(a, b, c) >= 0)
  74395. return false; // reflex, can't be an ear
  74396. // now make sure we don't have other points inside the potential ear
  74397. var p = ear.next.next;
  74398. while (p !== ear.prev) {
  74399. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74400. area(p.prev, p, p.next) >= 0)
  74401. return false;
  74402. p = p.next;
  74403. }
  74404. return true;
  74405. }
  74406. function isEarHashed(ear, minX, minY, size) {
  74407. var a = ear.prev, b = ear, c = ear.next;
  74408. if (area(a, b, c) >= 0)
  74409. return false; // reflex, can't be an ear
  74410. // triangle bbox; min & max are calculated like this for speed
  74411. 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);
  74412. // z-order range for the current triangle bbox;
  74413. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74414. // first look for points inside the triangle in increasing z-order
  74415. var p = ear.nextZ;
  74416. while (p && p.z <= maxZ) {
  74417. if (p !== ear.prev &&
  74418. p !== ear.next &&
  74419. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74420. area(p.prev, p, p.next) >= 0)
  74421. return false;
  74422. p = p.nextZ;
  74423. }
  74424. // then look for points in decreasing z-order
  74425. p = ear.prevZ;
  74426. while (p && p.z >= minZ) {
  74427. if (p !== ear.prev &&
  74428. p !== ear.next &&
  74429. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74430. area(p.prev, p, p.next) >= 0)
  74431. return false;
  74432. p = p.prevZ;
  74433. }
  74434. return true;
  74435. }
  74436. // go through all polygon nodes and cure small local self-intersections
  74437. function cureLocalIntersections(start, triangles, dim) {
  74438. var p = start;
  74439. do {
  74440. var a = p.prev, b = p.next.next;
  74441. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74442. triangles.push(a.i / dim);
  74443. triangles.push(p.i / dim);
  74444. triangles.push(b.i / dim);
  74445. // remove two nodes involved
  74446. removeNode(p);
  74447. removeNode(p.next);
  74448. p = start = b;
  74449. }
  74450. p = p.next;
  74451. } while (p !== start);
  74452. return p;
  74453. }
  74454. // try splitting polygon into two and triangulate them independently
  74455. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74456. // look for a valid diagonal that divides the polygon into two
  74457. var a = start;
  74458. do {
  74459. var b = a.next.next;
  74460. while (b !== a.prev) {
  74461. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74462. // split the polygon in two by the diagonal
  74463. var c = splitPolygon(a, b);
  74464. // filter colinear points around the cuts
  74465. a = filterPoints(a, a.next);
  74466. c = filterPoints(c, c.next);
  74467. // run earcut on each half
  74468. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74469. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74470. return;
  74471. }
  74472. b = b.next;
  74473. }
  74474. a = a.next;
  74475. } while (a !== start);
  74476. }
  74477. // link every hole into the outer loop, producing a single-ring polygon without holes
  74478. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74479. var queue = [], i, len, start, end, list;
  74480. for (i = 0, len = holeIndices.length; i < len; i++) {
  74481. start = holeIndices[i] * dim;
  74482. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74483. list = linkedList(data, start, end, dim, false);
  74484. if (list === list.next)
  74485. list.steiner = true;
  74486. queue.push(getLeftmost(list));
  74487. }
  74488. queue.sort(compareX);
  74489. // process holes from left to right
  74490. for (i = 0; i < queue.length; i++) {
  74491. eliminateHole(queue[i], outerNode);
  74492. outerNode = filterPoints(outerNode, outerNode.next);
  74493. }
  74494. return outerNode;
  74495. }
  74496. function compareX(a, b) {
  74497. return a.x - b.x;
  74498. }
  74499. // find a bridge between vertices that connects hole with an outer ring and and link it
  74500. function eliminateHole(hole, outerNode) {
  74501. outerNode = findHoleBridge(hole, outerNode);
  74502. if (outerNode) {
  74503. var b = splitPolygon(outerNode, hole);
  74504. filterPoints(b, b.next);
  74505. }
  74506. }
  74507. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74508. function findHoleBridge(hole, outerNode) {
  74509. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74510. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74511. // segment's endpoint with lesser x will be potential connection point
  74512. do {
  74513. if (hy <= p.y && hy >= p.next.y) {
  74514. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74515. if (x <= hx && x > qx) {
  74516. qx = x;
  74517. if (x === hx) {
  74518. if (hy === p.y)
  74519. return p;
  74520. if (hy === p.next.y)
  74521. return p.next;
  74522. }
  74523. m = p.x < p.next.x ? p : p.next;
  74524. }
  74525. }
  74526. p = p.next;
  74527. } while (p !== outerNode);
  74528. if (!m)
  74529. return null;
  74530. if (hx === qx)
  74531. return m.prev; // hole touches outer segment; pick lower endpoint
  74532. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74533. // if there are no points found, we have a valid connection;
  74534. // otherwise choose the point of the minimum angle with the ray as connection point
  74535. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74536. p = m.next;
  74537. while (p !== stop) {
  74538. if (hx >= p.x &&
  74539. p.x >= mx &&
  74540. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74541. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74542. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74543. m = p;
  74544. tanMin = tan;
  74545. }
  74546. }
  74547. p = p.next;
  74548. }
  74549. return m;
  74550. }
  74551. // interlink polygon nodes in z-order
  74552. function indexCurve(start, minX, minY, size) {
  74553. var p = start;
  74554. do {
  74555. if (p.z === null)
  74556. p.z = zOrder(p.x, p.y, minX, minY, size);
  74557. p.prevZ = p.prev;
  74558. p.nextZ = p.next;
  74559. p = p.next;
  74560. } while (p !== start);
  74561. p.prevZ.nextZ = null;
  74562. p.prevZ = null;
  74563. sortLinked(p);
  74564. }
  74565. // Simon Tatham's linked list merge sort algorithm
  74566. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74567. function sortLinked(list) {
  74568. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74569. do {
  74570. p = list;
  74571. list = null;
  74572. tail = null;
  74573. numMerges = 0;
  74574. while (p) {
  74575. numMerges++;
  74576. q = p;
  74577. pSize = 0;
  74578. for (i = 0; i < inSize; i++) {
  74579. pSize++;
  74580. q = q.nextZ;
  74581. if (!q)
  74582. break;
  74583. }
  74584. qSize = inSize;
  74585. while (pSize > 0 || (qSize > 0 && q)) {
  74586. if (pSize === 0) {
  74587. e = q;
  74588. q = q.nextZ;
  74589. qSize--;
  74590. }
  74591. else if (qSize === 0 || !q) {
  74592. e = p;
  74593. p = p.nextZ;
  74594. pSize--;
  74595. }
  74596. else if (p.z <= q.z) {
  74597. e = p;
  74598. p = p.nextZ;
  74599. pSize--;
  74600. }
  74601. else {
  74602. e = q;
  74603. q = q.nextZ;
  74604. qSize--;
  74605. }
  74606. if (tail)
  74607. tail.nextZ = e;
  74608. else
  74609. list = e;
  74610. e.prevZ = tail;
  74611. tail = e;
  74612. }
  74613. p = q;
  74614. }
  74615. tail.nextZ = null;
  74616. inSize *= 2;
  74617. } while (numMerges > 1);
  74618. return list;
  74619. }
  74620. // z-order of a point given coords and size of the data bounding box
  74621. function zOrder(x, y, minX, minY, size) {
  74622. // coords are transformed into non-negative 15-bit integer range
  74623. x = 32767 * (x - minX) / size;
  74624. y = 32767 * (y - minY) / size;
  74625. x = (x | (x << 8)) & 0x00FF00FF;
  74626. x = (x | (x << 4)) & 0x0F0F0F0F;
  74627. x = (x | (x << 2)) & 0x33333333;
  74628. x = (x | (x << 1)) & 0x55555555;
  74629. y = (y | (y << 8)) & 0x00FF00FF;
  74630. y = (y | (y << 4)) & 0x0F0F0F0F;
  74631. y = (y | (y << 2)) & 0x33333333;
  74632. y = (y | (y << 1)) & 0x55555555;
  74633. return x | (y << 1);
  74634. }
  74635. // find the leftmost node of a polygon ring
  74636. function getLeftmost(start) {
  74637. var p = start, leftmost = start;
  74638. do {
  74639. if (p.x < leftmost.x)
  74640. leftmost = p;
  74641. p = p.next;
  74642. } while (p !== start);
  74643. return leftmost;
  74644. }
  74645. // check if a point lies within a convex triangle
  74646. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74647. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74648. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74649. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74650. }
  74651. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74652. function isValidDiagonal(a, b) {
  74653. return a.next.i !== b.i &&
  74654. a.prev.i !== b.i &&
  74655. !intersectsPolygon(a, b) &&
  74656. locallyInside(a, b) &&
  74657. locallyInside(b, a) &&
  74658. middleInside(a, b);
  74659. }
  74660. // signed area of a triangle
  74661. function area(p, q, r) {
  74662. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74663. }
  74664. // check if two points are equal
  74665. function equals(p1, p2) {
  74666. return p1.x === p2.x && p1.y === p2.y;
  74667. }
  74668. // check if two segments intersect
  74669. function intersects(p1, q1, p2, q2) {
  74670. if ((equals(p1, q1) && equals(p2, q2)) ||
  74671. (equals(p1, q2) && equals(p2, q1)))
  74672. return true;
  74673. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74674. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74675. }
  74676. // check if a polygon diagonal intersects any polygon segments
  74677. function intersectsPolygon(a, b) {
  74678. var p = a;
  74679. do {
  74680. if (p.i !== a.i &&
  74681. p.next.i !== a.i &&
  74682. p.i !== b.i &&
  74683. p.next.i !== b.i &&
  74684. intersects(p, p.next, a, b))
  74685. return true;
  74686. p = p.next;
  74687. } while (p !== a);
  74688. return false;
  74689. }
  74690. // check if a polygon diagonal is locally inside the polygon
  74691. function locallyInside(a, b) {
  74692. return area(a.prev, a, a.next) < 0
  74693. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74694. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74695. }
  74696. // check if the middle point of a polygon diagonal is inside the polygon
  74697. function middleInside(a, b) {
  74698. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74699. do {
  74700. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74701. inside = !inside;
  74702. p = p.next;
  74703. } while (p !== a);
  74704. return inside;
  74705. }
  74706. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74707. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74708. function splitPolygon(a, b) {
  74709. 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;
  74710. a.next = b;
  74711. b.prev = a;
  74712. a2.next = an;
  74713. an.prev = a2;
  74714. b2.next = a2;
  74715. a2.prev = b2;
  74716. bp.next = b2;
  74717. b2.prev = bp;
  74718. return b2;
  74719. }
  74720. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74721. function insertNode(i, x, y, last) {
  74722. var p = new Node(i, x, y);
  74723. if (!last) {
  74724. p.prev = p;
  74725. p.next = p;
  74726. }
  74727. else {
  74728. p.next = last.next;
  74729. p.prev = last;
  74730. last.next.prev = p;
  74731. last.next = p;
  74732. }
  74733. return p;
  74734. }
  74735. function removeNode(p) {
  74736. p.next.prev = p.prev;
  74737. p.prev.next = p.next;
  74738. if (p.prevZ)
  74739. p.prevZ.nextZ = p.nextZ;
  74740. if (p.nextZ)
  74741. p.nextZ.prevZ = p.prevZ;
  74742. }
  74743. /**
  74744. * return a percentage difference between the polygon area and its triangulation area;
  74745. * used to verify correctness of triangulation
  74746. */
  74747. function deviation(data, holeIndices, dim, triangles) {
  74748. var hasHoles = holeIndices && holeIndices.length;
  74749. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74750. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74751. if (hasHoles) {
  74752. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74753. var start = holeIndices[i] * dim;
  74754. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74755. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74756. }
  74757. }
  74758. var trianglesArea = 0;
  74759. for (i = 0; i < triangles.length; i += 3) {
  74760. var a = triangles[i] * dim;
  74761. var b = triangles[i + 1] * dim;
  74762. var c = triangles[i + 2] * dim;
  74763. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74764. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74765. }
  74766. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74767. }
  74768. Earcut.deviation = deviation;
  74769. ;
  74770. function signedArea(data, start, end, dim) {
  74771. var sum = 0;
  74772. for (var i = start, j = end - dim; i < end; i += dim) {
  74773. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74774. j = i;
  74775. }
  74776. return sum;
  74777. }
  74778. /**
  74779. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74780. */
  74781. function flatten(data) {
  74782. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74783. for (var i = 0; i < data.length; i++) {
  74784. for (var j = 0; j < data[i].length; j++) {
  74785. for (var d = 0; d < dim; d++)
  74786. result.vertices.push(data[i][j][d]);
  74787. }
  74788. if (i > 0) {
  74789. holeIndex += data[i - 1].length;
  74790. result.holes.push(holeIndex);
  74791. }
  74792. }
  74793. return result;
  74794. }
  74795. Earcut.flatten = flatten;
  74796. ;
  74797. })(Earcut || (Earcut = {}));
  74798. //# sourceMappingURL=babylon.earcut.js.map
  74799. var BABYLON;
  74800. (function (BABYLON) {
  74801. var IndexedVector2 = /** @class */ (function (_super) {
  74802. __extends(IndexedVector2, _super);
  74803. function IndexedVector2(original, index) {
  74804. var _this = _super.call(this, original.x, original.y) || this;
  74805. _this.index = index;
  74806. return _this;
  74807. }
  74808. return IndexedVector2;
  74809. }(BABYLON.Vector2));
  74810. var PolygonPoints = /** @class */ (function () {
  74811. function PolygonPoints() {
  74812. this.elements = new Array();
  74813. }
  74814. PolygonPoints.prototype.add = function (originalPoints) {
  74815. var _this = this;
  74816. var result = new Array();
  74817. originalPoints.forEach(function (point) {
  74818. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74819. var newPoint = new IndexedVector2(point, _this.elements.length);
  74820. result.push(newPoint);
  74821. _this.elements.push(newPoint);
  74822. }
  74823. });
  74824. return result;
  74825. };
  74826. PolygonPoints.prototype.computeBounds = function () {
  74827. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74828. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74829. this.elements.forEach(function (point) {
  74830. // x
  74831. if (point.x < lmin.x) {
  74832. lmin.x = point.x;
  74833. }
  74834. else if (point.x > lmax.x) {
  74835. lmax.x = point.x;
  74836. }
  74837. // y
  74838. if (point.y < lmin.y) {
  74839. lmin.y = point.y;
  74840. }
  74841. else if (point.y > lmax.y) {
  74842. lmax.y = point.y;
  74843. }
  74844. });
  74845. return {
  74846. min: lmin,
  74847. max: lmax,
  74848. width: lmax.x - lmin.x,
  74849. height: lmax.y - lmin.y
  74850. };
  74851. };
  74852. return PolygonPoints;
  74853. }());
  74854. var Polygon = /** @class */ (function () {
  74855. function Polygon() {
  74856. }
  74857. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74858. return [
  74859. new BABYLON.Vector2(xmin, ymin),
  74860. new BABYLON.Vector2(xmax, ymin),
  74861. new BABYLON.Vector2(xmax, ymax),
  74862. new BABYLON.Vector2(xmin, ymax)
  74863. ];
  74864. };
  74865. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74866. if (cx === void 0) { cx = 0; }
  74867. if (cy === void 0) { cy = 0; }
  74868. if (numberOfSides === void 0) { numberOfSides = 32; }
  74869. var result = new Array();
  74870. var angle = 0;
  74871. var increment = (Math.PI * 2) / numberOfSides;
  74872. for (var i = 0; i < numberOfSides; i++) {
  74873. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74874. angle -= increment;
  74875. }
  74876. return result;
  74877. };
  74878. Polygon.Parse = function (input) {
  74879. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74880. var i, result = [];
  74881. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74882. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74883. }
  74884. return result;
  74885. };
  74886. Polygon.StartingAt = function (x, y) {
  74887. return BABYLON.Path2.StartingAt(x, y);
  74888. };
  74889. return Polygon;
  74890. }());
  74891. BABYLON.Polygon = Polygon;
  74892. var PolygonMeshBuilder = /** @class */ (function () {
  74893. function PolygonMeshBuilder(name, contours, scene) {
  74894. this._points = new PolygonPoints();
  74895. this._outlinepoints = new PolygonPoints();
  74896. this._holes = new Array();
  74897. this._epoints = new Array();
  74898. this._eholes = new Array();
  74899. this._name = name;
  74900. this._scene = scene;
  74901. var points;
  74902. if (contours instanceof BABYLON.Path2) {
  74903. points = contours.getPoints();
  74904. }
  74905. else {
  74906. points = contours;
  74907. }
  74908. this._addToepoint(points);
  74909. this._points.add(points);
  74910. this._outlinepoints.add(points);
  74911. }
  74912. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74913. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74914. var p = points_1[_i];
  74915. this._epoints.push(p.x, p.y);
  74916. }
  74917. };
  74918. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74919. this._points.add(hole);
  74920. var holepoints = new PolygonPoints();
  74921. holepoints.add(hole);
  74922. this._holes.push(holepoints);
  74923. this._eholes.push(this._epoints.length / 2);
  74924. this._addToepoint(hole);
  74925. return this;
  74926. };
  74927. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74928. var _this = this;
  74929. if (updatable === void 0) { updatable = false; }
  74930. if (depth === void 0) { depth = 0; }
  74931. var result = new BABYLON.Mesh(this._name, this._scene);
  74932. var normals = new Array();
  74933. var positions = new Array();
  74934. var uvs = new Array();
  74935. var bounds = this._points.computeBounds();
  74936. this._points.elements.forEach(function (p) {
  74937. normals.push(0, 1.0, 0);
  74938. positions.push(p.x, 0, p.y);
  74939. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74940. });
  74941. var indices = new Array();
  74942. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74943. for (var i = 0; i < res.length; i++) {
  74944. indices.push(res[i]);
  74945. }
  74946. if (depth > 0) {
  74947. var positionscount = (positions.length / 3); //get the current pointcount
  74948. this._points.elements.forEach(function (p) {
  74949. normals.push(0, -1.0, 0);
  74950. positions.push(p.x, -depth, p.y);
  74951. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74952. });
  74953. var totalCount = indices.length;
  74954. for (var i = 0; i < totalCount; i += 3) {
  74955. var i0 = indices[i + 0];
  74956. var i1 = indices[i + 1];
  74957. var i2 = indices[i + 2];
  74958. indices.push(i2 + positionscount);
  74959. indices.push(i1 + positionscount);
  74960. indices.push(i0 + positionscount);
  74961. }
  74962. //Add the sides
  74963. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74964. this._holes.forEach(function (hole) {
  74965. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74966. });
  74967. }
  74968. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74969. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74970. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74971. result.setIndices(indices);
  74972. return result;
  74973. };
  74974. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74975. var StartIndex = positions.length / 3;
  74976. var ulength = 0;
  74977. for (var i = 0; i < points.elements.length; i++) {
  74978. var p = points.elements[i];
  74979. var p1;
  74980. if ((i + 1) > points.elements.length - 1) {
  74981. p1 = points.elements[0];
  74982. }
  74983. else {
  74984. p1 = points.elements[i + 1];
  74985. }
  74986. positions.push(p.x, 0, p.y);
  74987. positions.push(p.x, -depth, p.y);
  74988. positions.push(p1.x, 0, p1.y);
  74989. positions.push(p1.x, -depth, p1.y);
  74990. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74991. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74992. var v3 = v2.subtract(v1);
  74993. var v4 = new BABYLON.Vector3(0, 1, 0);
  74994. var vn = BABYLON.Vector3.Cross(v3, v4);
  74995. vn = vn.normalize();
  74996. uvs.push(ulength / bounds.width, 0);
  74997. uvs.push(ulength / bounds.width, 1);
  74998. ulength += v3.length();
  74999. uvs.push((ulength / bounds.width), 0);
  75000. uvs.push((ulength / bounds.width), 1);
  75001. if (!flip) {
  75002. normals.push(-vn.x, -vn.y, -vn.z);
  75003. normals.push(-vn.x, -vn.y, -vn.z);
  75004. normals.push(-vn.x, -vn.y, -vn.z);
  75005. normals.push(-vn.x, -vn.y, -vn.z);
  75006. indices.push(StartIndex);
  75007. indices.push(StartIndex + 1);
  75008. indices.push(StartIndex + 2);
  75009. indices.push(StartIndex + 1);
  75010. indices.push(StartIndex + 3);
  75011. indices.push(StartIndex + 2);
  75012. }
  75013. else {
  75014. normals.push(vn.x, vn.y, vn.z);
  75015. normals.push(vn.x, vn.y, vn.z);
  75016. normals.push(vn.x, vn.y, vn.z);
  75017. normals.push(vn.x, vn.y, vn.z);
  75018. indices.push(StartIndex);
  75019. indices.push(StartIndex + 2);
  75020. indices.push(StartIndex + 1);
  75021. indices.push(StartIndex + 1);
  75022. indices.push(StartIndex + 2);
  75023. indices.push(StartIndex + 3);
  75024. }
  75025. StartIndex += 4;
  75026. }
  75027. ;
  75028. };
  75029. return PolygonMeshBuilder;
  75030. }());
  75031. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75032. })(BABYLON || (BABYLON = {}));
  75033. //# sourceMappingURL=babylon.polygonMesh.js.map
  75034. var BABYLON;
  75035. (function (BABYLON) {
  75036. // Unique ID when we import meshes from Babylon to CSG
  75037. var currentCSGMeshId = 0;
  75038. // # class Vertex
  75039. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75040. // one to provide additional features like texture coordinates and vertex
  75041. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75042. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75043. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75044. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75045. // is not used anywhere else.
  75046. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75047. var Vertex = /** @class */ (function () {
  75048. function Vertex(pos, normal, uv) {
  75049. this.pos = pos;
  75050. this.normal = normal;
  75051. this.uv = uv;
  75052. }
  75053. Vertex.prototype.clone = function () {
  75054. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75055. };
  75056. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75057. // orientation of a polygon is flipped.
  75058. Vertex.prototype.flip = function () {
  75059. this.normal = this.normal.scale(-1);
  75060. };
  75061. // Create a new vertex between this vertex and `other` by linearly
  75062. // interpolating all properties using a parameter of `t`. Subclasses should
  75063. // override this to interpolate additional properties.
  75064. Vertex.prototype.interpolate = function (other, t) {
  75065. 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));
  75066. };
  75067. return Vertex;
  75068. }());
  75069. // # class Plane
  75070. // Represents a plane in 3D space.
  75071. var Plane = /** @class */ (function () {
  75072. function Plane(normal, w) {
  75073. this.normal = normal;
  75074. this.w = w;
  75075. }
  75076. Plane.FromPoints = function (a, b, c) {
  75077. var v0 = c.subtract(a);
  75078. var v1 = b.subtract(a);
  75079. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75080. return null;
  75081. }
  75082. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75083. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75084. };
  75085. Plane.prototype.clone = function () {
  75086. return new Plane(this.normal.clone(), this.w);
  75087. };
  75088. Plane.prototype.flip = function () {
  75089. this.normal.scaleInPlace(-1);
  75090. this.w = -this.w;
  75091. };
  75092. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75093. // fragments in the appropriate lists. Coplanar polygons go into either
  75094. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75095. // respect to this plane. Polygons in front or in back of this plane go into
  75096. // either `front` or `back`.
  75097. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75098. var COPLANAR = 0;
  75099. var FRONT = 1;
  75100. var BACK = 2;
  75101. var SPANNING = 3;
  75102. // Classify each point as well as the entire polygon into one of the above
  75103. // four classes.
  75104. var polygonType = 0;
  75105. var types = [];
  75106. var i;
  75107. var t;
  75108. for (i = 0; i < polygon.vertices.length; i++) {
  75109. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75110. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75111. polygonType |= type;
  75112. types.push(type);
  75113. }
  75114. // Put the polygon in the correct list, splitting it when necessary.
  75115. switch (polygonType) {
  75116. case COPLANAR:
  75117. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75118. break;
  75119. case FRONT:
  75120. front.push(polygon);
  75121. break;
  75122. case BACK:
  75123. back.push(polygon);
  75124. break;
  75125. case SPANNING:
  75126. var f = [], b = [];
  75127. for (i = 0; i < polygon.vertices.length; i++) {
  75128. var j = (i + 1) % polygon.vertices.length;
  75129. var ti = types[i], tj = types[j];
  75130. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75131. if (ti !== BACK)
  75132. f.push(vi);
  75133. if (ti !== FRONT)
  75134. b.push(ti !== BACK ? vi.clone() : vi);
  75135. if ((ti | tj) === SPANNING) {
  75136. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75137. var v = vi.interpolate(vj, t);
  75138. f.push(v);
  75139. b.push(v.clone());
  75140. }
  75141. }
  75142. var poly;
  75143. if (f.length >= 3) {
  75144. poly = new Polygon(f, polygon.shared);
  75145. if (poly.plane)
  75146. front.push(poly);
  75147. }
  75148. if (b.length >= 3) {
  75149. poly = new Polygon(b, polygon.shared);
  75150. if (poly.plane)
  75151. back.push(poly);
  75152. }
  75153. break;
  75154. }
  75155. };
  75156. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75157. // point is on the plane.
  75158. Plane.EPSILON = 1e-5;
  75159. return Plane;
  75160. }());
  75161. // # class Polygon
  75162. // Represents a convex polygon. The vertices used to initialize a polygon must
  75163. // be coplanar and form a convex loop.
  75164. //
  75165. // Each convex polygon has a `shared` property, which is shared between all
  75166. // polygons that are clones of each other or were split from the same polygon.
  75167. // This can be used to define per-polygon properties (such as surface color).
  75168. var Polygon = /** @class */ (function () {
  75169. function Polygon(vertices, shared) {
  75170. this.vertices = vertices;
  75171. this.shared = shared;
  75172. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75173. }
  75174. Polygon.prototype.clone = function () {
  75175. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75176. return new Polygon(vertices, this.shared);
  75177. };
  75178. Polygon.prototype.flip = function () {
  75179. this.vertices.reverse().map(function (v) { v.flip(); });
  75180. this.plane.flip();
  75181. };
  75182. return Polygon;
  75183. }());
  75184. // # class Node
  75185. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75186. // by picking a polygon to split along. That polygon (and all other coplanar
  75187. // polygons) are added directly to that node and the other polygons are added to
  75188. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75189. // no distinction between internal and leaf nodes.
  75190. var Node = /** @class */ (function () {
  75191. function Node(polygons) {
  75192. this.plane = null;
  75193. this.front = null;
  75194. this.back = null;
  75195. this.polygons = new Array();
  75196. if (polygons) {
  75197. this.build(polygons);
  75198. }
  75199. }
  75200. Node.prototype.clone = function () {
  75201. var node = new Node();
  75202. node.plane = this.plane && this.plane.clone();
  75203. node.front = this.front && this.front.clone();
  75204. node.back = this.back && this.back.clone();
  75205. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75206. return node;
  75207. };
  75208. // Convert solid space to empty space and empty space to solid space.
  75209. Node.prototype.invert = function () {
  75210. for (var i = 0; i < this.polygons.length; i++) {
  75211. this.polygons[i].flip();
  75212. }
  75213. if (this.plane) {
  75214. this.plane.flip();
  75215. }
  75216. if (this.front) {
  75217. this.front.invert();
  75218. }
  75219. if (this.back) {
  75220. this.back.invert();
  75221. }
  75222. var temp = this.front;
  75223. this.front = this.back;
  75224. this.back = temp;
  75225. };
  75226. // Recursively remove all polygons in `polygons` that are inside this BSP
  75227. // tree.
  75228. Node.prototype.clipPolygons = function (polygons) {
  75229. if (!this.plane)
  75230. return polygons.slice();
  75231. var front = new Array(), back = new Array();
  75232. for (var i = 0; i < polygons.length; i++) {
  75233. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75234. }
  75235. if (this.front) {
  75236. front = this.front.clipPolygons(front);
  75237. }
  75238. if (this.back) {
  75239. back = this.back.clipPolygons(back);
  75240. }
  75241. else {
  75242. back = [];
  75243. }
  75244. return front.concat(back);
  75245. };
  75246. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75247. // `bsp`.
  75248. Node.prototype.clipTo = function (bsp) {
  75249. this.polygons = bsp.clipPolygons(this.polygons);
  75250. if (this.front)
  75251. this.front.clipTo(bsp);
  75252. if (this.back)
  75253. this.back.clipTo(bsp);
  75254. };
  75255. // Return a list of all polygons in this BSP tree.
  75256. Node.prototype.allPolygons = function () {
  75257. var polygons = this.polygons.slice();
  75258. if (this.front)
  75259. polygons = polygons.concat(this.front.allPolygons());
  75260. if (this.back)
  75261. polygons = polygons.concat(this.back.allPolygons());
  75262. return polygons;
  75263. };
  75264. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75265. // new polygons are filtered down to the bottom of the tree and become new
  75266. // nodes there. Each set of polygons is partitioned using the first polygon
  75267. // (no heuristic is used to pick a good split).
  75268. Node.prototype.build = function (polygons) {
  75269. if (!polygons.length)
  75270. return;
  75271. if (!this.plane)
  75272. this.plane = polygons[0].plane.clone();
  75273. var front = new Array(), back = new Array();
  75274. for (var i = 0; i < polygons.length; i++) {
  75275. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75276. }
  75277. if (front.length) {
  75278. if (!this.front)
  75279. this.front = new Node();
  75280. this.front.build(front);
  75281. }
  75282. if (back.length) {
  75283. if (!this.back)
  75284. this.back = new Node();
  75285. this.back.build(back);
  75286. }
  75287. };
  75288. return Node;
  75289. }());
  75290. var CSG = /** @class */ (function () {
  75291. function CSG() {
  75292. this.polygons = new Array();
  75293. }
  75294. // Convert BABYLON.Mesh to BABYLON.CSG
  75295. CSG.FromMesh = function (mesh) {
  75296. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75297. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75298. if (mesh instanceof BABYLON.Mesh) {
  75299. mesh.computeWorldMatrix(true);
  75300. matrix = mesh.getWorldMatrix();
  75301. meshPosition = mesh.position.clone();
  75302. meshRotation = mesh.rotation.clone();
  75303. if (mesh.rotationQuaternion) {
  75304. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75305. }
  75306. meshScaling = mesh.scaling.clone();
  75307. }
  75308. else {
  75309. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75310. }
  75311. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75312. var subMeshes = mesh.subMeshes;
  75313. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75314. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75315. vertices = [];
  75316. for (var j = 0; j < 3; j++) {
  75317. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75318. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75319. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75320. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75321. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75322. vertex = new Vertex(position, normal, uv);
  75323. vertices.push(vertex);
  75324. }
  75325. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75326. // To handle the case of degenerated triangle
  75327. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75328. if (polygon.plane)
  75329. polygons.push(polygon);
  75330. }
  75331. }
  75332. var csg = CSG.FromPolygons(polygons);
  75333. csg.matrix = matrix;
  75334. csg.position = meshPosition;
  75335. csg.rotation = meshRotation;
  75336. csg.scaling = meshScaling;
  75337. csg.rotationQuaternion = meshRotationQuaternion;
  75338. currentCSGMeshId++;
  75339. return csg;
  75340. };
  75341. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75342. CSG.FromPolygons = function (polygons) {
  75343. var csg = new CSG();
  75344. csg.polygons = polygons;
  75345. return csg;
  75346. };
  75347. CSG.prototype.clone = function () {
  75348. var csg = new CSG();
  75349. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75350. csg.copyTransformAttributes(this);
  75351. return csg;
  75352. };
  75353. CSG.prototype.union = function (csg) {
  75354. var a = new Node(this.clone().polygons);
  75355. var b = new Node(csg.clone().polygons);
  75356. a.clipTo(b);
  75357. b.clipTo(a);
  75358. b.invert();
  75359. b.clipTo(a);
  75360. b.invert();
  75361. a.build(b.allPolygons());
  75362. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75363. };
  75364. CSG.prototype.unionInPlace = function (csg) {
  75365. var a = new Node(this.polygons);
  75366. var b = new Node(csg.polygons);
  75367. a.clipTo(b);
  75368. b.clipTo(a);
  75369. b.invert();
  75370. b.clipTo(a);
  75371. b.invert();
  75372. a.build(b.allPolygons());
  75373. this.polygons = a.allPolygons();
  75374. };
  75375. CSG.prototype.subtract = function (csg) {
  75376. var a = new Node(this.clone().polygons);
  75377. var b = new Node(csg.clone().polygons);
  75378. a.invert();
  75379. a.clipTo(b);
  75380. b.clipTo(a);
  75381. b.invert();
  75382. b.clipTo(a);
  75383. b.invert();
  75384. a.build(b.allPolygons());
  75385. a.invert();
  75386. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75387. };
  75388. CSG.prototype.subtractInPlace = function (csg) {
  75389. var a = new Node(this.polygons);
  75390. var b = new Node(csg.polygons);
  75391. a.invert();
  75392. a.clipTo(b);
  75393. b.clipTo(a);
  75394. b.invert();
  75395. b.clipTo(a);
  75396. b.invert();
  75397. a.build(b.allPolygons());
  75398. a.invert();
  75399. this.polygons = a.allPolygons();
  75400. };
  75401. CSG.prototype.intersect = function (csg) {
  75402. var a = new Node(this.clone().polygons);
  75403. var b = new Node(csg.clone().polygons);
  75404. a.invert();
  75405. b.clipTo(a);
  75406. b.invert();
  75407. a.clipTo(b);
  75408. b.clipTo(a);
  75409. a.build(b.allPolygons());
  75410. a.invert();
  75411. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75412. };
  75413. CSG.prototype.intersectInPlace = function (csg) {
  75414. var a = new Node(this.polygons);
  75415. var b = new Node(csg.polygons);
  75416. a.invert();
  75417. b.clipTo(a);
  75418. b.invert();
  75419. a.clipTo(b);
  75420. b.clipTo(a);
  75421. a.build(b.allPolygons());
  75422. a.invert();
  75423. this.polygons = a.allPolygons();
  75424. };
  75425. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75426. // not modified.
  75427. CSG.prototype.inverse = function () {
  75428. var csg = this.clone();
  75429. csg.inverseInPlace();
  75430. return csg;
  75431. };
  75432. CSG.prototype.inverseInPlace = function () {
  75433. this.polygons.map(function (p) { p.flip(); });
  75434. };
  75435. // This is used to keep meshes transformations so they can be restored
  75436. // when we build back a Babylon Mesh
  75437. // NB : All CSG operations are performed in world coordinates
  75438. CSG.prototype.copyTransformAttributes = function (csg) {
  75439. this.matrix = csg.matrix;
  75440. this.position = csg.position;
  75441. this.rotation = csg.rotation;
  75442. this.scaling = csg.scaling;
  75443. this.rotationQuaternion = csg.rotationQuaternion;
  75444. return this;
  75445. };
  75446. // Build Raw mesh from CSG
  75447. // Coordinates here are in world space
  75448. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75449. var matrix = this.matrix.clone();
  75450. matrix.invert();
  75451. 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;
  75452. if (keepSubMeshes) {
  75453. // Sort Polygons, since subMeshes are indices range
  75454. polygons.sort(function (a, b) {
  75455. if (a.shared.meshId === b.shared.meshId) {
  75456. return a.shared.subMeshId - b.shared.subMeshId;
  75457. }
  75458. else {
  75459. return a.shared.meshId - b.shared.meshId;
  75460. }
  75461. });
  75462. }
  75463. for (var i = 0, il = polygons.length; i < il; i++) {
  75464. polygon = polygons[i];
  75465. // Building SubMeshes
  75466. if (!subMesh_dict[polygon.shared.meshId]) {
  75467. subMesh_dict[polygon.shared.meshId] = {};
  75468. }
  75469. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75470. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75471. indexStart: +Infinity,
  75472. indexEnd: -Infinity,
  75473. materialIndex: polygon.shared.materialIndex
  75474. };
  75475. }
  75476. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75477. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75478. polygonIndices[0] = 0;
  75479. polygonIndices[1] = j - 1;
  75480. polygonIndices[2] = j;
  75481. for (var k = 0; k < 3; k++) {
  75482. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75483. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75484. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75485. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75486. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75487. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75488. // Check if 2 points can be merged
  75489. if (!(typeof vertex_idx !== 'undefined' &&
  75490. normals[vertex_idx * 3] === localNormal.x &&
  75491. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75492. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75493. uvs[vertex_idx * 2] === uv.x &&
  75494. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75495. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75496. uvs.push(uv.x, uv.y);
  75497. normals.push(normal.x, normal.y, normal.z);
  75498. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75499. }
  75500. indices.push(vertex_idx);
  75501. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75502. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75503. currentIndex++;
  75504. }
  75505. }
  75506. }
  75507. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75508. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75509. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75510. mesh.setIndices(indices, null);
  75511. if (keepSubMeshes) {
  75512. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75513. var materialIndexOffset = 0, materialMaxIndex;
  75514. mesh.subMeshes = new Array();
  75515. for (var m in subMesh_dict) {
  75516. materialMaxIndex = -1;
  75517. for (var sm in subMesh_dict[m]) {
  75518. subMesh_obj = subMesh_dict[m][sm];
  75519. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75520. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75521. }
  75522. materialIndexOffset += ++materialMaxIndex;
  75523. }
  75524. }
  75525. return mesh;
  75526. };
  75527. // Build Mesh from CSG taking material and transforms into account
  75528. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75529. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75530. mesh.material = material;
  75531. mesh.position.copyFrom(this.position);
  75532. mesh.rotation.copyFrom(this.rotation);
  75533. if (this.rotationQuaternion) {
  75534. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75535. }
  75536. mesh.scaling.copyFrom(this.scaling);
  75537. mesh.computeWorldMatrix(true);
  75538. return mesh;
  75539. };
  75540. return CSG;
  75541. }());
  75542. BABYLON.CSG = CSG;
  75543. })(BABYLON || (BABYLON = {}));
  75544. //# sourceMappingURL=babylon.csg.js.map
  75545. var BABYLON;
  75546. (function (BABYLON) {
  75547. var LensFlare = /** @class */ (function () {
  75548. function LensFlare(size, position, color, imgUrl, system) {
  75549. this.size = size;
  75550. this.position = position;
  75551. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75552. this.color = color || new BABYLON.Color3(1, 1, 1);
  75553. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75554. this._system = system;
  75555. system.lensFlares.push(this);
  75556. }
  75557. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75558. return new LensFlare(size, position, color, imgUrl, system);
  75559. };
  75560. LensFlare.prototype.dispose = function () {
  75561. if (this.texture) {
  75562. this.texture.dispose();
  75563. }
  75564. // Remove from scene
  75565. var index = this._system.lensFlares.indexOf(this);
  75566. this._system.lensFlares.splice(index, 1);
  75567. };
  75568. ;
  75569. return LensFlare;
  75570. }());
  75571. BABYLON.LensFlare = LensFlare;
  75572. })(BABYLON || (BABYLON = {}));
  75573. //# sourceMappingURL=babylon.lensFlare.js.map
  75574. var BABYLON;
  75575. (function (BABYLON) {
  75576. var LensFlareSystem = /** @class */ (function () {
  75577. function LensFlareSystem(name, emitter, scene) {
  75578. this.name = name;
  75579. this.lensFlares = new Array();
  75580. this.borderLimit = 300;
  75581. this.viewportBorder = 0;
  75582. this.layerMask = 0x0FFFFFFF;
  75583. this._vertexBuffers = {};
  75584. this._isEnabled = true;
  75585. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75586. this._emitter = emitter;
  75587. this.id = name;
  75588. scene.lensFlareSystems.push(this);
  75589. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75590. var engine = scene.getEngine();
  75591. // VBO
  75592. var vertices = [];
  75593. vertices.push(1, 1);
  75594. vertices.push(-1, 1);
  75595. vertices.push(-1, -1);
  75596. vertices.push(1, -1);
  75597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75598. // Indices
  75599. var indices = [];
  75600. indices.push(0);
  75601. indices.push(1);
  75602. indices.push(2);
  75603. indices.push(0);
  75604. indices.push(2);
  75605. indices.push(3);
  75606. this._indexBuffer = engine.createIndexBuffer(indices);
  75607. // Effects
  75608. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75609. }
  75610. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75611. get: function () {
  75612. return this._isEnabled;
  75613. },
  75614. set: function (value) {
  75615. this._isEnabled = value;
  75616. },
  75617. enumerable: true,
  75618. configurable: true
  75619. });
  75620. LensFlareSystem.prototype.getScene = function () {
  75621. return this._scene;
  75622. };
  75623. LensFlareSystem.prototype.getEmitter = function () {
  75624. return this._emitter;
  75625. };
  75626. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75627. this._emitter = newEmitter;
  75628. };
  75629. LensFlareSystem.prototype.getEmitterPosition = function () {
  75630. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75631. };
  75632. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75633. var position = this.getEmitterPosition();
  75634. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75635. this._positionX = position.x;
  75636. this._positionY = position.y;
  75637. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75638. if (this.viewportBorder > 0) {
  75639. globalViewport.x -= this.viewportBorder;
  75640. globalViewport.y -= this.viewportBorder;
  75641. globalViewport.width += this.viewportBorder * 2;
  75642. globalViewport.height += this.viewportBorder * 2;
  75643. position.x += this.viewportBorder;
  75644. position.y += this.viewportBorder;
  75645. this._positionX += this.viewportBorder;
  75646. this._positionY += this.viewportBorder;
  75647. }
  75648. if (position.z > 0) {
  75649. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75650. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75651. return true;
  75652. }
  75653. return true;
  75654. }
  75655. return false;
  75656. };
  75657. LensFlareSystem.prototype._isVisible = function () {
  75658. if (!this._isEnabled || !this._scene.activeCamera) {
  75659. return false;
  75660. }
  75661. var emitterPosition = this.getEmitterPosition();
  75662. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75663. var distance = direction.length();
  75664. direction.normalize();
  75665. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75666. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75667. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75668. };
  75669. LensFlareSystem.prototype.render = function () {
  75670. if (!this._effect.isReady() || !this._scene.activeCamera)
  75671. return false;
  75672. var engine = this._scene.getEngine();
  75673. var viewport = this._scene.activeCamera.viewport;
  75674. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75675. // Position
  75676. if (!this.computeEffectivePosition(globalViewport)) {
  75677. return false;
  75678. }
  75679. // Visibility
  75680. if (!this._isVisible()) {
  75681. return false;
  75682. }
  75683. // Intensity
  75684. var awayX;
  75685. var awayY;
  75686. if (this._positionX < this.borderLimit + globalViewport.x) {
  75687. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75688. }
  75689. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75690. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75691. }
  75692. else {
  75693. awayX = 0;
  75694. }
  75695. if (this._positionY < this.borderLimit + globalViewport.y) {
  75696. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75697. }
  75698. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75699. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75700. }
  75701. else {
  75702. awayY = 0;
  75703. }
  75704. var away = (awayX > awayY) ? awayX : awayY;
  75705. away -= this.viewportBorder;
  75706. if (away > this.borderLimit) {
  75707. away = this.borderLimit;
  75708. }
  75709. var intensity = 1.0 - (away / this.borderLimit);
  75710. if (intensity < 0) {
  75711. return false;
  75712. }
  75713. if (intensity > 1.0) {
  75714. intensity = 1.0;
  75715. }
  75716. if (this.viewportBorder > 0) {
  75717. globalViewport.x += this.viewportBorder;
  75718. globalViewport.y += this.viewportBorder;
  75719. globalViewport.width -= this.viewportBorder * 2;
  75720. globalViewport.height -= this.viewportBorder * 2;
  75721. this._positionX -= this.viewportBorder;
  75722. this._positionY -= this.viewportBorder;
  75723. }
  75724. // Position
  75725. var centerX = globalViewport.x + globalViewport.width / 2;
  75726. var centerY = globalViewport.y + globalViewport.height / 2;
  75727. var distX = centerX - this._positionX;
  75728. var distY = centerY - this._positionY;
  75729. // Effects
  75730. engine.enableEffect(this._effect);
  75731. engine.setState(false);
  75732. engine.setDepthBuffer(false);
  75733. // VBOs
  75734. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75735. // Flares
  75736. for (var index = 0; index < this.lensFlares.length; index++) {
  75737. var flare = this.lensFlares[index];
  75738. engine.setAlphaMode(flare.alphaMode);
  75739. var x = centerX - (distX * flare.position);
  75740. var y = centerY - (distY * flare.position);
  75741. var cw = flare.size;
  75742. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75743. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75744. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75745. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75746. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75747. // Texture
  75748. this._effect.setTexture("textureSampler", flare.texture);
  75749. // Color
  75750. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75751. // Draw order
  75752. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75753. }
  75754. engine.setDepthBuffer(true);
  75755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75756. return true;
  75757. };
  75758. LensFlareSystem.prototype.dispose = function () {
  75759. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75760. if (vertexBuffer) {
  75761. vertexBuffer.dispose();
  75762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75763. }
  75764. if (this._indexBuffer) {
  75765. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75766. this._indexBuffer = null;
  75767. }
  75768. while (this.lensFlares.length) {
  75769. this.lensFlares[0].dispose();
  75770. }
  75771. // Remove from scene
  75772. var index = this._scene.lensFlareSystems.indexOf(this);
  75773. this._scene.lensFlareSystems.splice(index, 1);
  75774. };
  75775. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75776. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75777. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75778. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75779. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75780. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75781. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75782. var parsedFlare = parsedLensFlareSystem.flares[index];
  75783. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75784. }
  75785. return lensFlareSystem;
  75786. };
  75787. LensFlareSystem.prototype.serialize = function () {
  75788. var serializationObject = {};
  75789. serializationObject.id = this.id;
  75790. serializationObject.name = this.name;
  75791. serializationObject.emitterId = this.getEmitter().id;
  75792. serializationObject.borderLimit = this.borderLimit;
  75793. serializationObject.flares = [];
  75794. for (var index = 0; index < this.lensFlares.length; index++) {
  75795. var flare = this.lensFlares[index];
  75796. serializationObject.flares.push({
  75797. size: flare.size,
  75798. position: flare.position,
  75799. color: flare.color.asArray(),
  75800. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75801. });
  75802. }
  75803. return serializationObject;
  75804. };
  75805. return LensFlareSystem;
  75806. }());
  75807. BABYLON.LensFlareSystem = LensFlareSystem;
  75808. })(BABYLON || (BABYLON = {}));
  75809. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75810. var BABYLON;
  75811. (function (BABYLON) {
  75812. /**
  75813. * This is a holder class for the physics joint created by the physics plugin.
  75814. * It holds a set of functions to control the underlying joint.
  75815. */
  75816. var PhysicsJoint = /** @class */ (function () {
  75817. function PhysicsJoint(type, jointData) {
  75818. this.type = type;
  75819. this.jointData = jointData;
  75820. jointData.nativeParams = jointData.nativeParams || {};
  75821. }
  75822. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75823. get: function () {
  75824. return this._physicsJoint;
  75825. },
  75826. set: function (newJoint) {
  75827. if (this._physicsJoint) {
  75828. //remove from the wolrd
  75829. }
  75830. this._physicsJoint = newJoint;
  75831. },
  75832. enumerable: true,
  75833. configurable: true
  75834. });
  75835. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75836. set: function (physicsPlugin) {
  75837. this._physicsPlugin = physicsPlugin;
  75838. },
  75839. enumerable: true,
  75840. configurable: true
  75841. });
  75842. /**
  75843. * Execute a function that is physics-plugin specific.
  75844. * @param {Function} func the function that will be executed.
  75845. * It accepts two parameters: the physics world and the physics joint.
  75846. */
  75847. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75848. func(this._physicsPlugin.world, this._physicsJoint);
  75849. };
  75850. //TODO check if the native joints are the same
  75851. //Joint Types
  75852. PhysicsJoint.DistanceJoint = 0;
  75853. PhysicsJoint.HingeJoint = 1;
  75854. PhysicsJoint.BallAndSocketJoint = 2;
  75855. PhysicsJoint.WheelJoint = 3;
  75856. PhysicsJoint.SliderJoint = 4;
  75857. //OIMO
  75858. PhysicsJoint.PrismaticJoint = 5;
  75859. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75860. PhysicsJoint.UniversalJoint = 6;
  75861. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75862. //Cannon
  75863. //Similar to a Ball-Joint. Different in params
  75864. PhysicsJoint.PointToPointJoint = 8;
  75865. //Cannon only at the moment
  75866. PhysicsJoint.SpringJoint = 9;
  75867. PhysicsJoint.LockJoint = 10;
  75868. return PhysicsJoint;
  75869. }());
  75870. BABYLON.PhysicsJoint = PhysicsJoint;
  75871. /**
  75872. * A class representing a physics distance joint.
  75873. */
  75874. var DistanceJoint = /** @class */ (function (_super) {
  75875. __extends(DistanceJoint, _super);
  75876. function DistanceJoint(jointData) {
  75877. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75878. }
  75879. /**
  75880. * Update the predefined distance.
  75881. */
  75882. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75883. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75884. };
  75885. return DistanceJoint;
  75886. }(PhysicsJoint));
  75887. BABYLON.DistanceJoint = DistanceJoint;
  75888. var MotorEnabledJoint = /** @class */ (function (_super) {
  75889. __extends(MotorEnabledJoint, _super);
  75890. function MotorEnabledJoint(type, jointData) {
  75891. return _super.call(this, type, jointData) || this;
  75892. }
  75893. /**
  75894. * Set the motor values.
  75895. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75896. * @param {number} force the force to apply
  75897. * @param {number} maxForce max force for this motor.
  75898. */
  75899. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75900. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75901. };
  75902. /**
  75903. * Set the motor's limits.
  75904. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75905. */
  75906. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75907. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75908. };
  75909. return MotorEnabledJoint;
  75910. }(PhysicsJoint));
  75911. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75912. /**
  75913. * This class represents a single hinge physics joint
  75914. */
  75915. var HingeJoint = /** @class */ (function (_super) {
  75916. __extends(HingeJoint, _super);
  75917. function HingeJoint(jointData) {
  75918. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75919. }
  75920. /**
  75921. * Set the motor values.
  75922. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75923. * @param {number} force the force to apply
  75924. * @param {number} maxForce max force for this motor.
  75925. */
  75926. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75927. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75928. };
  75929. /**
  75930. * Set the motor's limits.
  75931. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75932. */
  75933. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75934. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75935. };
  75936. return HingeJoint;
  75937. }(MotorEnabledJoint));
  75938. BABYLON.HingeJoint = HingeJoint;
  75939. /**
  75940. * This class represents a dual hinge physics joint (same as wheel joint)
  75941. */
  75942. var Hinge2Joint = /** @class */ (function (_super) {
  75943. __extends(Hinge2Joint, _super);
  75944. function Hinge2Joint(jointData) {
  75945. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75946. }
  75947. /**
  75948. * Set the motor values.
  75949. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75950. * @param {number} force the force to apply
  75951. * @param {number} maxForce max force for this motor.
  75952. * @param {motorIndex} the motor's index, 0 or 1.
  75953. */
  75954. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75955. if (motorIndex === void 0) { motorIndex = 0; }
  75956. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75957. };
  75958. /**
  75959. * Set the motor limits.
  75960. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75961. * @param {number} upperLimit the upper limit
  75962. * @param {number} lowerLimit lower limit
  75963. * @param {motorIndex} the motor's index, 0 or 1.
  75964. */
  75965. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75966. if (motorIndex === void 0) { motorIndex = 0; }
  75967. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75968. };
  75969. return Hinge2Joint;
  75970. }(MotorEnabledJoint));
  75971. BABYLON.Hinge2Joint = Hinge2Joint;
  75972. })(BABYLON || (BABYLON = {}));
  75973. //# sourceMappingURL=babylon.physicsJoint.js.map
  75974. var BABYLON;
  75975. (function (BABYLON) {
  75976. var PhysicsImpostor = /** @class */ (function () {
  75977. function PhysicsImpostor(object, type, _options, _scene) {
  75978. if (_options === void 0) { _options = { mass: 0 }; }
  75979. var _this = this;
  75980. this.object = object;
  75981. this.type = type;
  75982. this._options = _options;
  75983. this._scene = _scene;
  75984. this._bodyUpdateRequired = false;
  75985. this._onBeforePhysicsStepCallbacks = new Array();
  75986. this._onAfterPhysicsStepCallbacks = new Array();
  75987. this._onPhysicsCollideCallbacks = [];
  75988. this._deltaPosition = BABYLON.Vector3.Zero();
  75989. this._isDisposed = false;
  75990. //temp variables for parent rotation calculations
  75991. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75992. this._tmpQuat = new BABYLON.Quaternion();
  75993. this._tmpQuat2 = new BABYLON.Quaternion();
  75994. /**
  75995. * this function is executed by the physics engine.
  75996. */
  75997. this.beforeStep = function () {
  75998. if (!_this._physicsEngine) {
  75999. return;
  76000. }
  76001. _this.object.translate(_this._deltaPosition, -1);
  76002. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76003. _this.object.computeWorldMatrix(false);
  76004. if (_this.object.parent && _this.object.rotationQuaternion) {
  76005. _this.getParentsRotation();
  76006. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76007. }
  76008. else {
  76009. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76010. }
  76011. if (!_this._options.disableBidirectionalTransformation) {
  76012. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76013. }
  76014. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76015. func(_this);
  76016. });
  76017. };
  76018. /**
  76019. * this function is executed by the physics engine.
  76020. */
  76021. this.afterStep = function () {
  76022. if (!_this._physicsEngine) {
  76023. return;
  76024. }
  76025. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76026. func(_this);
  76027. });
  76028. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76029. // object has now its world rotation. needs to be converted to local.
  76030. if (_this.object.parent && _this.object.rotationQuaternion) {
  76031. _this.getParentsRotation();
  76032. _this._tmpQuat.conjugateInPlace();
  76033. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76034. }
  76035. // take the position set and make it the absolute position of this object.
  76036. _this.object.setAbsolutePosition(_this.object.position);
  76037. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76038. _this.object.translate(_this._deltaPosition, 1);
  76039. };
  76040. /**
  76041. * Legacy collision detection event support
  76042. */
  76043. this.onCollideEvent = null;
  76044. //event and body object due to cannon's event-based architecture.
  76045. this.onCollide = function (e) {
  76046. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76047. return;
  76048. }
  76049. if (!_this._physicsEngine) {
  76050. return;
  76051. }
  76052. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76053. if (otherImpostor) {
  76054. // Legacy collision detection event support
  76055. if (_this.onCollideEvent) {
  76056. _this.onCollideEvent(_this, otherImpostor);
  76057. }
  76058. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76059. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76060. }).forEach(function (obj) {
  76061. obj.callback(_this, otherImpostor);
  76062. });
  76063. }
  76064. };
  76065. //sanity check!
  76066. if (!this.object) {
  76067. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76068. return;
  76069. }
  76070. //legacy support for old syntax.
  76071. if (!this._scene && object.getScene) {
  76072. this._scene = object.getScene();
  76073. }
  76074. if (!this._scene) {
  76075. return;
  76076. }
  76077. this._physicsEngine = this._scene.getPhysicsEngine();
  76078. if (!this._physicsEngine) {
  76079. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76080. }
  76081. else {
  76082. //set the object's quaternion, if not set
  76083. if (!this.object.rotationQuaternion) {
  76084. if (this.object.rotation) {
  76085. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76086. }
  76087. else {
  76088. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76089. }
  76090. }
  76091. //default options params
  76092. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76093. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76094. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76095. this._joints = [];
  76096. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76097. if (!this.object.parent || this._options.ignoreParent) {
  76098. this._init();
  76099. }
  76100. else if (this.object.parent.physicsImpostor) {
  76101. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76102. }
  76103. }
  76104. }
  76105. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76106. get: function () {
  76107. return this._isDisposed;
  76108. },
  76109. enumerable: true,
  76110. configurable: true
  76111. });
  76112. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76113. get: function () {
  76114. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76115. },
  76116. set: function (value) {
  76117. this.setMass(value);
  76118. },
  76119. enumerable: true,
  76120. configurable: true
  76121. });
  76122. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76123. get: function () {
  76124. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76125. },
  76126. set: function (value) {
  76127. if (!this._physicsEngine) {
  76128. return;
  76129. }
  76130. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76131. },
  76132. enumerable: true,
  76133. configurable: true
  76134. });
  76135. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76136. get: function () {
  76137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76138. },
  76139. set: function (value) {
  76140. if (!this._physicsEngine) {
  76141. return;
  76142. }
  76143. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76144. },
  76145. enumerable: true,
  76146. configurable: true
  76147. });
  76148. /**
  76149. * This function will completly initialize this impostor.
  76150. * It will create a new body - but only if this mesh has no parent.
  76151. * If it has, this impostor will not be used other than to define the impostor
  76152. * of the child mesh.
  76153. */
  76154. PhysicsImpostor.prototype._init = function () {
  76155. if (!this._physicsEngine) {
  76156. return;
  76157. }
  76158. this._physicsEngine.removeImpostor(this);
  76159. this.physicsBody = null;
  76160. this._parent = this._parent || this._getPhysicsParent();
  76161. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76162. this._physicsEngine.addImpostor(this);
  76163. }
  76164. };
  76165. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76166. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76167. var parentMesh = this.object.parent;
  76168. return parentMesh.physicsImpostor;
  76169. }
  76170. return null;
  76171. };
  76172. /**
  76173. * Should a new body be generated.
  76174. */
  76175. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76176. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76177. };
  76178. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76179. this.forceUpdate();
  76180. };
  76181. /**
  76182. * Force a regeneration of this or the parent's impostor's body.
  76183. * Use under cautious - This will remove all joints already implemented.
  76184. */
  76185. PhysicsImpostor.prototype.forceUpdate = function () {
  76186. this._init();
  76187. if (this.parent && !this._options.ignoreParent) {
  76188. this.parent.forceUpdate();
  76189. }
  76190. };
  76191. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76192. /*public get mesh(): AbstractMesh {
  76193. return this._mesh;
  76194. }*/
  76195. /**
  76196. * Gets the body that holds this impostor. Either its own, or its parent.
  76197. */
  76198. get: function () {
  76199. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76200. },
  76201. /**
  76202. * Set the physics body. Used mainly by the physics engine/plugin
  76203. */
  76204. set: function (physicsBody) {
  76205. if (this._physicsBody && this._physicsEngine) {
  76206. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76207. }
  76208. this._physicsBody = physicsBody;
  76209. this.resetUpdateFlags();
  76210. },
  76211. enumerable: true,
  76212. configurable: true
  76213. });
  76214. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76215. get: function () {
  76216. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76217. },
  76218. set: function (value) {
  76219. this._parent = value;
  76220. },
  76221. enumerable: true,
  76222. configurable: true
  76223. });
  76224. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76225. this._bodyUpdateRequired = false;
  76226. };
  76227. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76228. if (this.object.getBoundingInfo) {
  76229. var q = this.object.rotationQuaternion;
  76230. //reset rotation
  76231. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76232. //calculate the world matrix with no rotation
  76233. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76234. var boundingInfo = this.object.getBoundingInfo();
  76235. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76236. //bring back the rotation
  76237. this.object.rotationQuaternion = q;
  76238. //calculate the world matrix with the new rotation
  76239. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76240. return size;
  76241. }
  76242. else {
  76243. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76244. }
  76245. };
  76246. PhysicsImpostor.prototype.getObjectCenter = function () {
  76247. if (this.object.getBoundingInfo) {
  76248. var boundingInfo = this.object.getBoundingInfo();
  76249. return boundingInfo.boundingBox.centerWorld;
  76250. }
  76251. else {
  76252. return this.object.position;
  76253. }
  76254. };
  76255. /**
  76256. * Get a specific parametes from the options parameter.
  76257. */
  76258. PhysicsImpostor.prototype.getParam = function (paramName) {
  76259. return this._options[paramName];
  76260. };
  76261. /**
  76262. * Sets a specific parameter in the options given to the physics plugin
  76263. */
  76264. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76265. this._options[paramName] = value;
  76266. this._bodyUpdateRequired = true;
  76267. };
  76268. /**
  76269. * Specifically change the body's mass option. Won't recreate the physics body object
  76270. */
  76271. PhysicsImpostor.prototype.setMass = function (mass) {
  76272. if (this.getParam("mass") !== mass) {
  76273. this.setParam("mass", mass);
  76274. }
  76275. if (this._physicsEngine) {
  76276. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76277. }
  76278. };
  76279. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76280. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76281. };
  76282. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76283. if (this._physicsEngine) {
  76284. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76285. }
  76286. };
  76287. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76288. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76289. };
  76290. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76291. if (this._physicsEngine) {
  76292. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76293. }
  76294. };
  76295. /**
  76296. * Execute a function with the physics plugin native code.
  76297. * Provide a function the will have two variables - the world object and the physics body object.
  76298. */
  76299. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76300. if (this._physicsEngine) {
  76301. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76302. }
  76303. };
  76304. /**
  76305. * Register a function that will be executed before the physics world is stepping forward.
  76306. */
  76307. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76308. this._onBeforePhysicsStepCallbacks.push(func);
  76309. };
  76310. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76311. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76312. if (index > -1) {
  76313. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76314. }
  76315. else {
  76316. BABYLON.Tools.Warn("Function to remove was not found");
  76317. }
  76318. };
  76319. /**
  76320. * Register a function that will be executed after the physics step
  76321. */
  76322. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76323. this._onAfterPhysicsStepCallbacks.push(func);
  76324. };
  76325. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76326. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76327. if (index > -1) {
  76328. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76329. }
  76330. else {
  76331. BABYLON.Tools.Warn("Function to remove was not found");
  76332. }
  76333. };
  76334. /**
  76335. * register a function that will be executed when this impostor collides against a different body.
  76336. */
  76337. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76338. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76339. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76340. };
  76341. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76342. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76343. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76344. if (index > -1) {
  76345. this._onPhysicsCollideCallbacks.splice(index, 1);
  76346. }
  76347. else {
  76348. BABYLON.Tools.Warn("Function to remove was not found");
  76349. }
  76350. };
  76351. PhysicsImpostor.prototype.getParentsRotation = function () {
  76352. var parent = this.object.parent;
  76353. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76354. while (parent) {
  76355. if (parent.rotationQuaternion) {
  76356. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76357. }
  76358. else {
  76359. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76360. }
  76361. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76362. parent = parent.parent;
  76363. }
  76364. return this._tmpQuat;
  76365. };
  76366. /**
  76367. * Apply a force
  76368. */
  76369. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76370. if (this._physicsEngine) {
  76371. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76372. }
  76373. return this;
  76374. };
  76375. /**
  76376. * Apply an impulse
  76377. */
  76378. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76379. if (this._physicsEngine) {
  76380. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76381. }
  76382. return this;
  76383. };
  76384. /**
  76385. * A help function to create a joint.
  76386. */
  76387. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76388. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76389. this.addJoint(otherImpostor, joint);
  76390. return this;
  76391. };
  76392. /**
  76393. * Add a joint to this impostor with a different impostor.
  76394. */
  76395. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76396. this._joints.push({
  76397. otherImpostor: otherImpostor,
  76398. joint: joint
  76399. });
  76400. if (this._physicsEngine) {
  76401. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76402. }
  76403. return this;
  76404. };
  76405. /**
  76406. * Will keep this body still, in a sleep mode.
  76407. */
  76408. PhysicsImpostor.prototype.sleep = function () {
  76409. if (this._physicsEngine) {
  76410. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76411. }
  76412. return this;
  76413. };
  76414. /**
  76415. * Wake the body up.
  76416. */
  76417. PhysicsImpostor.prototype.wakeUp = function () {
  76418. if (this._physicsEngine) {
  76419. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76420. }
  76421. return this;
  76422. };
  76423. PhysicsImpostor.prototype.clone = function (newObject) {
  76424. if (!newObject)
  76425. return null;
  76426. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76427. };
  76428. PhysicsImpostor.prototype.dispose = function () {
  76429. var _this = this;
  76430. //no dispose if no physics engine is available.
  76431. if (!this._physicsEngine) {
  76432. return;
  76433. }
  76434. this._joints.forEach(function (j) {
  76435. if (_this._physicsEngine) {
  76436. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76437. }
  76438. });
  76439. //dispose the physics body
  76440. this._physicsEngine.removeImpostor(this);
  76441. if (this.parent) {
  76442. this.parent.forceUpdate();
  76443. }
  76444. else {
  76445. /*this._object.getChildMeshes().forEach(function(mesh) {
  76446. if (mesh.physicsImpostor) {
  76447. if (disposeChildren) {
  76448. mesh.physicsImpostor.dispose();
  76449. mesh.physicsImpostor = null;
  76450. }
  76451. }
  76452. })*/
  76453. }
  76454. this._isDisposed = true;
  76455. };
  76456. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76457. this._deltaPosition.copyFrom(position);
  76458. };
  76459. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76460. if (!this._deltaRotation) {
  76461. this._deltaRotation = new BABYLON.Quaternion();
  76462. }
  76463. this._deltaRotation.copyFrom(rotation);
  76464. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76465. };
  76466. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76467. if (this._physicsEngine) {
  76468. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76469. }
  76470. return this;
  76471. };
  76472. PhysicsImpostor.prototype.getRadius = function () {
  76473. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76474. };
  76475. /**
  76476. * Sync a bone with this impostor
  76477. * @param bone The bone to sync to the impostor.
  76478. * @param boneMesh The mesh that the bone is influencing.
  76479. * @param jointPivot The pivot of the joint / bone in local space.
  76480. * @param distToJoint Optional distance from the impostor to the joint.
  76481. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76482. */
  76483. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76484. var tempVec = PhysicsImpostor._tmpVecs[0];
  76485. var mesh = this.object;
  76486. if (mesh.rotationQuaternion) {
  76487. if (adjustRotation) {
  76488. var tempQuat = PhysicsImpostor._tmpQuat;
  76489. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76490. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76491. }
  76492. else {
  76493. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76494. }
  76495. }
  76496. tempVec.x = 0;
  76497. tempVec.y = 0;
  76498. tempVec.z = 0;
  76499. if (jointPivot) {
  76500. tempVec.x = jointPivot.x;
  76501. tempVec.y = jointPivot.y;
  76502. tempVec.z = jointPivot.z;
  76503. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76504. if (distToJoint === undefined || distToJoint === null) {
  76505. distToJoint = jointPivot.length();
  76506. }
  76507. tempVec.x *= distToJoint;
  76508. tempVec.y *= distToJoint;
  76509. tempVec.z *= distToJoint;
  76510. }
  76511. if (bone.getParent()) {
  76512. tempVec.addInPlace(mesh.getAbsolutePosition());
  76513. bone.setAbsolutePosition(tempVec, boneMesh);
  76514. }
  76515. else {
  76516. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76517. boneMesh.position.x -= tempVec.x;
  76518. boneMesh.position.y -= tempVec.y;
  76519. boneMesh.position.z -= tempVec.z;
  76520. }
  76521. };
  76522. /**
  76523. * Sync impostor to a bone
  76524. * @param bone The bone that the impostor will be synced to.
  76525. * @param boneMesh The mesh that the bone is influencing.
  76526. * @param jointPivot The pivot of the joint / bone in local space.
  76527. * @param distToJoint Optional distance from the impostor to the joint.
  76528. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76529. * @param boneAxis Optional vector3 axis the bone is aligned with
  76530. */
  76531. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76532. var mesh = this.object;
  76533. if (mesh.rotationQuaternion) {
  76534. if (adjustRotation) {
  76535. var tempQuat = PhysicsImpostor._tmpQuat;
  76536. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76537. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76538. }
  76539. else {
  76540. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76541. }
  76542. }
  76543. var pos = PhysicsImpostor._tmpVecs[0];
  76544. var boneDir = PhysicsImpostor._tmpVecs[1];
  76545. if (!boneAxis) {
  76546. boneAxis = PhysicsImpostor._tmpVecs[2];
  76547. boneAxis.x = 0;
  76548. boneAxis.y = 1;
  76549. boneAxis.z = 0;
  76550. }
  76551. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76552. bone.getAbsolutePositionToRef(boneMesh, pos);
  76553. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76554. distToJoint = jointPivot.length();
  76555. }
  76556. if (distToJoint !== undefined && distToJoint !== null) {
  76557. pos.x += boneDir.x * distToJoint;
  76558. pos.y += boneDir.y * distToJoint;
  76559. pos.z += boneDir.z * distToJoint;
  76560. }
  76561. mesh.setAbsolutePosition(pos);
  76562. };
  76563. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76564. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76565. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76566. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76567. //Impostor types
  76568. PhysicsImpostor.NoImpostor = 0;
  76569. PhysicsImpostor.SphereImpostor = 1;
  76570. PhysicsImpostor.BoxImpostor = 2;
  76571. PhysicsImpostor.PlaneImpostor = 3;
  76572. PhysicsImpostor.MeshImpostor = 4;
  76573. PhysicsImpostor.CylinderImpostor = 7;
  76574. PhysicsImpostor.ParticleImpostor = 8;
  76575. PhysicsImpostor.HeightmapImpostor = 9;
  76576. return PhysicsImpostor;
  76577. }());
  76578. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76579. })(BABYLON || (BABYLON = {}));
  76580. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76581. var BABYLON;
  76582. (function (BABYLON) {
  76583. var PhysicsEngine = /** @class */ (function () {
  76584. function PhysicsEngine(gravity, _physicsPlugin) {
  76585. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76586. this._physicsPlugin = _physicsPlugin;
  76587. //new methods and parameters
  76588. this._impostors = [];
  76589. this._joints = [];
  76590. if (!this._physicsPlugin.isSupported()) {
  76591. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76592. + "Please make sure it is included.");
  76593. }
  76594. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76595. this.setGravity(gravity);
  76596. this.setTimeStep();
  76597. }
  76598. PhysicsEngine.prototype.setGravity = function (gravity) {
  76599. this.gravity = gravity;
  76600. this._physicsPlugin.setGravity(this.gravity);
  76601. };
  76602. /**
  76603. * Set the time step of the physics engine.
  76604. * default is 1/60.
  76605. * To slow it down, enter 1/600 for example.
  76606. * To speed it up, 1/30
  76607. * @param {number} newTimeStep the new timestep to apply to this world.
  76608. */
  76609. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76610. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76611. this._physicsPlugin.setTimeStep(newTimeStep);
  76612. };
  76613. /**
  76614. * Get the time step of the physics engine.
  76615. */
  76616. PhysicsEngine.prototype.getTimeStep = function () {
  76617. return this._physicsPlugin.getTimeStep();
  76618. };
  76619. PhysicsEngine.prototype.dispose = function () {
  76620. this._impostors.forEach(function (impostor) {
  76621. impostor.dispose();
  76622. });
  76623. this._physicsPlugin.dispose();
  76624. };
  76625. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76626. return this._physicsPlugin.name;
  76627. };
  76628. /**
  76629. * Adding a new impostor for the impostor tracking.
  76630. * This will be done by the impostor itself.
  76631. * @param {PhysicsImpostor} impostor the impostor to add
  76632. */
  76633. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76634. impostor.uniqueId = this._impostors.push(impostor);
  76635. //if no parent, generate the body
  76636. if (!impostor.parent) {
  76637. this._physicsPlugin.generatePhysicsBody(impostor);
  76638. }
  76639. };
  76640. /**
  76641. * Remove an impostor from the engine.
  76642. * This impostor and its mesh will not longer be updated by the physics engine.
  76643. * @param {PhysicsImpostor} impostor the impostor to remove
  76644. */
  76645. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76646. var index = this._impostors.indexOf(impostor);
  76647. if (index > -1) {
  76648. var removed = this._impostors.splice(index, 1);
  76649. //Is it needed?
  76650. if (removed.length) {
  76651. //this will also remove it from the world.
  76652. removed[0].physicsBody = null;
  76653. }
  76654. }
  76655. };
  76656. /**
  76657. * Add a joint to the physics engine
  76658. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76659. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76660. * @param {PhysicsJoint} the joint that will connect both impostors.
  76661. */
  76662. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76663. var impostorJoint = {
  76664. mainImpostor: mainImpostor,
  76665. connectedImpostor: connectedImpostor,
  76666. joint: joint
  76667. };
  76668. joint.physicsPlugin = this._physicsPlugin;
  76669. this._joints.push(impostorJoint);
  76670. this._physicsPlugin.generateJoint(impostorJoint);
  76671. };
  76672. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76673. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76674. return (impostorJoint.connectedImpostor === connectedImpostor
  76675. && impostorJoint.joint === joint
  76676. && impostorJoint.mainImpostor === mainImpostor);
  76677. });
  76678. if (matchingJoints.length) {
  76679. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76680. //TODO remove it from the list as well
  76681. }
  76682. };
  76683. /**
  76684. * Called by the scene. no need to call it.
  76685. */
  76686. PhysicsEngine.prototype._step = function (delta) {
  76687. var _this = this;
  76688. //check if any mesh has no body / requires an update
  76689. this._impostors.forEach(function (impostor) {
  76690. if (impostor.isBodyInitRequired()) {
  76691. _this._physicsPlugin.generatePhysicsBody(impostor);
  76692. }
  76693. });
  76694. if (delta > 0.1) {
  76695. delta = 0.1;
  76696. }
  76697. else if (delta <= 0) {
  76698. delta = 1.0 / 60.0;
  76699. }
  76700. this._physicsPlugin.executeStep(delta, this._impostors);
  76701. };
  76702. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76703. return this._physicsPlugin;
  76704. };
  76705. PhysicsEngine.prototype.getImpostors = function () {
  76706. return this._impostors;
  76707. };
  76708. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76709. for (var i = 0; i < this._impostors.length; ++i) {
  76710. if (this._impostors[i].object === object) {
  76711. return this._impostors[i];
  76712. }
  76713. }
  76714. return null;
  76715. };
  76716. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76717. for (var i = 0; i < this._impostors.length; ++i) {
  76718. if (this._impostors[i].physicsBody === body) {
  76719. return this._impostors[i];
  76720. }
  76721. }
  76722. return null;
  76723. };
  76724. // Statics
  76725. PhysicsEngine.Epsilon = 0.001;
  76726. return PhysicsEngine;
  76727. }());
  76728. BABYLON.PhysicsEngine = PhysicsEngine;
  76729. })(BABYLON || (BABYLON = {}));
  76730. //# sourceMappingURL=babylon.physicsEngine.js.map
  76731. var BABYLON;
  76732. (function (BABYLON) {
  76733. var PhysicsHelper = /** @class */ (function () {
  76734. function PhysicsHelper(scene) {
  76735. this._scene = scene;
  76736. this._physicsEngine = this._scene.getPhysicsEngine();
  76737. if (!this._physicsEngine) {
  76738. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76739. }
  76740. }
  76741. /**
  76742. * @param {Vector3} origin the origin of the explosion
  76743. * @param {number} radius the explosion radius
  76744. * @param {number} strength the explosion strength
  76745. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76746. */
  76747. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76748. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76749. if (!this._physicsEngine) {
  76750. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76751. return null;
  76752. }
  76753. var impostors = this._physicsEngine.getImpostors();
  76754. if (impostors.length === 0) {
  76755. return null;
  76756. }
  76757. var event = new PhysicsRadialExplosionEvent(this._scene);
  76758. impostors.forEach(function (impostor) {
  76759. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76760. if (!impostorForceAndContactPoint) {
  76761. return;
  76762. }
  76763. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76764. });
  76765. event.dispose(false);
  76766. return event;
  76767. };
  76768. /**
  76769. * @param {Vector3} origin the origin of the explosion
  76770. * @param {number} radius the explosion radius
  76771. * @param {number} strength the explosion strength
  76772. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76773. */
  76774. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76775. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76776. if (!this._physicsEngine) {
  76777. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76778. return null;
  76779. }
  76780. var impostors = this._physicsEngine.getImpostors();
  76781. if (impostors.length === 0) {
  76782. return null;
  76783. }
  76784. var event = new PhysicsRadialExplosionEvent(this._scene);
  76785. impostors.forEach(function (impostor) {
  76786. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76787. if (!impostorForceAndContactPoint) {
  76788. return;
  76789. }
  76790. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76791. });
  76792. event.dispose(false);
  76793. return event;
  76794. };
  76795. /**
  76796. * @param {Vector3} origin the origin of the explosion
  76797. * @param {number} radius the explosion radius
  76798. * @param {number} strength the explosion strength
  76799. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76800. */
  76801. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76802. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76803. if (!this._physicsEngine) {
  76804. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76805. return null;
  76806. }
  76807. var impostors = this._physicsEngine.getImpostors();
  76808. if (impostors.length === 0) {
  76809. return null;
  76810. }
  76811. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76812. event.dispose(false);
  76813. return event;
  76814. };
  76815. /**
  76816. * @param {Vector3} origin the origin of the updraft
  76817. * @param {number} radius the radius of the updraft
  76818. * @param {number} strength the strength of the updraft
  76819. * @param {number} height the height of the updraft
  76820. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76821. */
  76822. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76823. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76824. if (!this._physicsEngine) {
  76825. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76826. return null;
  76827. }
  76828. if (this._physicsEngine.getImpostors().length === 0) {
  76829. return null;
  76830. }
  76831. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76832. event.dispose(false);
  76833. return event;
  76834. };
  76835. /**
  76836. * @param {Vector3} origin the of the vortex
  76837. * @param {number} radius the radius of the vortex
  76838. * @param {number} strength the strength of the vortex
  76839. * @param {number} height the height of the vortex
  76840. */
  76841. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76842. if (!this._physicsEngine) {
  76843. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76844. return null;
  76845. }
  76846. if (this._physicsEngine.getImpostors().length === 0) {
  76847. return null;
  76848. }
  76849. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76850. event.dispose(false);
  76851. return event;
  76852. };
  76853. return PhysicsHelper;
  76854. }());
  76855. BABYLON.PhysicsHelper = PhysicsHelper;
  76856. /***** Radial explosion *****/
  76857. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76858. function PhysicsRadialExplosionEvent(scene) {
  76859. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76860. this._rays = [];
  76861. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76862. this._scene = scene;
  76863. }
  76864. /**
  76865. * Returns the data related to the radial explosion event (sphere & rays).
  76866. * @returns {PhysicsRadialExplosionEventData}
  76867. */
  76868. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76869. this._dataFetched = true;
  76870. return {
  76871. sphere: this._sphere,
  76872. rays: this._rays,
  76873. };
  76874. };
  76875. /**
  76876. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76877. * @param impostor
  76878. * @param {Vector3} origin the origin of the explosion
  76879. * @param {number} radius the explosion radius
  76880. * @param {number} strength the explosion strength
  76881. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76882. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76883. */
  76884. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76885. if (impostor.mass === 0) {
  76886. return null;
  76887. }
  76888. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76889. return null;
  76890. }
  76891. if (impostor.object.getClassName() !== 'Mesh') {
  76892. return null;
  76893. }
  76894. var impostorObject = impostor.object;
  76895. var impostorObjectCenter = impostor.getObjectCenter();
  76896. var direction = impostorObjectCenter.subtract(origin);
  76897. var ray = new BABYLON.Ray(origin, direction, radius);
  76898. this._rays.push(ray);
  76899. var hit = ray.intersectsMesh(impostorObject);
  76900. var contactPoint = hit.pickedPoint;
  76901. if (!contactPoint) {
  76902. return null;
  76903. }
  76904. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76905. if (distanceFromOrigin > radius) {
  76906. return null;
  76907. }
  76908. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76909. ? strength
  76910. : strength * (1 - (distanceFromOrigin / radius));
  76911. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76912. return { force: force, contactPoint: contactPoint };
  76913. };
  76914. /**
  76915. * Disposes the sphere.
  76916. * @param {bolean} force
  76917. */
  76918. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76919. var _this = this;
  76920. if (force === void 0) { force = true; }
  76921. if (force) {
  76922. this._sphere.dispose();
  76923. }
  76924. else {
  76925. setTimeout(function () {
  76926. if (!_this._dataFetched) {
  76927. _this._sphere.dispose();
  76928. }
  76929. }, 0);
  76930. }
  76931. };
  76932. /*** Helpers ***/
  76933. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76934. if (!this._sphere) {
  76935. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76936. this._sphere.isVisible = false;
  76937. }
  76938. };
  76939. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76940. var impostorObject = impostor.object;
  76941. this._prepareSphere();
  76942. this._sphere.position = origin;
  76943. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76944. this._sphere._updateBoundingInfo();
  76945. this._sphere.computeWorldMatrix(true);
  76946. return this._sphere.intersectsMesh(impostorObject, true);
  76947. };
  76948. return PhysicsRadialExplosionEvent;
  76949. }());
  76950. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76951. /***** Gravitational Field *****/
  76952. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76953. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76954. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76955. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76956. this._physicsHelper = physicsHelper;
  76957. this._scene = scene;
  76958. this._origin = origin;
  76959. this._radius = radius;
  76960. this._strength = strength;
  76961. this._falloff = falloff;
  76962. this._tickCallback = this._tick.bind(this);
  76963. }
  76964. /**
  76965. * Returns the data related to the gravitational field event (sphere).
  76966. * @returns {PhysicsGravitationalFieldEventData}
  76967. */
  76968. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76969. this._dataFetched = true;
  76970. return {
  76971. sphere: this._sphere,
  76972. };
  76973. };
  76974. /**
  76975. * Enables the gravitational field.
  76976. */
  76977. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76978. this._tickCallback.call(this);
  76979. this._scene.registerBeforeRender(this._tickCallback);
  76980. };
  76981. /**
  76982. * Disables the gravitational field.
  76983. */
  76984. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76985. this._scene.unregisterBeforeRender(this._tickCallback);
  76986. };
  76987. /**
  76988. * Disposes the sphere.
  76989. * @param {bolean} force
  76990. */
  76991. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76992. var _this = this;
  76993. if (force === void 0) { force = true; }
  76994. if (force) {
  76995. this._sphere.dispose();
  76996. }
  76997. else {
  76998. setTimeout(function () {
  76999. if (!_this._dataFetched) {
  77000. _this._sphere.dispose();
  77001. }
  77002. }, 0);
  77003. }
  77004. };
  77005. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77006. // Since the params won't change, we fetch the event only once
  77007. if (this._sphere) {
  77008. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77009. }
  77010. else {
  77011. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77012. if (radialExplosionEvent) {
  77013. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77014. }
  77015. }
  77016. };
  77017. return PhysicsGravitationalFieldEvent;
  77018. }());
  77019. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77020. /***** Updraft *****/
  77021. var PhysicsUpdraftEvent = /** @class */ (function () {
  77022. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77023. this._scene = _scene;
  77024. this._origin = _origin;
  77025. this._radius = _radius;
  77026. this._strength = _strength;
  77027. this._height = _height;
  77028. this._updraftMode = _updraftMode;
  77029. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77030. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77031. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77032. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77033. this._physicsEngine = this._scene.getPhysicsEngine();
  77034. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77035. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77036. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77037. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77038. }
  77039. this._tickCallback = this._tick.bind(this);
  77040. }
  77041. /**
  77042. * Returns the data related to the updraft event (cylinder).
  77043. * @returns {PhysicsUpdraftEventData}
  77044. */
  77045. PhysicsUpdraftEvent.prototype.getData = function () {
  77046. this._dataFetched = true;
  77047. return {
  77048. cylinder: this._cylinder,
  77049. };
  77050. };
  77051. /**
  77052. * Enables the updraft.
  77053. */
  77054. PhysicsUpdraftEvent.prototype.enable = function () {
  77055. this._tickCallback.call(this);
  77056. this._scene.registerBeforeRender(this._tickCallback);
  77057. };
  77058. /**
  77059. * Disables the cortex.
  77060. */
  77061. PhysicsUpdraftEvent.prototype.disable = function () {
  77062. this._scene.unregisterBeforeRender(this._tickCallback);
  77063. };
  77064. /**
  77065. * Disposes the sphere.
  77066. * @param {bolean} force
  77067. */
  77068. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77069. var _this = this;
  77070. if (force === void 0) { force = true; }
  77071. if (force) {
  77072. this._cylinder.dispose();
  77073. }
  77074. else {
  77075. setTimeout(function () {
  77076. if (!_this._dataFetched) {
  77077. _this._cylinder.dispose();
  77078. }
  77079. }, 0);
  77080. }
  77081. };
  77082. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77083. if (impostor.mass === 0) {
  77084. return null;
  77085. }
  77086. if (!this._intersectsWithCylinder(impostor)) {
  77087. return null;
  77088. }
  77089. var impostorObjectCenter = impostor.getObjectCenter();
  77090. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77091. var direction = this._originDirection;
  77092. }
  77093. else {
  77094. var direction = impostorObjectCenter.subtract(this._originTop);
  77095. }
  77096. var multiplier = this._strength * -1;
  77097. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77098. return { force: force, contactPoint: impostorObjectCenter };
  77099. };
  77100. PhysicsUpdraftEvent.prototype._tick = function () {
  77101. var _this = this;
  77102. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77103. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77104. if (!impostorForceAndContactPoint) {
  77105. return;
  77106. }
  77107. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77108. });
  77109. };
  77110. /*** Helpers ***/
  77111. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77112. if (!this._cylinder) {
  77113. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77114. height: this._height,
  77115. diameter: this._radius * 2,
  77116. }, this._scene);
  77117. this._cylinder.isVisible = false;
  77118. }
  77119. };
  77120. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77121. var impostorObject = impostor.object;
  77122. this._prepareCylinder();
  77123. this._cylinder.position = this._cylinderPosition;
  77124. return this._cylinder.intersectsMesh(impostorObject, true);
  77125. };
  77126. return PhysicsUpdraftEvent;
  77127. }());
  77128. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77129. /***** Vortex *****/
  77130. var PhysicsVortexEvent = /** @class */ (function () {
  77131. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77132. this._scene = _scene;
  77133. this._origin = _origin;
  77134. this._radius = _radius;
  77135. this._strength = _strength;
  77136. this._height = _height;
  77137. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77138. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77139. this._updraftMultiplier = 0.02;
  77140. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77141. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77142. this._physicsEngine = this._scene.getPhysicsEngine();
  77143. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77144. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77145. this._tickCallback = this._tick.bind(this);
  77146. }
  77147. /**
  77148. * Returns the data related to the vortex event (cylinder).
  77149. * @returns {PhysicsVortexEventData}
  77150. */
  77151. PhysicsVortexEvent.prototype.getData = function () {
  77152. this._dataFetched = true;
  77153. return {
  77154. cylinder: this._cylinder,
  77155. };
  77156. };
  77157. /**
  77158. * Enables the vortex.
  77159. */
  77160. PhysicsVortexEvent.prototype.enable = function () {
  77161. this._tickCallback.call(this);
  77162. this._scene.registerBeforeRender(this._tickCallback);
  77163. };
  77164. /**
  77165. * Disables the cortex.
  77166. */
  77167. PhysicsVortexEvent.prototype.disable = function () {
  77168. this._scene.unregisterBeforeRender(this._tickCallback);
  77169. };
  77170. /**
  77171. * Disposes the sphere.
  77172. * @param {bolean} force
  77173. */
  77174. PhysicsVortexEvent.prototype.dispose = function (force) {
  77175. var _this = this;
  77176. if (force === void 0) { force = true; }
  77177. if (force) {
  77178. this._cylinder.dispose();
  77179. }
  77180. else {
  77181. setTimeout(function () {
  77182. if (!_this._dataFetched) {
  77183. _this._cylinder.dispose();
  77184. }
  77185. }, 0);
  77186. }
  77187. };
  77188. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77189. if (impostor.mass === 0) {
  77190. return null;
  77191. }
  77192. if (!this._intersectsWithCylinder(impostor)) {
  77193. return null;
  77194. }
  77195. if (impostor.object.getClassName() !== 'Mesh') {
  77196. return null;
  77197. }
  77198. var impostorObject = impostor.object;
  77199. var impostorObjectCenter = impostor.getObjectCenter();
  77200. 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)
  77201. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77202. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77203. var hit = ray.intersectsMesh(impostorObject);
  77204. var contactPoint = hit.pickedPoint;
  77205. if (!contactPoint) {
  77206. return null;
  77207. }
  77208. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77209. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77210. var directionToOrigin = contactPoint.normalize();
  77211. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77212. directionToOrigin = directionToOrigin.negate();
  77213. }
  77214. // TODO: find a more physically based solution
  77215. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77216. var forceX = directionToOrigin.x * this._strength / 8;
  77217. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77218. var forceZ = directionToOrigin.z * this._strength / 8;
  77219. }
  77220. else {
  77221. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77222. var forceY = this._originTop.y * this._updraftMultiplier;
  77223. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77224. }
  77225. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77226. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77227. return { force: force, contactPoint: impostorObjectCenter };
  77228. };
  77229. PhysicsVortexEvent.prototype._tick = function () {
  77230. var _this = this;
  77231. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77232. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77233. if (!impostorForceAndContactPoint) {
  77234. return;
  77235. }
  77236. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77237. });
  77238. };
  77239. /*** Helpers ***/
  77240. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77241. if (!this._cylinder) {
  77242. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77243. height: this._height,
  77244. diameter: this._radius * 2,
  77245. }, this._scene);
  77246. this._cylinder.isVisible = false;
  77247. }
  77248. };
  77249. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77250. var impostorObject = impostor.object;
  77251. this._prepareCylinder();
  77252. this._cylinder.position = this._cylinderPosition;
  77253. return this._cylinder.intersectsMesh(impostorObject, true);
  77254. };
  77255. return PhysicsVortexEvent;
  77256. }());
  77257. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77258. /***** Enums *****/
  77259. /**
  77260. * The strenght of the force in correspondence to the distance of the affected object
  77261. */
  77262. var PhysicsRadialImpulseFalloff;
  77263. (function (PhysicsRadialImpulseFalloff) {
  77264. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77265. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77266. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77267. /**
  77268. * The strenght of the force in correspondence to the distance of the affected object
  77269. */
  77270. var PhysicsUpdraftMode;
  77271. (function (PhysicsUpdraftMode) {
  77272. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77273. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77274. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77275. })(BABYLON || (BABYLON = {}));
  77276. //# sourceMappingURL=babylon.physicsHelper.js.map
  77277. var BABYLON;
  77278. (function (BABYLON) {
  77279. var CannonJSPlugin = /** @class */ (function () {
  77280. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77281. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77282. if (iterations === void 0) { iterations = 10; }
  77283. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77284. this.name = "CannonJSPlugin";
  77285. this._physicsMaterials = new Array();
  77286. this._fixedTimeStep = 1 / 60;
  77287. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77288. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77289. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77290. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77291. this._tmpPosition = BABYLON.Vector3.Zero();
  77292. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77293. this._tmpUnityRotation = new BABYLON.Quaternion();
  77294. if (!this.isSupported()) {
  77295. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77296. return;
  77297. }
  77298. this._extendNamespace();
  77299. this.world = new this.BJSCANNON.World();
  77300. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77301. this.world.solver.iterations = iterations;
  77302. }
  77303. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77304. this.world.gravity.copy(gravity);
  77305. };
  77306. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77307. this._fixedTimeStep = timeStep;
  77308. };
  77309. CannonJSPlugin.prototype.getTimeStep = function () {
  77310. return this._fixedTimeStep;
  77311. };
  77312. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77313. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77314. };
  77315. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77316. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77317. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77318. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77319. };
  77320. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77321. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77322. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77323. impostor.physicsBody.applyForce(impulse, worldPoint);
  77324. };
  77325. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77326. //parent-child relationship. Does this impostor has a parent impostor?
  77327. if (impostor.parent) {
  77328. if (impostor.physicsBody) {
  77329. this.removePhysicsBody(impostor);
  77330. //TODO is that needed?
  77331. impostor.forceUpdate();
  77332. }
  77333. return;
  77334. }
  77335. //should a new body be created for this impostor?
  77336. if (impostor.isBodyInitRequired()) {
  77337. var shape = this._createShape(impostor);
  77338. //unregister events, if body is being changed
  77339. var oldBody = impostor.physicsBody;
  77340. if (oldBody) {
  77341. this.removePhysicsBody(impostor);
  77342. }
  77343. //create the body and material
  77344. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77345. var bodyCreationObject = {
  77346. mass: impostor.getParam("mass"),
  77347. material: material
  77348. };
  77349. // A simple extend, in case native options were used.
  77350. var nativeOptions = impostor.getParam("nativeOptions");
  77351. for (var key in nativeOptions) {
  77352. if (nativeOptions.hasOwnProperty(key)) {
  77353. bodyCreationObject[key] = nativeOptions[key];
  77354. }
  77355. }
  77356. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77357. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77358. this.world.addEventListener("preStep", impostor.beforeStep);
  77359. this.world.addEventListener("postStep", impostor.afterStep);
  77360. impostor.physicsBody.addShape(shape);
  77361. this.world.add(impostor.physicsBody);
  77362. //try to keep the body moving in the right direction by taking old properties.
  77363. //Should be tested!
  77364. if (oldBody) {
  77365. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77366. impostor.physicsBody[param].copy(oldBody[param]);
  77367. });
  77368. }
  77369. this._processChildMeshes(impostor);
  77370. }
  77371. //now update the body's transformation
  77372. this._updatePhysicsBodyTransformation(impostor);
  77373. };
  77374. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77375. var _this = this;
  77376. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77377. var currentRotation = mainImpostor.object.rotationQuaternion;
  77378. if (meshChildren.length) {
  77379. var processMesh = function (localPosition, mesh) {
  77380. if (!currentRotation || !mesh.rotationQuaternion) {
  77381. return;
  77382. }
  77383. var childImpostor = mesh.getPhysicsImpostor();
  77384. if (childImpostor) {
  77385. var parent = childImpostor.parent;
  77386. if (parent !== mainImpostor) {
  77387. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77388. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77389. if (childImpostor.physicsBody) {
  77390. _this.removePhysicsBody(childImpostor);
  77391. childImpostor.physicsBody = null;
  77392. }
  77393. childImpostor.parent = mainImpostor;
  77394. childImpostor.resetUpdateFlags();
  77395. 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));
  77396. //Add the mass of the children.
  77397. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77398. }
  77399. }
  77400. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77401. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77402. };
  77403. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77404. }
  77405. };
  77406. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77407. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77408. this.world.removeEventListener("preStep", impostor.beforeStep);
  77409. this.world.removeEventListener("postStep", impostor.afterStep);
  77410. this.world.remove(impostor.physicsBody);
  77411. };
  77412. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77413. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77414. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77415. if (!mainBody || !connectedBody) {
  77416. return;
  77417. }
  77418. var constraint;
  77419. var jointData = impostorJoint.joint.jointData;
  77420. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77421. var constraintData = {
  77422. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77423. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77424. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77425. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77426. maxForce: jointData.nativeParams.maxForce,
  77427. collideConnected: !!jointData.collision
  77428. };
  77429. switch (impostorJoint.joint.type) {
  77430. case BABYLON.PhysicsJoint.HingeJoint:
  77431. case BABYLON.PhysicsJoint.Hinge2Joint:
  77432. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77433. break;
  77434. case BABYLON.PhysicsJoint.DistanceJoint:
  77435. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77436. break;
  77437. case BABYLON.PhysicsJoint.SpringJoint:
  77438. var springData = jointData;
  77439. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77440. restLength: springData.length,
  77441. stiffness: springData.stiffness,
  77442. damping: springData.damping,
  77443. localAnchorA: constraintData.pivotA,
  77444. localAnchorB: constraintData.pivotB
  77445. });
  77446. break;
  77447. case BABYLON.PhysicsJoint.LockJoint:
  77448. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77449. break;
  77450. case BABYLON.PhysicsJoint.PointToPointJoint:
  77451. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77452. default:
  77453. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77454. break;
  77455. }
  77456. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77457. constraint.collideConnected = !!jointData.collision;
  77458. impostorJoint.joint.physicsJoint = constraint;
  77459. //don't add spring as constraint, as it is not one.
  77460. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77461. this.world.addConstraint(constraint);
  77462. }
  77463. else {
  77464. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77465. constraint.applyForce();
  77466. });
  77467. }
  77468. };
  77469. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77470. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77471. };
  77472. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77473. var index;
  77474. var mat;
  77475. for (index = 0; index < this._physicsMaterials.length; index++) {
  77476. mat = this._physicsMaterials[index];
  77477. if (mat.friction === friction && mat.restitution === restitution) {
  77478. return mat;
  77479. }
  77480. }
  77481. var currentMat = new this.BJSCANNON.Material(name);
  77482. currentMat.friction = friction;
  77483. currentMat.restitution = restitution;
  77484. this._physicsMaterials.push(currentMat);
  77485. return currentMat;
  77486. };
  77487. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77488. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77489. };
  77490. CannonJSPlugin.prototype._createShape = function (impostor) {
  77491. var object = impostor.object;
  77492. var returnValue;
  77493. var extendSize = impostor.getObjectExtendSize();
  77494. switch (impostor.type) {
  77495. case BABYLON.PhysicsImpostor.SphereImpostor:
  77496. var radiusX = extendSize.x;
  77497. var radiusY = extendSize.y;
  77498. var radiusZ = extendSize.z;
  77499. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77500. break;
  77501. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77502. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77503. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77504. break;
  77505. case BABYLON.PhysicsImpostor.BoxImpostor:
  77506. var box = extendSize.scale(0.5);
  77507. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77508. break;
  77509. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77510. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77511. returnValue = new this.BJSCANNON.Plane();
  77512. break;
  77513. case BABYLON.PhysicsImpostor.MeshImpostor:
  77514. // should transform the vertex data to world coordinates!!
  77515. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77516. var rawFaces = object.getIndices ? object.getIndices() : [];
  77517. if (!rawVerts)
  77518. return;
  77519. // get only scale! so the object could transform correctly.
  77520. var oldPosition = object.position.clone();
  77521. var oldRotation = object.rotation && object.rotation.clone();
  77522. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77523. object.position.copyFromFloats(0, 0, 0);
  77524. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77525. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77526. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77527. var transform = object.computeWorldMatrix(true);
  77528. // convert rawVerts to object space
  77529. var temp = new Array();
  77530. var index;
  77531. for (index = 0; index < rawVerts.length; index += 3) {
  77532. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77533. }
  77534. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77535. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77536. //now set back the transformation!
  77537. object.position.copyFrom(oldPosition);
  77538. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77539. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77540. break;
  77541. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77542. var oldPosition2 = object.position.clone();
  77543. var oldRotation2 = object.rotation && object.rotation.clone();
  77544. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77545. object.position.copyFromFloats(0, 0, 0);
  77546. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77547. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77548. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77549. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77550. returnValue = this._createHeightmap(object);
  77551. object.position.copyFrom(oldPosition2);
  77552. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77553. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77554. object.computeWorldMatrix(true);
  77555. break;
  77556. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77557. returnValue = new this.BJSCANNON.Particle();
  77558. break;
  77559. }
  77560. return returnValue;
  77561. };
  77562. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77563. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77564. var transform = object.computeWorldMatrix(true);
  77565. // convert rawVerts to object space
  77566. var temp = new Array();
  77567. var index;
  77568. for (index = 0; index < pos.length; index += 3) {
  77569. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77570. }
  77571. pos = temp;
  77572. var matrix = new Array();
  77573. //For now pointDepth will not be used and will be automatically calculated.
  77574. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77575. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77576. var boundingInfo = object.getBoundingInfo();
  77577. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77578. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77579. var elementSize = dim * 2 / arraySize;
  77580. for (var i = 0; i < pos.length; i = i + 3) {
  77581. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77582. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77583. var y = -pos[i + 2] + minY;
  77584. if (!matrix[x]) {
  77585. matrix[x] = [];
  77586. }
  77587. if (!matrix[x][z]) {
  77588. matrix[x][z] = y;
  77589. }
  77590. matrix[x][z] = Math.max(y, matrix[x][z]);
  77591. }
  77592. for (var x = 0; x <= arraySize; ++x) {
  77593. if (!matrix[x]) {
  77594. var loc = 1;
  77595. while (!matrix[(x + loc) % arraySize]) {
  77596. loc++;
  77597. }
  77598. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77599. //console.log("missing x", x);
  77600. }
  77601. for (var z = 0; z <= arraySize; ++z) {
  77602. if (!matrix[x][z]) {
  77603. var loc = 1;
  77604. var newValue;
  77605. while (newValue === undefined) {
  77606. newValue = matrix[x][(z + loc++) % arraySize];
  77607. }
  77608. matrix[x][z] = newValue;
  77609. }
  77610. }
  77611. }
  77612. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77613. elementSize: elementSize
  77614. });
  77615. //For future reference, needed for body transformation
  77616. shape.minY = minY;
  77617. return shape;
  77618. };
  77619. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77620. var object = impostor.object;
  77621. //make sure it is updated...
  77622. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77623. // The delta between the mesh position and the mesh bounding box center
  77624. var bInfo = object.getBoundingInfo();
  77625. if (!bInfo)
  77626. return;
  77627. var center = impostor.getObjectCenter();
  77628. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77629. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77630. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77631. this._tmpPosition.copyFrom(center);
  77632. var quaternion = object.rotationQuaternion;
  77633. if (!quaternion) {
  77634. return;
  77635. }
  77636. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77637. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77638. //-90 DEG in X, precalculated
  77639. quaternion = quaternion.multiply(this._minus90X);
  77640. //Invert! (Precalculated, 90 deg in X)
  77641. //No need to clone. this will never change.
  77642. impostor.setDeltaRotation(this._plus90X);
  77643. }
  77644. //If it is a heightfield, if should be centered.
  77645. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77646. var mesh = object;
  77647. var boundingInfo = mesh.getBoundingInfo();
  77648. //calculate the correct body position:
  77649. var rotationQuaternion = mesh.rotationQuaternion;
  77650. mesh.rotationQuaternion = this._tmpUnityRotation;
  77651. mesh.computeWorldMatrix(true);
  77652. //get original center with no rotation
  77653. var c = center.clone();
  77654. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77655. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77656. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77657. mesh.setPreTransformMatrix(p);
  77658. mesh.computeWorldMatrix(true);
  77659. //calculate the translation
  77660. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77661. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77662. //add it inverted to the delta
  77663. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77664. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77665. //rotation is back
  77666. mesh.rotationQuaternion = rotationQuaternion;
  77667. mesh.setPreTransformMatrix(oldPivot);
  77668. mesh.computeWorldMatrix(true);
  77669. }
  77670. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77671. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77672. //this._tmpPosition.copyFrom(object.position);
  77673. }
  77674. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77675. //Now update the impostor object
  77676. impostor.physicsBody.position.copy(this._tmpPosition);
  77677. impostor.physicsBody.quaternion.copy(quaternion);
  77678. };
  77679. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77680. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77681. if (impostor.object.rotationQuaternion) {
  77682. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77683. }
  77684. };
  77685. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77686. impostor.physicsBody.position.copy(newPosition);
  77687. impostor.physicsBody.quaternion.copy(newRotation);
  77688. };
  77689. CannonJSPlugin.prototype.isSupported = function () {
  77690. return this.BJSCANNON !== undefined;
  77691. };
  77692. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77693. impostor.physicsBody.velocity.copy(velocity);
  77694. };
  77695. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77696. impostor.physicsBody.angularVelocity.copy(velocity);
  77697. };
  77698. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77699. var v = impostor.physicsBody.velocity;
  77700. if (!v) {
  77701. return null;
  77702. }
  77703. return new BABYLON.Vector3(v.x, v.y, v.z);
  77704. };
  77705. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77706. var v = impostor.physicsBody.angularVelocity;
  77707. if (!v) {
  77708. return null;
  77709. }
  77710. return new BABYLON.Vector3(v.x, v.y, v.z);
  77711. };
  77712. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77713. impostor.physicsBody.mass = mass;
  77714. impostor.physicsBody.updateMassProperties();
  77715. };
  77716. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77717. return impostor.physicsBody.mass;
  77718. };
  77719. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77720. return impostor.physicsBody.material.friction;
  77721. };
  77722. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77723. impostor.physicsBody.material.friction = friction;
  77724. };
  77725. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77726. return impostor.physicsBody.material.restitution;
  77727. };
  77728. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77729. impostor.physicsBody.material.restitution = restitution;
  77730. };
  77731. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77732. impostor.physicsBody.sleep();
  77733. };
  77734. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77735. impostor.physicsBody.wakeUp();
  77736. };
  77737. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77738. joint.physicsJoint.distance = maxDistance;
  77739. };
  77740. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77741. // if (!motorIndex) {
  77742. // joint.physicsJoint.enableMotor();
  77743. // }
  77744. // }
  77745. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77746. // if (!motorIndex) {
  77747. // joint.physicsJoint.disableMotor();
  77748. // }
  77749. // }
  77750. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77751. if (!motorIndex) {
  77752. joint.physicsJoint.enableMotor();
  77753. joint.physicsJoint.setMotorSpeed(speed);
  77754. if (maxForce) {
  77755. this.setLimit(joint, maxForce);
  77756. }
  77757. }
  77758. };
  77759. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77760. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77761. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77762. };
  77763. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77764. var body = impostor.physicsBody;
  77765. mesh.position.x = body.position.x;
  77766. mesh.position.y = body.position.y;
  77767. mesh.position.z = body.position.z;
  77768. if (mesh.rotationQuaternion) {
  77769. mesh.rotationQuaternion.x = body.quaternion.x;
  77770. mesh.rotationQuaternion.y = body.quaternion.y;
  77771. mesh.rotationQuaternion.z = body.quaternion.z;
  77772. mesh.rotationQuaternion.w = body.quaternion.w;
  77773. }
  77774. };
  77775. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77776. var shape = impostor.physicsBody.shapes[0];
  77777. return shape.boundingSphereRadius;
  77778. };
  77779. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77780. var shape = impostor.physicsBody.shapes[0];
  77781. result.x = shape.halfExtents.x * 2;
  77782. result.y = shape.halfExtents.y * 2;
  77783. result.z = shape.halfExtents.z * 2;
  77784. };
  77785. CannonJSPlugin.prototype.dispose = function () {
  77786. };
  77787. CannonJSPlugin.prototype._extendNamespace = function () {
  77788. //this will force cannon to execute at least one step when using interpolation
  77789. var step_tmp1 = new this.BJSCANNON.Vec3();
  77790. var Engine = this.BJSCANNON;
  77791. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77792. maxSubSteps = maxSubSteps || 10;
  77793. timeSinceLastCalled = timeSinceLastCalled || 0;
  77794. if (timeSinceLastCalled === 0) {
  77795. this.internalStep(dt);
  77796. this.time += dt;
  77797. }
  77798. else {
  77799. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77800. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77801. var t0 = performance.now();
  77802. for (var i = 0; i !== internalSteps; i++) {
  77803. this.internalStep(dt);
  77804. if (performance.now() - t0 > dt * 1000) {
  77805. break;
  77806. }
  77807. }
  77808. this.time += timeSinceLastCalled;
  77809. var h = this.time % dt;
  77810. var h_div_dt = h / dt;
  77811. var interpvelo = step_tmp1;
  77812. var bodies = this.bodies;
  77813. for (var j = 0; j !== bodies.length; j++) {
  77814. var b = bodies[j];
  77815. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77816. b.position.vsub(b.previousPosition, interpvelo);
  77817. interpvelo.scale(h_div_dt, interpvelo);
  77818. b.position.vadd(interpvelo, b.interpolatedPosition);
  77819. }
  77820. else {
  77821. b.interpolatedPosition.copy(b.position);
  77822. b.interpolatedQuaternion.copy(b.quaternion);
  77823. }
  77824. }
  77825. }
  77826. };
  77827. };
  77828. return CannonJSPlugin;
  77829. }());
  77830. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77831. })(BABYLON || (BABYLON = {}));
  77832. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77833. var BABYLON;
  77834. (function (BABYLON) {
  77835. var OimoJSPlugin = /** @class */ (function () {
  77836. function OimoJSPlugin(iterations) {
  77837. this.name = "OimoJSPlugin";
  77838. this._tmpImpostorsArray = [];
  77839. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77840. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77841. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77842. this.world.worldscale(1);
  77843. this.world.clear();
  77844. //making sure no stats are calculated
  77845. this.world.isNoStat = true;
  77846. }
  77847. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77848. this.world.gravity.copy(gravity);
  77849. };
  77850. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77851. this.world.timeStep = timeStep;
  77852. };
  77853. OimoJSPlugin.prototype.getTimeStep = function () {
  77854. return this.world.timeStep;
  77855. };
  77856. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77857. var _this = this;
  77858. impostors.forEach(function (impostor) {
  77859. impostor.beforeStep();
  77860. });
  77861. this.world.step();
  77862. impostors.forEach(function (impostor) {
  77863. impostor.afterStep();
  77864. //update the ordered impostors array
  77865. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77866. });
  77867. //check for collisions
  77868. var contact = this.world.contacts;
  77869. while (contact !== null) {
  77870. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77871. contact = contact.next;
  77872. continue;
  77873. }
  77874. //is this body colliding with any other? get the impostor
  77875. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77876. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77877. if (!mainImpostor || !collidingImpostor) {
  77878. contact = contact.next;
  77879. continue;
  77880. }
  77881. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77882. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77883. contact = contact.next;
  77884. }
  77885. };
  77886. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77887. var mass = impostor.physicsBody.massInfo.mass;
  77888. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77889. };
  77890. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77891. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77892. this.applyImpulse(impostor, force, contactPoint);
  77893. };
  77894. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77895. var _this = this;
  77896. //parent-child relationship. Does this impostor has a parent impostor?
  77897. if (impostor.parent) {
  77898. if (impostor.physicsBody) {
  77899. this.removePhysicsBody(impostor);
  77900. //TODO is that needed?
  77901. impostor.forceUpdate();
  77902. }
  77903. return;
  77904. }
  77905. if (impostor.isBodyInitRequired()) {
  77906. var bodyConfig = {
  77907. name: impostor.uniqueId,
  77908. //Oimo must have mass, also for static objects.
  77909. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77910. size: [],
  77911. type: [],
  77912. pos: [],
  77913. rot: [],
  77914. move: impostor.getParam("mass") !== 0,
  77915. //Supporting older versions of Oimo
  77916. world: this.world
  77917. };
  77918. var impostors = [impostor];
  77919. var addToArray = function (parent) {
  77920. if (!parent.getChildMeshes)
  77921. return;
  77922. parent.getChildMeshes().forEach(function (m) {
  77923. if (m.physicsImpostor) {
  77924. impostors.push(m.physicsImpostor);
  77925. //m.physicsImpostor._init();
  77926. }
  77927. });
  77928. };
  77929. addToArray(impostor.object);
  77930. var checkWithEpsilon_1 = function (value) {
  77931. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77932. };
  77933. impostors.forEach(function (i) {
  77934. if (!impostor.object.rotationQuaternion) {
  77935. return;
  77936. }
  77937. //get the correct bounding box
  77938. var oldQuaternion = i.object.rotationQuaternion;
  77939. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77940. x: impostor.object.rotationQuaternion.x,
  77941. y: impostor.object.rotationQuaternion.y,
  77942. z: impostor.object.rotationQuaternion.z,
  77943. s: impostor.object.rotationQuaternion.w
  77944. });
  77945. var extendSize = i.getObjectExtendSize();
  77946. if (i === impostor) {
  77947. var center = impostor.getObjectCenter();
  77948. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77949. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77950. //Can also use Array.prototype.push.apply
  77951. bodyConfig.pos.push(center.x);
  77952. bodyConfig.pos.push(center.y);
  77953. bodyConfig.pos.push(center.z);
  77954. //tmp solution
  77955. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77956. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77957. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77958. }
  77959. else {
  77960. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77961. bodyConfig.pos.push(localPosition.x);
  77962. bodyConfig.pos.push(localPosition.y);
  77963. bodyConfig.pos.push(localPosition.z);
  77964. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77965. bodyConfig.rot.push(0);
  77966. bodyConfig.rot.push(0);
  77967. bodyConfig.rot.push(0);
  77968. }
  77969. // register mesh
  77970. switch (i.type) {
  77971. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77972. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77973. case BABYLON.PhysicsImpostor.SphereImpostor:
  77974. var radiusX = extendSize.x;
  77975. var radiusY = extendSize.y;
  77976. var radiusZ = extendSize.z;
  77977. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77978. bodyConfig.type.push('sphere');
  77979. //due to the way oimo works with compounds, add 3 times
  77980. bodyConfig.size.push(size);
  77981. bodyConfig.size.push(size);
  77982. bodyConfig.size.push(size);
  77983. break;
  77984. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77985. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77986. var sizeY = checkWithEpsilon_1(extendSize.y);
  77987. bodyConfig.type.push('cylinder');
  77988. bodyConfig.size.push(sizeX);
  77989. bodyConfig.size.push(sizeY);
  77990. //due to the way oimo works with compounds, add one more value.
  77991. bodyConfig.size.push(sizeY);
  77992. break;
  77993. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77994. case BABYLON.PhysicsImpostor.BoxImpostor:
  77995. default:
  77996. var sizeX = checkWithEpsilon_1(extendSize.x);
  77997. var sizeY = checkWithEpsilon_1(extendSize.y);
  77998. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77999. bodyConfig.type.push('box');
  78000. bodyConfig.size.push(sizeX);
  78001. bodyConfig.size.push(sizeY);
  78002. bodyConfig.size.push(sizeZ);
  78003. break;
  78004. }
  78005. //actually not needed, but hey...
  78006. i.object.rotationQuaternion = oldQuaternion;
  78007. });
  78008. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78009. }
  78010. else {
  78011. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78012. }
  78013. impostor.setDeltaPosition(this._tmpPositionVector);
  78014. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78015. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78016. };
  78017. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78018. //impostor.physicsBody.dispose();
  78019. //Same as : (older oimo versions)
  78020. this.world.removeRigidBody(impostor.physicsBody);
  78021. };
  78022. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78023. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78024. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78025. if (!mainBody || !connectedBody) {
  78026. return;
  78027. }
  78028. var jointData = impostorJoint.joint.jointData;
  78029. var options = jointData.nativeParams || {};
  78030. var type;
  78031. var nativeJointData = {
  78032. body1: mainBody,
  78033. body2: connectedBody,
  78034. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78035. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78036. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78037. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78038. min: options.min,
  78039. max: options.max,
  78040. collision: options.collision || jointData.collision,
  78041. spring: options.spring,
  78042. //supporting older version of Oimo
  78043. world: this.world
  78044. };
  78045. switch (impostorJoint.joint.type) {
  78046. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78047. type = "jointBall";
  78048. break;
  78049. case BABYLON.PhysicsJoint.SpringJoint:
  78050. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78051. var springData = jointData;
  78052. nativeJointData.min = springData.length || nativeJointData.min;
  78053. //Max should also be set, just make sure it is at least min
  78054. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78055. case BABYLON.PhysicsJoint.DistanceJoint:
  78056. type = "jointDistance";
  78057. nativeJointData.max = jointData.maxDistance;
  78058. break;
  78059. case BABYLON.PhysicsJoint.PrismaticJoint:
  78060. type = "jointPrisme";
  78061. break;
  78062. case BABYLON.PhysicsJoint.SliderJoint:
  78063. type = "jointSlide";
  78064. break;
  78065. case BABYLON.PhysicsJoint.WheelJoint:
  78066. type = "jointWheel";
  78067. break;
  78068. case BABYLON.PhysicsJoint.HingeJoint:
  78069. default:
  78070. type = "jointHinge";
  78071. break;
  78072. }
  78073. nativeJointData.type = type;
  78074. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78075. };
  78076. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78077. //Bug in Oimo prevents us from disposing a joint in the playground
  78078. //joint.joint.physicsJoint.dispose();
  78079. //So we will bruteforce it!
  78080. try {
  78081. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78082. }
  78083. catch (e) {
  78084. BABYLON.Tools.Warn(e);
  78085. }
  78086. };
  78087. OimoJSPlugin.prototype.isSupported = function () {
  78088. return this.BJSOIMO !== undefined;
  78089. };
  78090. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78091. if (!impostor.physicsBody.sleeping) {
  78092. //TODO check that
  78093. if (impostor.physicsBody.shapes.next) {
  78094. var parentShape = this._getLastShape(impostor.physicsBody);
  78095. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78096. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78097. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78098. }
  78099. else {
  78100. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78101. }
  78102. if (impostor.object.rotationQuaternion) {
  78103. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78104. impostor.object.rotationQuaternion.normalize();
  78105. }
  78106. }
  78107. };
  78108. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78109. var body = impostor.physicsBody;
  78110. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78111. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78112. body.syncShapes();
  78113. body.awake();
  78114. };
  78115. OimoJSPlugin.prototype._getLastShape = function (body) {
  78116. var lastShape = body.shapes;
  78117. while (lastShape.next) {
  78118. lastShape = lastShape.next;
  78119. }
  78120. return lastShape;
  78121. };
  78122. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78123. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78124. };
  78125. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78126. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78127. };
  78128. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78129. var v = impostor.physicsBody.linearVelocity;
  78130. if (!v) {
  78131. return null;
  78132. }
  78133. return new BABYLON.Vector3(v.x, v.y, v.z);
  78134. };
  78135. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78136. var v = impostor.physicsBody.angularVelocity;
  78137. if (!v) {
  78138. return null;
  78139. }
  78140. return new BABYLON.Vector3(v.x, v.y, v.z);
  78141. };
  78142. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78143. var staticBody = mass === 0;
  78144. //this will actually set the body's density and not its mass.
  78145. //But this is how oimo treats the mass variable.
  78146. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78147. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78148. };
  78149. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78150. return impostor.physicsBody.shapes.density;
  78151. };
  78152. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78153. return impostor.physicsBody.shapes.friction;
  78154. };
  78155. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78156. impostor.physicsBody.shapes.friction = friction;
  78157. };
  78158. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78159. return impostor.physicsBody.shapes.restitution;
  78160. };
  78161. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78162. impostor.physicsBody.shapes.restitution = restitution;
  78163. };
  78164. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78165. impostor.physicsBody.sleep();
  78166. };
  78167. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78168. impostor.physicsBody.awake();
  78169. };
  78170. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78171. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78172. if (minDistance !== void 0) {
  78173. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78174. }
  78175. };
  78176. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78177. //TODO separate rotational and transational motors.
  78178. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78179. if (motor) {
  78180. motor.setMotor(speed, maxForce);
  78181. }
  78182. };
  78183. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78184. //TODO separate rotational and transational motors.
  78185. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78186. if (motor) {
  78187. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78188. }
  78189. };
  78190. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78191. var body = impostor.physicsBody;
  78192. mesh.position.x = body.position.x;
  78193. mesh.position.y = body.position.y;
  78194. mesh.position.z = body.position.z;
  78195. if (mesh.rotationQuaternion) {
  78196. mesh.rotationQuaternion.x = body.orientation.x;
  78197. mesh.rotationQuaternion.y = body.orientation.y;
  78198. mesh.rotationQuaternion.z = body.orientation.z;
  78199. mesh.rotationQuaternion.w = body.orientation.s;
  78200. }
  78201. };
  78202. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78203. return impostor.physicsBody.shapes.radius;
  78204. };
  78205. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78206. var shape = impostor.physicsBody.shapes;
  78207. result.x = shape.halfWidth * 2;
  78208. result.y = shape.halfHeight * 2;
  78209. result.z = shape.halfDepth * 2;
  78210. };
  78211. OimoJSPlugin.prototype.dispose = function () {
  78212. this.world.clear();
  78213. };
  78214. return OimoJSPlugin;
  78215. }());
  78216. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78217. })(BABYLON || (BABYLON = {}));
  78218. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78219. var BABYLON;
  78220. (function (BABYLON) {
  78221. /*
  78222. * Based on jsTGALoader - Javascript loader for TGA file
  78223. * By Vincent Thibault
  78224. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78225. */
  78226. var TGATools = /** @class */ (function () {
  78227. function TGATools() {
  78228. }
  78229. TGATools.GetTGAHeader = function (data) {
  78230. var offset = 0;
  78231. var header = {
  78232. id_length: data[offset++],
  78233. colormap_type: data[offset++],
  78234. image_type: data[offset++],
  78235. colormap_index: data[offset++] | data[offset++] << 8,
  78236. colormap_length: data[offset++] | data[offset++] << 8,
  78237. colormap_size: data[offset++],
  78238. origin: [
  78239. data[offset++] | data[offset++] << 8,
  78240. data[offset++] | data[offset++] << 8
  78241. ],
  78242. width: data[offset++] | data[offset++] << 8,
  78243. height: data[offset++] | data[offset++] << 8,
  78244. pixel_size: data[offset++],
  78245. flags: data[offset++]
  78246. };
  78247. return header;
  78248. };
  78249. TGATools.UploadContent = function (gl, data) {
  78250. // Not enough data to contain header ?
  78251. if (data.length < 19) {
  78252. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78253. return;
  78254. }
  78255. // Read Header
  78256. var offset = 18;
  78257. var header = TGATools.GetTGAHeader(data);
  78258. // Assume it's a valid Targa file.
  78259. if (header.id_length + offset > data.length) {
  78260. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78261. return;
  78262. }
  78263. // Skip not needed data
  78264. offset += header.id_length;
  78265. var use_rle = false;
  78266. var use_pal = false;
  78267. var use_grey = false;
  78268. // Get some informations.
  78269. switch (header.image_type) {
  78270. case TGATools._TYPE_RLE_INDEXED:
  78271. use_rle = true;
  78272. case TGATools._TYPE_INDEXED:
  78273. use_pal = true;
  78274. break;
  78275. case TGATools._TYPE_RLE_RGB:
  78276. use_rle = true;
  78277. case TGATools._TYPE_RGB:
  78278. // use_rgb = true;
  78279. break;
  78280. case TGATools._TYPE_RLE_GREY:
  78281. use_rle = true;
  78282. case TGATools._TYPE_GREY:
  78283. use_grey = true;
  78284. break;
  78285. }
  78286. var pixel_data;
  78287. // var numAlphaBits = header.flags & 0xf;
  78288. var pixel_size = header.pixel_size >> 3;
  78289. var pixel_total = header.width * header.height * pixel_size;
  78290. // Read palettes
  78291. var palettes;
  78292. if (use_pal) {
  78293. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78294. }
  78295. // Read LRE
  78296. if (use_rle) {
  78297. pixel_data = new Uint8Array(pixel_total);
  78298. var c, count, i;
  78299. var localOffset = 0;
  78300. var pixels = new Uint8Array(pixel_size);
  78301. while (offset < pixel_total && localOffset < pixel_total) {
  78302. c = data[offset++];
  78303. count = (c & 0x7f) + 1;
  78304. // RLE pixels
  78305. if (c & 0x80) {
  78306. // Bind pixel tmp array
  78307. for (i = 0; i < pixel_size; ++i) {
  78308. pixels[i] = data[offset++];
  78309. }
  78310. // Copy pixel array
  78311. for (i = 0; i < count; ++i) {
  78312. pixel_data.set(pixels, localOffset + i * pixel_size);
  78313. }
  78314. localOffset += pixel_size * count;
  78315. }
  78316. else {
  78317. count *= pixel_size;
  78318. for (i = 0; i < count; ++i) {
  78319. pixel_data[localOffset + i] = data[offset++];
  78320. }
  78321. localOffset += count;
  78322. }
  78323. }
  78324. }
  78325. else {
  78326. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78327. }
  78328. // Load to texture
  78329. var x_start, y_start, x_step, y_step, y_end, x_end;
  78330. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78331. default:
  78332. case TGATools._ORIGIN_UL:
  78333. x_start = 0;
  78334. x_step = 1;
  78335. x_end = header.width;
  78336. y_start = 0;
  78337. y_step = 1;
  78338. y_end = header.height;
  78339. break;
  78340. case TGATools._ORIGIN_BL:
  78341. x_start = 0;
  78342. x_step = 1;
  78343. x_end = header.width;
  78344. y_start = header.height - 1;
  78345. y_step = -1;
  78346. y_end = -1;
  78347. break;
  78348. case TGATools._ORIGIN_UR:
  78349. x_start = header.width - 1;
  78350. x_step = -1;
  78351. x_end = -1;
  78352. y_start = 0;
  78353. y_step = 1;
  78354. y_end = header.height;
  78355. break;
  78356. case TGATools._ORIGIN_BR:
  78357. x_start = header.width - 1;
  78358. x_step = -1;
  78359. x_end = -1;
  78360. y_start = header.height - 1;
  78361. y_step = -1;
  78362. y_end = -1;
  78363. break;
  78364. }
  78365. // Load the specify method
  78366. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78367. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78368. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78369. };
  78370. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78371. var image = pixel_data, colormap = palettes;
  78372. var width = header.width, height = header.height;
  78373. var color, i = 0, x, y;
  78374. var imageData = new Uint8Array(width * height * 4);
  78375. for (y = y_start; y !== y_end; y += y_step) {
  78376. for (x = x_start; x !== x_end; x += x_step, i++) {
  78377. color = image[i];
  78378. imageData[(x + width * y) * 4 + 3] = 255;
  78379. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78380. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78381. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78382. }
  78383. }
  78384. return imageData;
  78385. };
  78386. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78387. var image = pixel_data;
  78388. var width = header.width, height = header.height;
  78389. var color, i = 0, x, y;
  78390. var imageData = new Uint8Array(width * height * 4);
  78391. for (y = y_start; y !== y_end; y += y_step) {
  78392. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78393. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78394. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78395. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78396. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78397. imageData[(x + width * y) * 4 + 0] = r;
  78398. imageData[(x + width * y) * 4 + 1] = g;
  78399. imageData[(x + width * y) * 4 + 2] = b;
  78400. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78401. }
  78402. }
  78403. return imageData;
  78404. };
  78405. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78406. var image = pixel_data;
  78407. var width = header.width, height = header.height;
  78408. var i = 0, x, y;
  78409. var imageData = new Uint8Array(width * height * 4);
  78410. for (y = y_start; y !== y_end; y += y_step) {
  78411. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78412. imageData[(x + width * y) * 4 + 3] = 255;
  78413. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78414. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78415. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78416. }
  78417. }
  78418. return imageData;
  78419. };
  78420. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78421. var image = pixel_data;
  78422. var width = header.width, height = header.height;
  78423. var i = 0, x, y;
  78424. var imageData = new Uint8Array(width * height * 4);
  78425. for (y = y_start; y !== y_end; y += y_step) {
  78426. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78427. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78428. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78429. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78430. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78431. }
  78432. }
  78433. return imageData;
  78434. };
  78435. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78436. var image = pixel_data;
  78437. var width = header.width, height = header.height;
  78438. var color, i = 0, x, y;
  78439. var imageData = new Uint8Array(width * height * 4);
  78440. for (y = y_start; y !== y_end; y += y_step) {
  78441. for (x = x_start; x !== x_end; x += x_step, i++) {
  78442. color = image[i];
  78443. imageData[(x + width * y) * 4 + 0] = color;
  78444. imageData[(x + width * y) * 4 + 1] = color;
  78445. imageData[(x + width * y) * 4 + 2] = color;
  78446. imageData[(x + width * y) * 4 + 3] = 255;
  78447. }
  78448. }
  78449. return imageData;
  78450. };
  78451. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78452. var image = pixel_data;
  78453. var width = header.width, height = header.height;
  78454. var i = 0, x, y;
  78455. var imageData = new Uint8Array(width * height * 4);
  78456. for (y = y_start; y !== y_end; y += y_step) {
  78457. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78458. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78459. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78460. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78461. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78462. }
  78463. }
  78464. return imageData;
  78465. };
  78466. //private static _TYPE_NO_DATA = 0;
  78467. TGATools._TYPE_INDEXED = 1;
  78468. TGATools._TYPE_RGB = 2;
  78469. TGATools._TYPE_GREY = 3;
  78470. TGATools._TYPE_RLE_INDEXED = 9;
  78471. TGATools._TYPE_RLE_RGB = 10;
  78472. TGATools._TYPE_RLE_GREY = 11;
  78473. TGATools._ORIGIN_MASK = 0x30;
  78474. TGATools._ORIGIN_SHIFT = 0x04;
  78475. TGATools._ORIGIN_BL = 0x00;
  78476. TGATools._ORIGIN_BR = 0x01;
  78477. TGATools._ORIGIN_UL = 0x02;
  78478. TGATools._ORIGIN_UR = 0x03;
  78479. return TGATools;
  78480. }());
  78481. BABYLON.TGATools = TGATools;
  78482. })(BABYLON || (BABYLON = {}));
  78483. //# sourceMappingURL=babylon.tga.js.map
  78484. var BABYLON;
  78485. (function (BABYLON) {
  78486. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78487. // All values and structures referenced from:
  78488. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78489. var DDS_MAGIC = 0x20534444;
  78490. var
  78491. //DDSD_CAPS = 0x1,
  78492. //DDSD_HEIGHT = 0x2,
  78493. //DDSD_WIDTH = 0x4,
  78494. //DDSD_PITCH = 0x8,
  78495. //DDSD_PIXELFORMAT = 0x1000,
  78496. DDSD_MIPMAPCOUNT = 0x20000;
  78497. //DDSD_LINEARSIZE = 0x80000,
  78498. //DDSD_DEPTH = 0x800000;
  78499. // var DDSCAPS_COMPLEX = 0x8,
  78500. // DDSCAPS_MIPMAP = 0x400000,
  78501. // DDSCAPS_TEXTURE = 0x1000;
  78502. var DDSCAPS2_CUBEMAP = 0x200;
  78503. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78504. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78505. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78506. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78507. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78508. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78509. // DDSCAPS2_VOLUME = 0x200000;
  78510. var
  78511. //DDPF_ALPHAPIXELS = 0x1,
  78512. //DDPF_ALPHA = 0x2,
  78513. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78514. //DDPF_YUV = 0x200,
  78515. DDPF_LUMINANCE = 0x20000;
  78516. function FourCCToInt32(value) {
  78517. return value.charCodeAt(0) +
  78518. (value.charCodeAt(1) << 8) +
  78519. (value.charCodeAt(2) << 16) +
  78520. (value.charCodeAt(3) << 24);
  78521. }
  78522. function Int32ToFourCC(value) {
  78523. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78524. }
  78525. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78526. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78527. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78528. var FOURCC_DX10 = FourCCToInt32("DX10");
  78529. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78530. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78531. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78532. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78533. var headerLengthInt = 31; // The header length in 32 bit ints
  78534. // Offsets into the header array
  78535. var off_magic = 0;
  78536. var off_size = 1;
  78537. var off_flags = 2;
  78538. var off_height = 3;
  78539. var off_width = 4;
  78540. var off_mipmapCount = 7;
  78541. var off_pfFlags = 20;
  78542. var off_pfFourCC = 21;
  78543. var off_RGBbpp = 22;
  78544. var off_RMask = 23;
  78545. var off_GMask = 24;
  78546. var off_BMask = 25;
  78547. var off_AMask = 26;
  78548. // var off_caps1 = 27;
  78549. var off_caps2 = 28;
  78550. // var off_caps3 = 29;
  78551. // var off_caps4 = 30;
  78552. var off_dxgiFormat = 32;
  78553. ;
  78554. var DDSTools = /** @class */ (function () {
  78555. function DDSTools() {
  78556. }
  78557. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78558. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78559. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78560. var mipmapCount = 1;
  78561. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78562. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78563. }
  78564. var fourCC = header[off_pfFourCC];
  78565. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78566. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78567. switch (fourCC) {
  78568. case FOURCC_D3DFMT_R16G16B16A16F:
  78569. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78570. break;
  78571. case FOURCC_D3DFMT_R32G32B32A32F:
  78572. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78573. break;
  78574. case FOURCC_DX10:
  78575. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78576. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78577. break;
  78578. }
  78579. }
  78580. return {
  78581. width: header[off_width],
  78582. height: header[off_height],
  78583. mipmapCount: mipmapCount,
  78584. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78585. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78586. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78587. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78588. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78589. dxgiFormat: dxgiFormat,
  78590. textureType: textureType
  78591. };
  78592. };
  78593. DDSTools._ToHalfFloat = function (value) {
  78594. if (!DDSTools._FloatView) {
  78595. DDSTools._FloatView = new Float32Array(1);
  78596. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78597. }
  78598. DDSTools._FloatView[0] = value;
  78599. var x = DDSTools._Int32View[0];
  78600. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78601. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78602. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78603. /* If zero, or denormal, or exponent underflows too much for a denormal
  78604. * half, return signed zero. */
  78605. if (e < 103) {
  78606. return bits;
  78607. }
  78608. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78609. if (e > 142) {
  78610. bits |= 0x7c00;
  78611. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78612. * not Inf, so make sure we set one mantissa bit too. */
  78613. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78614. return bits;
  78615. }
  78616. /* If exponent underflows but not too much, return a denormal */
  78617. if (e < 113) {
  78618. m |= 0x0800;
  78619. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78620. * to 1, which is OK. */
  78621. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78622. return bits;
  78623. }
  78624. bits |= ((e - 112) << 10) | (m >> 1);
  78625. bits += m & 1;
  78626. return bits;
  78627. };
  78628. DDSTools._FromHalfFloat = function (value) {
  78629. var s = (value & 0x8000) >> 15;
  78630. var e = (value & 0x7C00) >> 10;
  78631. var f = value & 0x03FF;
  78632. if (e === 0) {
  78633. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78634. }
  78635. else if (e == 0x1F) {
  78636. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78637. }
  78638. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78639. };
  78640. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78641. var destArray = new Float32Array(dataLength);
  78642. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78643. var index = 0;
  78644. for (var y = 0; y < height; y++) {
  78645. for (var x = 0; x < width; x++) {
  78646. var srcPos = (x + y * width) * 4;
  78647. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78648. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78649. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78650. if (DDSTools.StoreLODInAlphaChannel) {
  78651. destArray[index + 3] = lod;
  78652. }
  78653. else {
  78654. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78655. }
  78656. index += 4;
  78657. }
  78658. }
  78659. return destArray;
  78660. };
  78661. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78662. if (DDSTools.StoreLODInAlphaChannel) {
  78663. var destArray = new Uint16Array(dataLength);
  78664. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78665. var index = 0;
  78666. for (var y = 0; y < height; y++) {
  78667. for (var x = 0; x < width; x++) {
  78668. var srcPos = (x + y * width) * 4;
  78669. destArray[index] = srcData[srcPos];
  78670. destArray[index + 1] = srcData[srcPos + 1];
  78671. destArray[index + 2] = srcData[srcPos + 2];
  78672. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78673. index += 4;
  78674. }
  78675. }
  78676. return destArray;
  78677. }
  78678. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78679. };
  78680. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78681. if (DDSTools.StoreLODInAlphaChannel) {
  78682. var destArray = new Float32Array(dataLength);
  78683. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78684. var index = 0;
  78685. for (var y = 0; y < height; y++) {
  78686. for (var x = 0; x < width; x++) {
  78687. var srcPos = (x + y * width) * 4;
  78688. destArray[index] = srcData[srcPos];
  78689. destArray[index + 1] = srcData[srcPos + 1];
  78690. destArray[index + 2] = srcData[srcPos + 2];
  78691. destArray[index + 3] = lod;
  78692. index += 4;
  78693. }
  78694. }
  78695. return destArray;
  78696. }
  78697. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78698. };
  78699. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78700. var destArray = new Uint8Array(dataLength);
  78701. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78702. var index = 0;
  78703. for (var y = 0; y < height; y++) {
  78704. for (var x = 0; x < width; x++) {
  78705. var srcPos = (x + y * width) * 4;
  78706. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78707. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78708. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78709. if (DDSTools.StoreLODInAlphaChannel) {
  78710. destArray[index + 3] = lod;
  78711. }
  78712. else {
  78713. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78714. }
  78715. index += 4;
  78716. }
  78717. }
  78718. return destArray;
  78719. };
  78720. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78721. var destArray = new Uint8Array(dataLength);
  78722. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78723. var index = 0;
  78724. for (var y = 0; y < height; y++) {
  78725. for (var x = 0; x < width; x++) {
  78726. var srcPos = (x + y * width) * 4;
  78727. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78728. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78729. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78730. if (DDSTools.StoreLODInAlphaChannel) {
  78731. destArray[index + 3] = lod;
  78732. }
  78733. else {
  78734. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78735. }
  78736. index += 4;
  78737. }
  78738. }
  78739. return destArray;
  78740. };
  78741. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78742. var byteArray = new Uint8Array(dataLength);
  78743. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78744. var index = 0;
  78745. for (var y = 0; y < height; y++) {
  78746. for (var x = 0; x < width; x++) {
  78747. var srcPos = (x + y * width) * 4;
  78748. byteArray[index] = srcData[srcPos + rOffset];
  78749. byteArray[index + 1] = srcData[srcPos + gOffset];
  78750. byteArray[index + 2] = srcData[srcPos + bOffset];
  78751. byteArray[index + 3] = srcData[srcPos + aOffset];
  78752. index += 4;
  78753. }
  78754. }
  78755. return byteArray;
  78756. };
  78757. DDSTools._ExtractLongWordOrder = function (value) {
  78758. if (value === 0 || value === 255 || value === -16777216) {
  78759. return 0;
  78760. }
  78761. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78762. };
  78763. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78764. var byteArray = new Uint8Array(dataLength);
  78765. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78766. var index = 0;
  78767. for (var y = 0; y < height; y++) {
  78768. for (var x = 0; x < width; x++) {
  78769. var srcPos = (x + y * width) * 3;
  78770. byteArray[index] = srcData[srcPos + rOffset];
  78771. byteArray[index + 1] = srcData[srcPos + gOffset];
  78772. byteArray[index + 2] = srcData[srcPos + bOffset];
  78773. index += 3;
  78774. }
  78775. }
  78776. return byteArray;
  78777. };
  78778. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78779. var byteArray = new Uint8Array(dataLength);
  78780. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78781. var index = 0;
  78782. for (var y = 0; y < height; y++) {
  78783. for (var x = 0; x < width; x++) {
  78784. var srcPos = (x + y * width);
  78785. byteArray[index] = srcData[srcPos];
  78786. index++;
  78787. }
  78788. }
  78789. return byteArray;
  78790. };
  78791. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78792. if (lodIndex === void 0) { lodIndex = -1; }
  78793. var ext = engine.getCaps().s3tc;
  78794. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78795. var fourCC, width, height, dataLength = 0, dataOffset;
  78796. var byteArray, mipmapCount, mip;
  78797. var internalFormat = 0;
  78798. var format = 0;
  78799. var blockBytes = 1;
  78800. if (header[off_magic] !== DDS_MAGIC) {
  78801. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78802. return;
  78803. }
  78804. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78805. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78806. return;
  78807. }
  78808. if (info.isCompressed && !ext) {
  78809. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78810. return;
  78811. }
  78812. var bpp = header[off_RGBbpp];
  78813. dataOffset = header[off_size] + 4;
  78814. var computeFormats = false;
  78815. if (info.isFourCC) {
  78816. fourCC = header[off_pfFourCC];
  78817. switch (fourCC) {
  78818. case FOURCC_DXT1:
  78819. blockBytes = 8;
  78820. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78821. break;
  78822. case FOURCC_DXT3:
  78823. blockBytes = 16;
  78824. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78825. break;
  78826. case FOURCC_DXT5:
  78827. blockBytes = 16;
  78828. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78829. break;
  78830. case FOURCC_D3DFMT_R16G16B16A16F:
  78831. computeFormats = true;
  78832. break;
  78833. case FOURCC_D3DFMT_R32G32B32A32F:
  78834. computeFormats = true;
  78835. break;
  78836. case FOURCC_DX10:
  78837. // There is an additionnal header so dataOffset need to be changed
  78838. dataOffset += 5 * 4; // 5 uints
  78839. var supported = false;
  78840. switch (info.dxgiFormat) {
  78841. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78842. computeFormats = true;
  78843. supported = true;
  78844. break;
  78845. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78846. info.isRGB = true;
  78847. info.isFourCC = false;
  78848. bpp = 32;
  78849. supported = true;
  78850. break;
  78851. }
  78852. if (supported) {
  78853. break;
  78854. }
  78855. default:
  78856. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78857. return;
  78858. }
  78859. }
  78860. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78861. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78862. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78863. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78864. if (computeFormats) {
  78865. format = engine._getWebGLTextureType(info.textureType);
  78866. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78867. }
  78868. mipmapCount = 1;
  78869. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78870. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78871. }
  78872. for (var face = 0; face < faces; face++) {
  78873. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78874. width = header[off_width];
  78875. height = header[off_height];
  78876. for (mip = 0; mip < mipmapCount; ++mip) {
  78877. if (lodIndex === -1 || lodIndex === mip) {
  78878. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78879. var i = (lodIndex === -1) ? mip : 0;
  78880. if (!info.isCompressed && info.isFourCC) {
  78881. dataLength = width * height * 4;
  78882. var floatArray = null;
  78883. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78884. if (bpp === 128) {
  78885. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78886. }
  78887. else if (bpp === 64) {
  78888. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78889. }
  78890. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78891. format = engine._getWebGLTextureType(info.textureType);
  78892. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78893. }
  78894. else {
  78895. if (bpp === 128) {
  78896. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78897. }
  78898. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78899. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78900. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78901. format = engine._getWebGLTextureType(info.textureType);
  78902. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78903. }
  78904. else {
  78905. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78906. }
  78907. }
  78908. if (floatArray) {
  78909. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78910. }
  78911. }
  78912. else if (info.isRGB) {
  78913. if (bpp === 24) {
  78914. dataLength = width * height * 3;
  78915. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78916. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78917. }
  78918. else {
  78919. dataLength = width * height * 4;
  78920. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78921. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78922. }
  78923. }
  78924. else if (info.isLuminance) {
  78925. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78926. var unpaddedRowSize = width;
  78927. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78928. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78929. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78930. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78931. }
  78932. else {
  78933. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78934. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78935. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78936. }
  78937. }
  78938. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78939. width *= 0.5;
  78940. height *= 0.5;
  78941. width = Math.max(1.0, width);
  78942. height = Math.max(1.0, height);
  78943. }
  78944. if (currentFace !== undefined) {
  78945. // Loading a single face
  78946. break;
  78947. }
  78948. }
  78949. };
  78950. DDSTools.StoreLODInAlphaChannel = false;
  78951. return DDSTools;
  78952. }());
  78953. BABYLON.DDSTools = DDSTools;
  78954. })(BABYLON || (BABYLON = {}));
  78955. //# sourceMappingURL=babylon.dds.js.map
  78956. var BABYLON;
  78957. (function (BABYLON) {
  78958. /**
  78959. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78960. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78961. */
  78962. var KhronosTextureContainer = /** @class */ (function () {
  78963. /**
  78964. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78965. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78966. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78967. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78968. */
  78969. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78970. this.arrayBuffer = arrayBuffer;
  78971. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78972. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78973. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78974. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78975. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78976. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78977. BABYLON.Tools.Error("texture missing KTX identifier");
  78978. return;
  78979. }
  78980. // load the reset of the header in native 32 bit int
  78981. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78982. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78983. var oppositeEndianess = header[0] === 0x01020304;
  78984. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78985. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78986. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78987. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78988. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78989. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78990. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78991. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78992. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78993. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78994. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78995. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78996. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78997. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78998. if (this.glType !== 0) {
  78999. BABYLON.Tools.Error("only compressed formats currently supported");
  79000. return;
  79001. }
  79002. else {
  79003. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79004. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79005. }
  79006. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79007. BABYLON.Tools.Error("only 2D textures currently supported");
  79008. return;
  79009. }
  79010. if (this.numberOfArrayElements !== 0) {
  79011. BABYLON.Tools.Error("texture arrays not currently supported");
  79012. return;
  79013. }
  79014. if (this.numberOfFaces !== facesExpected) {
  79015. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79016. return;
  79017. }
  79018. // we now have a completely validated file, so could use existence of loadType as success
  79019. // would need to make this more elaborate & adjust checks above to support more than one load type
  79020. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79021. }
  79022. // not as fast hardware based, but will probably never need to use
  79023. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79024. return ((val & 0xFF) << 24)
  79025. | ((val & 0xFF00) << 8)
  79026. | ((val >> 8) & 0xFF00)
  79027. | ((val >> 24) & 0xFF);
  79028. };
  79029. /**
  79030. * It is assumed that the texture has already been created & is currently bound
  79031. */
  79032. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79033. switch (this.loadType) {
  79034. case KhronosTextureContainer.COMPRESSED_2D:
  79035. this._upload2DCompressedLevels(gl, loadMipmaps);
  79036. break;
  79037. case KhronosTextureContainer.TEX_2D:
  79038. case KhronosTextureContainer.COMPRESSED_3D:
  79039. case KhronosTextureContainer.TEX_3D:
  79040. }
  79041. };
  79042. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79043. // initialize width & height for level 1
  79044. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79045. var width = this.pixelWidth;
  79046. var height = this.pixelHeight;
  79047. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79048. for (var level = 0; level < mipmapCount; level++) {
  79049. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79050. for (var face = 0; face < this.numberOfFaces; face++) {
  79051. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79052. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79053. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79054. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79055. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79056. }
  79057. width = Math.max(1.0, width * 0.5);
  79058. height = Math.max(1.0, height * 0.5);
  79059. }
  79060. };
  79061. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79062. // load types
  79063. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79064. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79065. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79066. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79067. return KhronosTextureContainer;
  79068. }());
  79069. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79070. })(BABYLON || (BABYLON = {}));
  79071. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79072. var BABYLON;
  79073. (function (BABYLON) {
  79074. var Debug = /** @class */ (function () {
  79075. function Debug() {
  79076. }
  79077. Debug.AxesViewer = /** @class */ (function () {
  79078. function AxesViewer(scene, scaleLines) {
  79079. if (scaleLines === void 0) { scaleLines = 1; }
  79080. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79081. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79082. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79083. this.scaleLines = 1;
  79084. this.scaleLines = scaleLines;
  79085. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79086. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79087. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79088. this._xmesh.renderingGroupId = 2;
  79089. this._ymesh.renderingGroupId = 2;
  79090. this._zmesh.renderingGroupId = 2;
  79091. this._xmesh.material.checkReadyOnlyOnce = true;
  79092. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79093. this._ymesh.material.checkReadyOnlyOnce = true;
  79094. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79095. this._zmesh.material.checkReadyOnlyOnce = true;
  79096. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79097. this.scene = scene;
  79098. }
  79099. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79100. var scaleLines = this.scaleLines;
  79101. if (this._xmesh) {
  79102. this._xmesh.position.copyFrom(position);
  79103. }
  79104. if (this._ymesh) {
  79105. this._ymesh.position.copyFrom(position);
  79106. }
  79107. if (this._zmesh) {
  79108. this._zmesh.position.copyFrom(position);
  79109. }
  79110. var point2 = this._xline[1];
  79111. point2.x = xaxis.x * scaleLines;
  79112. point2.y = xaxis.y * scaleLines;
  79113. point2.z = xaxis.z * scaleLines;
  79114. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79115. point2 = this._yline[1];
  79116. point2.x = yaxis.x * scaleLines;
  79117. point2.y = yaxis.y * scaleLines;
  79118. point2.z = yaxis.z * scaleLines;
  79119. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79120. point2 = this._zline[1];
  79121. point2.x = zaxis.x * scaleLines;
  79122. point2.y = zaxis.y * scaleLines;
  79123. point2.z = zaxis.z * scaleLines;
  79124. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79125. };
  79126. AxesViewer.prototype.dispose = function () {
  79127. if (this._xmesh) {
  79128. this._xmesh.dispose();
  79129. }
  79130. if (this._ymesh) {
  79131. this._ymesh.dispose();
  79132. }
  79133. if (this._zmesh) {
  79134. this._zmesh.dispose();
  79135. }
  79136. this._xmesh = null;
  79137. this._ymesh = null;
  79138. this._zmesh = null;
  79139. this.scene = null;
  79140. };
  79141. return AxesViewer;
  79142. }());
  79143. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79144. __extends(BoneAxesViewer, _super);
  79145. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79146. if (scaleLines === void 0) { scaleLines = 1; }
  79147. var _this = _super.call(this, scene, scaleLines) || this;
  79148. _this.pos = BABYLON.Vector3.Zero();
  79149. _this.xaxis = BABYLON.Vector3.Zero();
  79150. _this.yaxis = BABYLON.Vector3.Zero();
  79151. _this.zaxis = BABYLON.Vector3.Zero();
  79152. _this.mesh = mesh;
  79153. _this.bone = bone;
  79154. return _this;
  79155. }
  79156. BoneAxesViewer.prototype.update = function () {
  79157. if (!this.mesh || !this.bone) {
  79158. return;
  79159. }
  79160. var bone = this.bone;
  79161. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79162. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79163. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79164. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79165. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79166. };
  79167. BoneAxesViewer.prototype.dispose = function () {
  79168. if (this.mesh) {
  79169. this.mesh = null;
  79170. this.bone = null;
  79171. _super.prototype.dispose.call(this);
  79172. }
  79173. };
  79174. return BoneAxesViewer;
  79175. }(Debug.AxesViewer));
  79176. Debug.PhysicsViewer = /** @class */ (function () {
  79177. function PhysicsViewer(scene) {
  79178. this._impostors = [];
  79179. this._meshes = [];
  79180. this._numMeshes = 0;
  79181. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79182. var physicEngine = this._scene.getPhysicsEngine();
  79183. if (physicEngine) {
  79184. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79185. }
  79186. }
  79187. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79188. var plugin = this._physicsEnginePlugin;
  79189. for (var i = 0; i < this._numMeshes; i++) {
  79190. var impostor = this._impostors[i];
  79191. if (!impostor) {
  79192. continue;
  79193. }
  79194. if (impostor.isDisposed) {
  79195. this.hideImpostor(this._impostors[i--]);
  79196. }
  79197. else {
  79198. var mesh = this._meshes[i];
  79199. if (mesh && plugin) {
  79200. plugin.syncMeshWithImpostor(mesh, impostor);
  79201. }
  79202. }
  79203. }
  79204. };
  79205. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79206. if (!this._scene) {
  79207. return;
  79208. }
  79209. for (var i = 0; i < this._numMeshes; i++) {
  79210. if (this._impostors[i] == impostor) {
  79211. return;
  79212. }
  79213. }
  79214. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79215. if (debugMesh) {
  79216. this._impostors[this._numMeshes] = impostor;
  79217. this._meshes[this._numMeshes] = debugMesh;
  79218. if (this._numMeshes === 0) {
  79219. this._renderFunction = this._updateDebugMeshes.bind(this);
  79220. this._scene.registerBeforeRender(this._renderFunction);
  79221. }
  79222. this._numMeshes++;
  79223. }
  79224. };
  79225. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79226. if (!impostor || !this._scene) {
  79227. return;
  79228. }
  79229. var removed = false;
  79230. for (var i = 0; i < this._numMeshes; i++) {
  79231. if (this._impostors[i] == impostor) {
  79232. var mesh = this._meshes[i];
  79233. if (!mesh) {
  79234. continue;
  79235. }
  79236. this._scene.removeMesh(mesh);
  79237. mesh.dispose();
  79238. this._numMeshes--;
  79239. if (this._numMeshes > 0) {
  79240. this._meshes[i] = this._meshes[this._numMeshes];
  79241. this._impostors[i] = this._impostors[this._numMeshes];
  79242. this._meshes[this._numMeshes] = null;
  79243. this._impostors[this._numMeshes] = null;
  79244. }
  79245. else {
  79246. this._meshes[0] = null;
  79247. this._impostors[0] = null;
  79248. }
  79249. removed = true;
  79250. break;
  79251. }
  79252. }
  79253. if (removed && this._numMeshes === 0) {
  79254. this._scene.unregisterBeforeRender(this._renderFunction);
  79255. }
  79256. };
  79257. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79258. if (!this._debugMaterial) {
  79259. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79260. this._debugMaterial.wireframe = true;
  79261. }
  79262. return this._debugMaterial;
  79263. };
  79264. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79265. if (!this._debugBoxMesh) {
  79266. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79267. this._debugBoxMesh.renderingGroupId = 1;
  79268. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79269. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79270. scene.removeMesh(this._debugBoxMesh);
  79271. }
  79272. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79273. };
  79274. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79275. if (!this._debugSphereMesh) {
  79276. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79277. this._debugSphereMesh.renderingGroupId = 1;
  79278. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79279. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79280. scene.removeMesh(this._debugSphereMesh);
  79281. }
  79282. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79283. };
  79284. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79285. var mesh = null;
  79286. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79287. mesh = this._getDebugBoxMesh(scene);
  79288. impostor.getBoxSizeToRef(mesh.scaling);
  79289. }
  79290. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79291. mesh = this._getDebugSphereMesh(scene);
  79292. var radius = impostor.getRadius();
  79293. mesh.scaling.x = radius * 2;
  79294. mesh.scaling.y = radius * 2;
  79295. mesh.scaling.z = radius * 2;
  79296. }
  79297. return mesh;
  79298. };
  79299. PhysicsViewer.prototype.dispose = function () {
  79300. for (var i = 0; i < this._numMeshes; i++) {
  79301. this.hideImpostor(this._impostors[i]);
  79302. }
  79303. if (this._debugBoxMesh) {
  79304. this._debugBoxMesh.dispose();
  79305. }
  79306. if (this._debugSphereMesh) {
  79307. this._debugSphereMesh.dispose();
  79308. }
  79309. if (this._debugMaterial) {
  79310. this._debugMaterial.dispose();
  79311. }
  79312. this._impostors.length = 0;
  79313. this._scene = null;
  79314. this._physicsEnginePlugin = null;
  79315. };
  79316. return PhysicsViewer;
  79317. }());
  79318. Debug.SkeletonViewer = /** @class */ (function () {
  79319. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79320. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79321. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79322. this.skeleton = skeleton;
  79323. this.mesh = mesh;
  79324. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79325. this.renderingGroupId = renderingGroupId;
  79326. this.color = BABYLON.Color3.White();
  79327. this._debugLines = new Array();
  79328. this._isEnabled = false;
  79329. this._scene = scene;
  79330. this.update();
  79331. this._renderFunction = this.update.bind(this);
  79332. }
  79333. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79334. get: function () {
  79335. return this._isEnabled;
  79336. },
  79337. set: function (value) {
  79338. if (this._isEnabled === value) {
  79339. return;
  79340. }
  79341. this._isEnabled = value;
  79342. if (value) {
  79343. this._scene.registerBeforeRender(this._renderFunction);
  79344. }
  79345. else {
  79346. this._scene.unregisterBeforeRender(this._renderFunction);
  79347. }
  79348. },
  79349. enumerable: true,
  79350. configurable: true
  79351. });
  79352. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79353. if (x === void 0) { x = 0; }
  79354. if (y === void 0) { y = 0; }
  79355. if (z === void 0) { z = 0; }
  79356. var tmat = BABYLON.Tmp.Matrix[0];
  79357. var parentBone = bone.getParent();
  79358. tmat.copyFrom(bone.getLocalMatrix());
  79359. if (x !== 0 || y !== 0 || z !== 0) {
  79360. var tmat2 = BABYLON.Tmp.Matrix[1];
  79361. BABYLON.Matrix.IdentityToRef(tmat2);
  79362. tmat2.m[12] = x;
  79363. tmat2.m[13] = y;
  79364. tmat2.m[14] = z;
  79365. tmat2.multiplyToRef(tmat, tmat);
  79366. }
  79367. if (parentBone) {
  79368. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79369. }
  79370. tmat.multiplyToRef(meshMat, tmat);
  79371. position.x = tmat.m[12];
  79372. position.y = tmat.m[13];
  79373. position.z = tmat.m[14];
  79374. };
  79375. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79376. var len = bones.length;
  79377. var meshPos = this.mesh.position;
  79378. for (var i = 0; i < len; i++) {
  79379. var bone = bones[i];
  79380. var points = this._debugLines[i];
  79381. if (!points) {
  79382. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79383. this._debugLines[i] = points;
  79384. }
  79385. this._getBonePosition(points[0], bone, meshMat);
  79386. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79387. points[0].subtractInPlace(meshPos);
  79388. points[1].subtractInPlace(meshPos);
  79389. }
  79390. };
  79391. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79392. var len = bones.length;
  79393. var boneNum = 0;
  79394. var meshPos = this.mesh.position;
  79395. for (var i = len - 1; i >= 0; i--) {
  79396. var childBone = bones[i];
  79397. var parentBone = childBone.getParent();
  79398. if (!parentBone) {
  79399. continue;
  79400. }
  79401. var points = this._debugLines[boneNum];
  79402. if (!points) {
  79403. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79404. this._debugLines[boneNum] = points;
  79405. }
  79406. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79407. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79408. points[0].subtractInPlace(meshPos);
  79409. points[1].subtractInPlace(meshPos);
  79410. boneNum++;
  79411. }
  79412. };
  79413. SkeletonViewer.prototype.update = function () {
  79414. if (this.autoUpdateBonesMatrices) {
  79415. this.skeleton.computeAbsoluteTransforms();
  79416. }
  79417. if (this.skeleton.bones[0].length === undefined) {
  79418. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79419. }
  79420. else {
  79421. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79422. }
  79423. if (!this._debugMesh) {
  79424. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79425. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79426. }
  79427. else {
  79428. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79429. }
  79430. this._debugMesh.position.copyFrom(this.mesh.position);
  79431. this._debugMesh.color = this.color;
  79432. };
  79433. SkeletonViewer.prototype.dispose = function () {
  79434. if (this._debugMesh) {
  79435. this.isEnabled = false;
  79436. this._debugMesh.dispose();
  79437. this._debugMesh = null;
  79438. }
  79439. };
  79440. return SkeletonViewer;
  79441. }());
  79442. return Debug;
  79443. }());
  79444. BABYLON.Debug = Debug;
  79445. })(BABYLON || (BABYLON = {}));
  79446. //# sourceMappingURL=babylon.debugModules.js.map
  79447. var BABYLON;
  79448. (function (BABYLON) {
  79449. var RayHelper = /** @class */ (function () {
  79450. function RayHelper(ray) {
  79451. this.ray = ray;
  79452. }
  79453. RayHelper.CreateAndShow = function (ray, scene, color) {
  79454. var helper = new RayHelper(ray);
  79455. helper.show(scene, color);
  79456. return helper;
  79457. };
  79458. RayHelper.prototype.show = function (scene, color) {
  79459. if (!this._renderFunction && this.ray) {
  79460. var ray = this.ray;
  79461. this._renderFunction = this._render.bind(this);
  79462. this._scene = scene;
  79463. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79464. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79465. if (this._renderFunction) {
  79466. this._scene.registerBeforeRender(this._renderFunction);
  79467. }
  79468. }
  79469. if (color && this._renderLine) {
  79470. this._renderLine.color.copyFrom(color);
  79471. }
  79472. };
  79473. RayHelper.prototype.hide = function () {
  79474. if (this._renderFunction && this._scene) {
  79475. this._scene.unregisterBeforeRender(this._renderFunction);
  79476. this._scene = null;
  79477. this._renderFunction = null;
  79478. if (this._renderLine) {
  79479. this._renderLine.dispose();
  79480. this._renderLine = null;
  79481. }
  79482. this._renderPoints = [];
  79483. }
  79484. };
  79485. RayHelper.prototype._render = function () {
  79486. var ray = this.ray;
  79487. if (!ray) {
  79488. return;
  79489. }
  79490. var point = this._renderPoints[1];
  79491. var len = Math.min(ray.length, 1000000);
  79492. point.copyFrom(ray.direction);
  79493. point.scaleInPlace(len);
  79494. point.addInPlace(ray.origin);
  79495. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79496. };
  79497. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79498. this._attachedToMesh = mesh;
  79499. var ray = this.ray;
  79500. if (!ray) {
  79501. return;
  79502. }
  79503. if (!ray.direction) {
  79504. ray.direction = BABYLON.Vector3.Zero();
  79505. }
  79506. if (!ray.origin) {
  79507. ray.origin = BABYLON.Vector3.Zero();
  79508. }
  79509. if (length) {
  79510. ray.length = length;
  79511. }
  79512. if (!meshSpaceOrigin) {
  79513. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79514. }
  79515. if (!meshSpaceDirection) {
  79516. // -1 so that this will work with Mesh.lookAt
  79517. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79518. }
  79519. if (!this._meshSpaceDirection) {
  79520. this._meshSpaceDirection = meshSpaceDirection.clone();
  79521. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79522. }
  79523. else {
  79524. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79525. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79526. }
  79527. if (!this._updateToMeshFunction) {
  79528. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79529. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79530. }
  79531. this._updateToMesh();
  79532. };
  79533. RayHelper.prototype.detachFromMesh = function () {
  79534. if (this._attachedToMesh) {
  79535. if (this._updateToMeshFunction) {
  79536. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79537. }
  79538. this._attachedToMesh = null;
  79539. this._updateToMeshFunction = null;
  79540. }
  79541. };
  79542. RayHelper.prototype._updateToMesh = function () {
  79543. var ray = this.ray;
  79544. if (!this._attachedToMesh || !ray) {
  79545. return;
  79546. }
  79547. if (this._attachedToMesh._isDisposed) {
  79548. this.detachFromMesh();
  79549. return;
  79550. }
  79551. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79552. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79553. };
  79554. RayHelper.prototype.dispose = function () {
  79555. this.hide();
  79556. this.detachFromMesh();
  79557. this.ray = null;
  79558. };
  79559. return RayHelper;
  79560. }());
  79561. BABYLON.RayHelper = RayHelper;
  79562. })(BABYLON || (BABYLON = {}));
  79563. //# sourceMappingURL=babylon.rayHelper.js.map
  79564. var BABYLON;
  79565. (function (BABYLON) {
  79566. // load the inspector using require, if not present in the global namespace.
  79567. var DebugLayer = /** @class */ (function () {
  79568. function DebugLayer(scene) {
  79569. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79570. this._scene = scene;
  79571. // load inspector using require, if it doesn't exist on the global namespace.
  79572. }
  79573. /** Creates the inspector window. */
  79574. DebugLayer.prototype._createInspector = function (config) {
  79575. if (config === void 0) { config = {}; }
  79576. var popup = config.popup || false;
  79577. var initialTab = config.initialTab || 0;
  79578. var parentElement = config.parentElement || null;
  79579. if (!this._inspector) {
  79580. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79581. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79582. } // else nothing to do,; instance is already existing
  79583. };
  79584. DebugLayer.prototype.isVisible = function () {
  79585. if (!this._inspector) {
  79586. return false;
  79587. }
  79588. return true;
  79589. };
  79590. DebugLayer.prototype.hide = function () {
  79591. if (this._inspector) {
  79592. try {
  79593. this._inspector.dispose();
  79594. }
  79595. catch (e) {
  79596. // If the inspector has been removed directly from the inspector tool
  79597. }
  79598. this._inspector = null;
  79599. }
  79600. };
  79601. DebugLayer.prototype.show = function (config) {
  79602. if (config === void 0) { config = {}; }
  79603. if (typeof this.BJSINSPECTOR == 'undefined') {
  79604. // Load inspector and add it to the DOM
  79605. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79606. }
  79607. else {
  79608. // Otherwise creates the inspector
  79609. this._createInspector(config);
  79610. }
  79611. };
  79612. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79613. return DebugLayer;
  79614. }());
  79615. BABYLON.DebugLayer = DebugLayer;
  79616. })(BABYLON || (BABYLON = {}));
  79617. //# sourceMappingURL=babylon.debugLayer.js.map
  79618. var BABYLON;
  79619. (function (BABYLON) {
  79620. var BoundingBoxRenderer = /** @class */ (function () {
  79621. function BoundingBoxRenderer(scene) {
  79622. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79623. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79624. this.showBackLines = true;
  79625. this.renderList = new BABYLON.SmartArray(32);
  79626. this._vertexBuffers = {};
  79627. this._scene = scene;
  79628. }
  79629. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79630. if (this._colorShader) {
  79631. return;
  79632. }
  79633. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79634. attributes: [BABYLON.VertexBuffer.PositionKind],
  79635. uniforms: ["world", "viewProjection", "color"]
  79636. });
  79637. var engine = this._scene.getEngine();
  79638. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79639. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79640. this._createIndexBuffer();
  79641. };
  79642. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79643. var engine = this._scene.getEngine();
  79644. 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]);
  79645. };
  79646. BoundingBoxRenderer.prototype._rebuild = function () {
  79647. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79648. if (vb) {
  79649. vb._rebuild();
  79650. }
  79651. this._createIndexBuffer();
  79652. };
  79653. BoundingBoxRenderer.prototype.reset = function () {
  79654. this.renderList.reset();
  79655. };
  79656. BoundingBoxRenderer.prototype.render = function () {
  79657. if (this.renderList.length === 0) {
  79658. return;
  79659. }
  79660. this._prepareRessources();
  79661. if (!this._colorShader.isReady()) {
  79662. return;
  79663. }
  79664. var engine = this._scene.getEngine();
  79665. engine.setDepthWrite(false);
  79666. this._colorShader._preBind();
  79667. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79668. var boundingBox = this.renderList.data[boundingBoxIndex];
  79669. var min = boundingBox.minimum;
  79670. var max = boundingBox.maximum;
  79671. var diff = max.subtract(min);
  79672. var median = min.add(diff.scale(0.5));
  79673. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79674. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79675. .multiply(boundingBox.getWorldMatrix());
  79676. // VBOs
  79677. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79678. if (this.showBackLines) {
  79679. // Back
  79680. engine.setDepthFunctionToGreaterOrEqual();
  79681. this._scene.resetCachedMaterial();
  79682. this._colorShader.setColor4("color", this.backColor.toColor4());
  79683. this._colorShader.bind(worldMatrix);
  79684. // Draw order
  79685. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79686. }
  79687. // Front
  79688. engine.setDepthFunctionToLess();
  79689. this._scene.resetCachedMaterial();
  79690. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79691. this._colorShader.bind(worldMatrix);
  79692. // Draw order
  79693. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79694. }
  79695. this._colorShader.unbind();
  79696. engine.setDepthFunctionToLessOrEqual();
  79697. engine.setDepthWrite(true);
  79698. };
  79699. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79700. this._prepareRessources();
  79701. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79702. return;
  79703. }
  79704. var engine = this._scene.getEngine();
  79705. engine.setDepthWrite(false);
  79706. engine.setColorWrite(false);
  79707. this._colorShader._preBind();
  79708. var boundingBox = mesh._boundingInfo.boundingBox;
  79709. var min = boundingBox.minimum;
  79710. var max = boundingBox.maximum;
  79711. var diff = max.subtract(min);
  79712. var median = min.add(diff.scale(0.5));
  79713. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79714. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79715. .multiply(boundingBox.getWorldMatrix());
  79716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79717. engine.setDepthFunctionToLess();
  79718. this._scene.resetCachedMaterial();
  79719. this._colorShader.bind(worldMatrix);
  79720. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79721. this._colorShader.unbind();
  79722. engine.setDepthFunctionToLessOrEqual();
  79723. engine.setDepthWrite(true);
  79724. engine.setColorWrite(true);
  79725. };
  79726. BoundingBoxRenderer.prototype.dispose = function () {
  79727. if (!this._colorShader) {
  79728. return;
  79729. }
  79730. this.renderList.dispose();
  79731. this._colorShader.dispose();
  79732. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79733. if (buffer) {
  79734. buffer.dispose();
  79735. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79736. }
  79737. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79738. };
  79739. return BoundingBoxRenderer;
  79740. }());
  79741. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79742. })(BABYLON || (BABYLON = {}));
  79743. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79744. var BABYLON;
  79745. (function (BABYLON) {
  79746. var MorphTarget = /** @class */ (function () {
  79747. function MorphTarget(name, influence) {
  79748. if (influence === void 0) { influence = 0; }
  79749. this.name = name;
  79750. this.animations = new Array();
  79751. this._positions = null;
  79752. this._normals = null;
  79753. this._tangents = null;
  79754. this.onInfluenceChanged = new BABYLON.Observable();
  79755. this.influence = influence;
  79756. }
  79757. Object.defineProperty(MorphTarget.prototype, "influence", {
  79758. get: function () {
  79759. return this._influence;
  79760. },
  79761. set: function (influence) {
  79762. if (this._influence === influence) {
  79763. return;
  79764. }
  79765. var previous = this._influence;
  79766. this._influence = influence;
  79767. if (this.onInfluenceChanged.hasObservers) {
  79768. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79769. }
  79770. },
  79771. enumerable: true,
  79772. configurable: true
  79773. });
  79774. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79775. get: function () {
  79776. return !!this._positions;
  79777. },
  79778. enumerable: true,
  79779. configurable: true
  79780. });
  79781. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79782. get: function () {
  79783. return !!this._normals;
  79784. },
  79785. enumerable: true,
  79786. configurable: true
  79787. });
  79788. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79789. get: function () {
  79790. return !!this._tangents;
  79791. },
  79792. enumerable: true,
  79793. configurable: true
  79794. });
  79795. MorphTarget.prototype.setPositions = function (data) {
  79796. this._positions = data;
  79797. };
  79798. MorphTarget.prototype.getPositions = function () {
  79799. return this._positions;
  79800. };
  79801. MorphTarget.prototype.setNormals = function (data) {
  79802. this._normals = data;
  79803. };
  79804. MorphTarget.prototype.getNormals = function () {
  79805. return this._normals;
  79806. };
  79807. MorphTarget.prototype.setTangents = function (data) {
  79808. this._tangents = data;
  79809. };
  79810. MorphTarget.prototype.getTangents = function () {
  79811. return this._tangents;
  79812. };
  79813. /**
  79814. * Serializes the current target into a Serialization object.
  79815. * Returns the serialized object.
  79816. */
  79817. MorphTarget.prototype.serialize = function () {
  79818. var serializationObject = {};
  79819. serializationObject.name = this.name;
  79820. serializationObject.influence = this.influence;
  79821. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79822. if (this.hasNormals) {
  79823. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79824. }
  79825. if (this.hasTangents) {
  79826. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79827. }
  79828. // Animations
  79829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79830. return serializationObject;
  79831. };
  79832. // Statics
  79833. MorphTarget.Parse = function (serializationObject) {
  79834. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79835. result.setPositions(serializationObject.positions);
  79836. if (serializationObject.normals) {
  79837. result.setNormals(serializationObject.normals);
  79838. }
  79839. if (serializationObject.tangents) {
  79840. result.setTangents(serializationObject.tangents);
  79841. }
  79842. // Animations
  79843. if (serializationObject.animations) {
  79844. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79845. var parsedAnimation = serializationObject.animations[animationIndex];
  79846. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79847. }
  79848. }
  79849. return result;
  79850. };
  79851. MorphTarget.FromMesh = function (mesh, name, influence) {
  79852. if (!name) {
  79853. name = mesh.name;
  79854. }
  79855. var result = new MorphTarget(name, influence);
  79856. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79857. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79858. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79859. }
  79860. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79861. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79862. }
  79863. return result;
  79864. };
  79865. return MorphTarget;
  79866. }());
  79867. BABYLON.MorphTarget = MorphTarget;
  79868. })(BABYLON || (BABYLON = {}));
  79869. //# sourceMappingURL=babylon.morphTarget.js.map
  79870. var BABYLON;
  79871. (function (BABYLON) {
  79872. var MorphTargetManager = /** @class */ (function () {
  79873. function MorphTargetManager(scene) {
  79874. if (scene === void 0) { scene = null; }
  79875. this._targets = new Array();
  79876. this._targetObservable = new Array();
  79877. this._activeTargets = new BABYLON.SmartArray(16);
  79878. this._supportsNormals = false;
  79879. this._supportsTangents = false;
  79880. this._vertexCount = 0;
  79881. this._uniqueId = 0;
  79882. this._tempInfluences = new Array();
  79883. if (!scene) {
  79884. scene = BABYLON.Engine.LastCreatedScene;
  79885. }
  79886. this._scene = scene;
  79887. if (this._scene) {
  79888. this._scene.morphTargetManagers.push(this);
  79889. this._uniqueId = this._scene.getUniqueId();
  79890. }
  79891. }
  79892. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79893. get: function () {
  79894. return this._uniqueId;
  79895. },
  79896. enumerable: true,
  79897. configurable: true
  79898. });
  79899. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79900. get: function () {
  79901. return this._vertexCount;
  79902. },
  79903. enumerable: true,
  79904. configurable: true
  79905. });
  79906. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79907. get: function () {
  79908. return this._supportsNormals;
  79909. },
  79910. enumerable: true,
  79911. configurable: true
  79912. });
  79913. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79914. get: function () {
  79915. return this._supportsTangents;
  79916. },
  79917. enumerable: true,
  79918. configurable: true
  79919. });
  79920. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79921. get: function () {
  79922. return this._targets.length;
  79923. },
  79924. enumerable: true,
  79925. configurable: true
  79926. });
  79927. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79928. get: function () {
  79929. return this._activeTargets.length;
  79930. },
  79931. enumerable: true,
  79932. configurable: true
  79933. });
  79934. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79935. get: function () {
  79936. return this._influences;
  79937. },
  79938. enumerable: true,
  79939. configurable: true
  79940. });
  79941. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79942. return this._activeTargets.data[index];
  79943. };
  79944. MorphTargetManager.prototype.getTarget = function (index) {
  79945. return this._targets[index];
  79946. };
  79947. MorphTargetManager.prototype.addTarget = function (target) {
  79948. var _this = this;
  79949. this._targets.push(target);
  79950. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79951. _this._syncActiveTargets(needUpdate);
  79952. }));
  79953. this._syncActiveTargets(true);
  79954. };
  79955. MorphTargetManager.prototype.removeTarget = function (target) {
  79956. var index = this._targets.indexOf(target);
  79957. if (index >= 0) {
  79958. this._targets.splice(index, 1);
  79959. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79960. this._syncActiveTargets(true);
  79961. }
  79962. };
  79963. /**
  79964. * Serializes the current manager into a Serialization object.
  79965. * Returns the serialized object.
  79966. */
  79967. MorphTargetManager.prototype.serialize = function () {
  79968. var serializationObject = {};
  79969. serializationObject.id = this.uniqueId;
  79970. serializationObject.targets = [];
  79971. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79972. var target = _a[_i];
  79973. serializationObject.targets.push(target.serialize());
  79974. }
  79975. return serializationObject;
  79976. };
  79977. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79978. var influenceCount = 0;
  79979. this._activeTargets.reset();
  79980. this._supportsNormals = true;
  79981. this._supportsTangents = true;
  79982. this._vertexCount = 0;
  79983. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79984. var target = _a[_i];
  79985. this._activeTargets.push(target);
  79986. this._tempInfluences[influenceCount++] = target.influence;
  79987. var positions = target.getPositions();
  79988. if (positions) {
  79989. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79990. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79991. var vertexCount = positions.length / 3;
  79992. if (this._vertexCount === 0) {
  79993. this._vertexCount = vertexCount;
  79994. }
  79995. else if (this._vertexCount !== vertexCount) {
  79996. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79997. return;
  79998. }
  79999. }
  80000. }
  80001. if (!this._influences || this._influences.length !== influenceCount) {
  80002. this._influences = new Float32Array(influenceCount);
  80003. }
  80004. for (var index = 0; index < influenceCount; index++) {
  80005. this._influences[index] = this._tempInfluences[index];
  80006. }
  80007. if (needUpdate && this._scene) {
  80008. // Flag meshes as dirty to resync with the active targets
  80009. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80010. var mesh = _c[_b];
  80011. if (mesh.morphTargetManager === this) {
  80012. mesh._syncGeometryWithMorphTargetManager();
  80013. }
  80014. }
  80015. }
  80016. };
  80017. // Statics
  80018. MorphTargetManager.Parse = function (serializationObject, scene) {
  80019. var result = new MorphTargetManager(scene);
  80020. result._uniqueId = serializationObject.id;
  80021. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80022. var targetData = _a[_i];
  80023. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80024. }
  80025. return result;
  80026. };
  80027. return MorphTargetManager;
  80028. }());
  80029. BABYLON.MorphTargetManager = MorphTargetManager;
  80030. })(BABYLON || (BABYLON = {}));
  80031. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80032. var BABYLON;
  80033. (function (BABYLON) {
  80034. var Octree = /** @class */ (function () {
  80035. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80036. if (maxDepth === void 0) { maxDepth = 2; }
  80037. this.maxDepth = maxDepth;
  80038. this.dynamicContent = new Array();
  80039. this._maxBlockCapacity = maxBlockCapacity || 64;
  80040. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80041. this._creationFunc = creationFunc;
  80042. }
  80043. // Methods
  80044. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80045. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80046. };
  80047. Octree.prototype.addMesh = function (entry) {
  80048. for (var index = 0; index < this.blocks.length; index++) {
  80049. var block = this.blocks[index];
  80050. block.addEntry(entry);
  80051. }
  80052. };
  80053. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80054. this._selectionContent.reset();
  80055. for (var index = 0; index < this.blocks.length; index++) {
  80056. var block = this.blocks[index];
  80057. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80058. }
  80059. if (allowDuplicate) {
  80060. this._selectionContent.concat(this.dynamicContent);
  80061. }
  80062. else {
  80063. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80064. }
  80065. return this._selectionContent;
  80066. };
  80067. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80068. this._selectionContent.reset();
  80069. for (var index = 0; index < this.blocks.length; index++) {
  80070. var block = this.blocks[index];
  80071. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80072. }
  80073. if (allowDuplicate) {
  80074. this._selectionContent.concat(this.dynamicContent);
  80075. }
  80076. else {
  80077. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80078. }
  80079. return this._selectionContent;
  80080. };
  80081. Octree.prototype.intersectsRay = function (ray) {
  80082. this._selectionContent.reset();
  80083. for (var index = 0; index < this.blocks.length; index++) {
  80084. var block = this.blocks[index];
  80085. block.intersectsRay(ray, this._selectionContent);
  80086. }
  80087. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80088. return this._selectionContent;
  80089. };
  80090. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80091. target.blocks = new Array();
  80092. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80093. // Segmenting space
  80094. for (var x = 0; x < 2; x++) {
  80095. for (var y = 0; y < 2; y++) {
  80096. for (var z = 0; z < 2; z++) {
  80097. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80098. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80099. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80100. block.addEntries(entries);
  80101. target.blocks.push(block);
  80102. }
  80103. }
  80104. }
  80105. };
  80106. Octree.CreationFuncForMeshes = function (entry, block) {
  80107. var boundingInfo = entry.getBoundingInfo();
  80108. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80109. block.entries.push(entry);
  80110. }
  80111. };
  80112. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80113. var boundingInfo = entry.getBoundingInfo();
  80114. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80115. block.entries.push(entry);
  80116. }
  80117. };
  80118. return Octree;
  80119. }());
  80120. BABYLON.Octree = Octree;
  80121. })(BABYLON || (BABYLON = {}));
  80122. //# sourceMappingURL=babylon.octree.js.map
  80123. var BABYLON;
  80124. (function (BABYLON) {
  80125. var OctreeBlock = /** @class */ (function () {
  80126. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80127. this.entries = new Array();
  80128. this._boundingVectors = new Array();
  80129. this._capacity = capacity;
  80130. this._depth = depth;
  80131. this._maxDepth = maxDepth;
  80132. this._creationFunc = creationFunc;
  80133. this._minPoint = minPoint;
  80134. this._maxPoint = maxPoint;
  80135. this._boundingVectors.push(minPoint.clone());
  80136. this._boundingVectors.push(maxPoint.clone());
  80137. this._boundingVectors.push(minPoint.clone());
  80138. this._boundingVectors[2].x = maxPoint.x;
  80139. this._boundingVectors.push(minPoint.clone());
  80140. this._boundingVectors[3].y = maxPoint.y;
  80141. this._boundingVectors.push(minPoint.clone());
  80142. this._boundingVectors[4].z = maxPoint.z;
  80143. this._boundingVectors.push(maxPoint.clone());
  80144. this._boundingVectors[5].z = minPoint.z;
  80145. this._boundingVectors.push(maxPoint.clone());
  80146. this._boundingVectors[6].x = minPoint.x;
  80147. this._boundingVectors.push(maxPoint.clone());
  80148. this._boundingVectors[7].y = minPoint.y;
  80149. }
  80150. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80151. // Property
  80152. get: function () {
  80153. return this._capacity;
  80154. },
  80155. enumerable: true,
  80156. configurable: true
  80157. });
  80158. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80159. get: function () {
  80160. return this._minPoint;
  80161. },
  80162. enumerable: true,
  80163. configurable: true
  80164. });
  80165. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80166. get: function () {
  80167. return this._maxPoint;
  80168. },
  80169. enumerable: true,
  80170. configurable: true
  80171. });
  80172. // Methods
  80173. OctreeBlock.prototype.addEntry = function (entry) {
  80174. if (this.blocks) {
  80175. for (var index = 0; index < this.blocks.length; index++) {
  80176. var block = this.blocks[index];
  80177. block.addEntry(entry);
  80178. }
  80179. return;
  80180. }
  80181. this._creationFunc(entry, this);
  80182. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80183. this.createInnerBlocks();
  80184. }
  80185. };
  80186. OctreeBlock.prototype.addEntries = function (entries) {
  80187. for (var index = 0; index < entries.length; index++) {
  80188. var mesh = entries[index];
  80189. this.addEntry(mesh);
  80190. }
  80191. };
  80192. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80193. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80194. if (this.blocks) {
  80195. for (var index = 0; index < this.blocks.length; index++) {
  80196. var block = this.blocks[index];
  80197. block.select(frustumPlanes, selection, allowDuplicate);
  80198. }
  80199. return;
  80200. }
  80201. if (allowDuplicate) {
  80202. selection.concat(this.entries);
  80203. }
  80204. else {
  80205. selection.concatWithNoDuplicate(this.entries);
  80206. }
  80207. }
  80208. };
  80209. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80210. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80211. if (this.blocks) {
  80212. for (var index = 0; index < this.blocks.length; index++) {
  80213. var block = this.blocks[index];
  80214. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80215. }
  80216. return;
  80217. }
  80218. if (allowDuplicate) {
  80219. selection.concat(this.entries);
  80220. }
  80221. else {
  80222. selection.concatWithNoDuplicate(this.entries);
  80223. }
  80224. }
  80225. };
  80226. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80227. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80228. if (this.blocks) {
  80229. for (var index = 0; index < this.blocks.length; index++) {
  80230. var block = this.blocks[index];
  80231. block.intersectsRay(ray, selection);
  80232. }
  80233. return;
  80234. }
  80235. selection.concatWithNoDuplicate(this.entries);
  80236. }
  80237. };
  80238. OctreeBlock.prototype.createInnerBlocks = function () {
  80239. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80240. };
  80241. return OctreeBlock;
  80242. }());
  80243. BABYLON.OctreeBlock = OctreeBlock;
  80244. })(BABYLON || (BABYLON = {}));
  80245. //# sourceMappingURL=babylon.octreeBlock.js.map
  80246. var BABYLON;
  80247. (function (BABYLON) {
  80248. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80249. __extends(VRDistortionCorrectionPostProcess, _super);
  80250. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80251. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80252. 'LensCenter',
  80253. 'Scale',
  80254. 'ScaleIn',
  80255. 'HmdWarpParam'
  80256. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80257. _this._isRightEye = isRightEye;
  80258. _this._distortionFactors = vrMetrics.distortionK;
  80259. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80260. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80261. _this.adaptScaleToCurrentViewport = true;
  80262. _this.onSizeChangedObservable.add(function () {
  80263. _this.aspectRatio = _this.width * .5 / _this.height;
  80264. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80265. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80266. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80267. });
  80268. _this.onApplyObservable.add(function (effect) {
  80269. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80270. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80271. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80272. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80273. });
  80274. return _this;
  80275. }
  80276. return VRDistortionCorrectionPostProcess;
  80277. }(BABYLON.PostProcess));
  80278. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80279. })(BABYLON || (BABYLON = {}));
  80280. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80281. var BABYLON;
  80282. (function (BABYLON) {
  80283. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80284. __extends(AnaglyphPostProcess, _super);
  80285. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80286. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80287. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80288. _this.onApplyObservable.add(function (effect) {
  80289. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80290. });
  80291. return _this;
  80292. }
  80293. return AnaglyphPostProcess;
  80294. }(BABYLON.PostProcess));
  80295. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80296. })(BABYLON || (BABYLON = {}));
  80297. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80298. var BABYLON;
  80299. (function (BABYLON) {
  80300. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80301. __extends(StereoscopicInterlacePostProcess, _super);
  80302. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80303. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80304. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80305. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80306. _this.onSizeChangedObservable.add(function () {
  80307. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80308. });
  80309. _this.onApplyObservable.add(function (effect) {
  80310. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80311. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80312. });
  80313. return _this;
  80314. }
  80315. return StereoscopicInterlacePostProcess;
  80316. }(BABYLON.PostProcess));
  80317. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80318. })(BABYLON || (BABYLON = {}));
  80319. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80320. var BABYLON;
  80321. (function (BABYLON) {
  80322. /**
  80323. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80324. * Screen rotation is taken into account.
  80325. */
  80326. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80327. function FreeCameraDeviceOrientationInput() {
  80328. var _this = this;
  80329. this._screenOrientationAngle = 0;
  80330. this._screenQuaternion = new BABYLON.Quaternion();
  80331. this._alpha = 0;
  80332. this._beta = 0;
  80333. this._gamma = 0;
  80334. this._orientationChanged = function () {
  80335. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80336. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80337. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80338. };
  80339. this._deviceOrientation = function (evt) {
  80340. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80341. _this._beta = evt.beta !== null ? evt.beta : 0;
  80342. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80343. };
  80344. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80345. this._orientationChanged();
  80346. }
  80347. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80348. get: function () {
  80349. return this._camera;
  80350. },
  80351. set: function (camera) {
  80352. this._camera = camera;
  80353. if (this._camera != null && !this._camera.rotationQuaternion) {
  80354. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80355. }
  80356. },
  80357. enumerable: true,
  80358. configurable: true
  80359. });
  80360. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80361. window.addEventListener("orientationchange", this._orientationChanged);
  80362. window.addEventListener("deviceorientation", this._deviceOrientation);
  80363. //In certain cases, the attach control is called AFTER orientation was changed,
  80364. //So this is needed.
  80365. this._orientationChanged();
  80366. };
  80367. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80368. window.removeEventListener("orientationchange", this._orientationChanged);
  80369. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80370. };
  80371. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80372. //if no device orientation provided, don't update the rotation.
  80373. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80374. if (!this._alpha)
  80375. return;
  80376. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80377. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80378. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80379. //Mirror on XY Plane
  80380. this._camera.rotationQuaternion.z *= -1;
  80381. this._camera.rotationQuaternion.w *= -1;
  80382. };
  80383. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80384. return "FreeCameraDeviceOrientationInput";
  80385. };
  80386. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80387. return "deviceOrientation";
  80388. };
  80389. return FreeCameraDeviceOrientationInput;
  80390. }());
  80391. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80392. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80393. })(BABYLON || (BABYLON = {}));
  80394. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80395. var BABYLON;
  80396. (function (BABYLON) {
  80397. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80398. function ArcRotateCameraVRDeviceOrientationInput() {
  80399. this.alphaCorrection = 1;
  80400. this.betaCorrection = 1;
  80401. this.gammaCorrection = 1;
  80402. this._alpha = 0;
  80403. this._gamma = 0;
  80404. this._dirty = false;
  80405. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80406. }
  80407. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80408. this.camera.attachControl(element, noPreventDefault);
  80409. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80410. };
  80411. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80412. if (evt.alpha !== null) {
  80413. this._alpha = +evt.alpha | 0;
  80414. }
  80415. if (evt.gamma !== null) {
  80416. this._gamma = +evt.gamma | 0;
  80417. }
  80418. this._dirty = true;
  80419. };
  80420. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80421. if (this._dirty) {
  80422. this._dirty = false;
  80423. if (this._gamma < 0) {
  80424. this._gamma = 180 + this._gamma;
  80425. }
  80426. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80427. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80428. }
  80429. };
  80430. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80431. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80432. };
  80433. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80434. return "ArcRotateCameraVRDeviceOrientationInput";
  80435. };
  80436. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80437. return "VRDeviceOrientation";
  80438. };
  80439. return ArcRotateCameraVRDeviceOrientationInput;
  80440. }());
  80441. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80442. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80443. })(BABYLON || (BABYLON = {}));
  80444. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80445. var BABYLON;
  80446. (function (BABYLON) {
  80447. var VRCameraMetrics = /** @class */ (function () {
  80448. function VRCameraMetrics() {
  80449. this.compensateDistortion = true;
  80450. }
  80451. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80452. get: function () {
  80453. return this.hResolution / (2 * this.vResolution);
  80454. },
  80455. enumerable: true,
  80456. configurable: true
  80457. });
  80458. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80459. get: function () {
  80460. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80461. },
  80462. enumerable: true,
  80463. configurable: true
  80464. });
  80465. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80466. get: function () {
  80467. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80468. var h = (4 * meters) / this.hScreenSize;
  80469. return BABYLON.Matrix.Translation(h, 0, 0);
  80470. },
  80471. enumerable: true,
  80472. configurable: true
  80473. });
  80474. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80475. get: function () {
  80476. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80477. var h = (4 * meters) / this.hScreenSize;
  80478. return BABYLON.Matrix.Translation(-h, 0, 0);
  80479. },
  80480. enumerable: true,
  80481. configurable: true
  80482. });
  80483. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80484. get: function () {
  80485. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80486. },
  80487. enumerable: true,
  80488. configurable: true
  80489. });
  80490. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80491. get: function () {
  80492. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. VRCameraMetrics.GetDefault = function () {
  80498. var result = new VRCameraMetrics();
  80499. result.hResolution = 1280;
  80500. result.vResolution = 800;
  80501. result.hScreenSize = 0.149759993;
  80502. result.vScreenSize = 0.0935999975;
  80503. result.vScreenCenter = 0.0467999987;
  80504. result.eyeToScreenDistance = 0.0410000011;
  80505. result.lensSeparationDistance = 0.0635000020;
  80506. result.interpupillaryDistance = 0.0640000030;
  80507. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80508. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80509. result.postProcessScaleFactor = 1.714605507808412;
  80510. result.lensCenterOffset = 0.151976421;
  80511. return result;
  80512. };
  80513. return VRCameraMetrics;
  80514. }());
  80515. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80516. })(BABYLON || (BABYLON = {}));
  80517. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80518. var BABYLON;
  80519. (function (BABYLON) {
  80520. /**
  80521. * This represents a WebVR camera.
  80522. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80523. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80524. */
  80525. var WebVRFreeCamera = /** @class */ (function (_super) {
  80526. __extends(WebVRFreeCamera, _super);
  80527. /**
  80528. * Instantiates a WebVRFreeCamera.
  80529. * @param name The name of the WebVRFreeCamera
  80530. * @param position The starting anchor position for the camera
  80531. * @param scene The scene the camera belongs to
  80532. * @param webVROptions a set of customizable options for the webVRCamera
  80533. */
  80534. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80535. if (webVROptions === void 0) { webVROptions = {}; }
  80536. var _this = _super.call(this, name, position, scene) || this;
  80537. _this.webVROptions = webVROptions;
  80538. /**
  80539. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80540. */
  80541. _this._vrDevice = null;
  80542. /**
  80543. * The rawPose of the vrDevice.
  80544. */
  80545. _this.rawPose = null;
  80546. _this._specsVersion = "1.1";
  80547. _this._attached = false;
  80548. _this._descendants = [];
  80549. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80550. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80551. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80552. _this._standingMatrix = null;
  80553. /**
  80554. * Represents device position in babylon space.
  80555. */
  80556. _this.devicePosition = BABYLON.Vector3.Zero();
  80557. /**
  80558. * Represents device rotation in babylon space.
  80559. */
  80560. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80561. /**
  80562. * The scale of the device to be used when translating from device space to babylon space.
  80563. */
  80564. _this.deviceScaleFactor = 1;
  80565. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80566. _this._worldToDevice = BABYLON.Matrix.Identity();
  80567. /**
  80568. * References to the webVR controllers for the vrDevice.
  80569. */
  80570. _this.controllers = [];
  80571. /**
  80572. * Emits an event when a controller is attached.
  80573. */
  80574. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80575. /**
  80576. * Emits an event when a controller's mesh has been loaded;
  80577. */
  80578. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80579. /**
  80580. * If the rig cameras be used as parent instead of this camera.
  80581. */
  80582. _this.rigParenting = true;
  80583. _this._defaultHeight = undefined;
  80584. _this._workingVector = BABYLON.Vector3.Zero();
  80585. _this._oneVector = BABYLON.Vector3.One();
  80586. _this._workingMatrix = BABYLON.Matrix.Identity();
  80587. _this._cache.position = BABYLON.Vector3.Zero();
  80588. if (webVROptions.defaultHeight) {
  80589. _this._defaultHeight = webVROptions.defaultHeight;
  80590. _this.position.y = _this._defaultHeight;
  80591. }
  80592. _this.minZ = 0.1;
  80593. //legacy support - the compensation boolean was removed.
  80594. if (arguments.length === 5) {
  80595. _this.webVROptions = arguments[4];
  80596. }
  80597. // default webVR options
  80598. if (_this.webVROptions.trackPosition == undefined) {
  80599. _this.webVROptions.trackPosition = true;
  80600. }
  80601. if (_this.webVROptions.controllerMeshes == undefined) {
  80602. _this.webVROptions.controllerMeshes = true;
  80603. }
  80604. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80605. _this.webVROptions.defaultLightingOnControllers = true;
  80606. }
  80607. _this.rotationQuaternion = new BABYLON.Quaternion();
  80608. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80609. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80610. }
  80611. //enable VR
  80612. var engine = _this.getEngine();
  80613. _this._onVREnabled = function (success) { if (success) {
  80614. _this.initControllers();
  80615. } };
  80616. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80617. engine.initWebVR().add(function (event) {
  80618. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80619. return;
  80620. }
  80621. _this._vrDevice = event.vrDisplay;
  80622. //reset the rig parameters.
  80623. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80624. if (_this._attached) {
  80625. _this.getEngine().enableVR();
  80626. }
  80627. });
  80628. if (typeof (VRFrameData) !== "undefined")
  80629. _this._frameData = new VRFrameData();
  80630. /**
  80631. * The idea behind the following lines:
  80632. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80633. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80634. * the second will not show it correctly.
  80635. *
  80636. * To solve this - each object that has the camera as parent will be added to a protected array.
  80637. * When the rig camera renders, it will take this array and set all of those to be its children.
  80638. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80639. * Amazing!
  80640. */
  80641. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80642. if (camera.parent === _this && _this.rigParenting) {
  80643. _this._descendants = _this.getDescendants(true, function (n) {
  80644. // don't take the cameras or the controllers!
  80645. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80646. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80647. return !isController && !isRigCamera;
  80648. });
  80649. _this._descendants.forEach(function (node) {
  80650. node.parent = camera;
  80651. });
  80652. }
  80653. });
  80654. scene.onAfterCameraRenderObservable.add(function (camera) {
  80655. if (camera.parent === _this && _this.rigParenting) {
  80656. _this._descendants.forEach(function (node) {
  80657. node.parent = _this;
  80658. });
  80659. }
  80660. });
  80661. return _this;
  80662. }
  80663. /**
  80664. * Gets the device distance from the ground in meters.
  80665. * @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.
  80666. */
  80667. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80668. if (this._standingMatrix) {
  80669. // Add standing matrix offset to get real offset from ground in room
  80670. this._standingMatrix.getTranslationToRef(this._workingVector);
  80671. return this._deviceRoomPosition.y + this._workingVector.y;
  80672. }
  80673. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80674. return this._defaultHeight || 0;
  80675. };
  80676. /**
  80677. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80678. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80679. */
  80680. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80681. var _this = this;
  80682. if (callback === void 0) { callback = function (bool) { }; }
  80683. // Use standing matrix if available
  80684. this.getEngine().initWebVRAsync().then(function (result) {
  80685. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80686. callback(false);
  80687. }
  80688. else {
  80689. _this._standingMatrix = new BABYLON.Matrix();
  80690. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80691. if (!_this.getScene().useRightHandedSystem) {
  80692. [2, 6, 8, 9, 14].forEach(function (num) {
  80693. if (_this._standingMatrix) {
  80694. _this._standingMatrix.m[num] *= -1;
  80695. }
  80696. });
  80697. }
  80698. callback(true);
  80699. }
  80700. });
  80701. };
  80702. /**
  80703. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80704. * @returns A promise with a boolean set to if the standing matrix is supported.
  80705. */
  80706. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80707. var _this = this;
  80708. return new Promise(function (res, rej) {
  80709. _this.useStandingMatrix(function (supported) {
  80710. res(supported);
  80711. });
  80712. });
  80713. };
  80714. /**
  80715. * Disposes the camera
  80716. */
  80717. WebVRFreeCamera.prototype.dispose = function () {
  80718. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80719. _super.prototype.dispose.call(this);
  80720. };
  80721. /**
  80722. * Gets a vrController by name.
  80723. * @param name The name of the controller to retreive
  80724. * @returns the controller matching the name specified or null if not found
  80725. */
  80726. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80727. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80728. var gp = _a[_i];
  80729. if (gp.hand === name) {
  80730. return gp;
  80731. }
  80732. }
  80733. return null;
  80734. };
  80735. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80736. /**
  80737. * The controller corrisponding to the users left hand.
  80738. */
  80739. get: function () {
  80740. if (!this._leftController) {
  80741. this._leftController = this.getControllerByName("left");
  80742. }
  80743. return this._leftController;
  80744. },
  80745. enumerable: true,
  80746. configurable: true
  80747. });
  80748. ;
  80749. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80750. /**
  80751. * The controller corrisponding to the users right hand.
  80752. */
  80753. get: function () {
  80754. if (!this._rightController) {
  80755. this._rightController = this.getControllerByName("right");
  80756. }
  80757. return this._rightController;
  80758. },
  80759. enumerable: true,
  80760. configurable: true
  80761. });
  80762. ;
  80763. /**
  80764. * Casts a ray forward from the vrCamera's gaze.
  80765. * @param length Length of the ray (default: 100)
  80766. * @returns the ray corrisponding to the gaze
  80767. */
  80768. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80769. if (length === void 0) { length = 100; }
  80770. if (this.leftCamera) {
  80771. // Use left eye to avoid computation to compute center on every call
  80772. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80773. }
  80774. else {
  80775. return _super.prototype.getForwardRay.call(this, length);
  80776. }
  80777. };
  80778. /**
  80779. * Updates the camera based on device's frame data
  80780. */
  80781. WebVRFreeCamera.prototype._checkInputs = function () {
  80782. if (this._vrDevice && this._vrDevice.isPresenting) {
  80783. this._vrDevice.getFrameData(this._frameData);
  80784. this.updateFromDevice(this._frameData.pose);
  80785. }
  80786. _super.prototype._checkInputs.call(this);
  80787. };
  80788. /**
  80789. * Updates the poseControlled values based on the input device pose.
  80790. * @param poseData Pose coming from the device
  80791. */
  80792. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80793. if (poseData && poseData.orientation) {
  80794. this.rawPose = poseData;
  80795. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80796. if (this.getScene().useRightHandedSystem) {
  80797. this._deviceRoomRotationQuaternion.z *= -1;
  80798. this._deviceRoomRotationQuaternion.w *= -1;
  80799. }
  80800. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80801. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80802. if (this.getScene().useRightHandedSystem) {
  80803. this._deviceRoomPosition.z *= -1;
  80804. }
  80805. }
  80806. }
  80807. };
  80808. /**
  80809. * WebVR's attach control will start broadcasting frames to the device.
  80810. * Note that in certain browsers (chrome for example) this function must be called
  80811. * within a user-interaction callback. Example:
  80812. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80813. *
  80814. * @param element html element to attach the vrDevice to
  80815. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80816. */
  80817. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80818. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80819. this._attached = true;
  80820. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80821. if (this._vrDevice) {
  80822. this.getEngine().enableVR();
  80823. }
  80824. };
  80825. /**
  80826. * Detaches the camera from the html element and disables VR
  80827. *
  80828. * @param element html element to detach from
  80829. */
  80830. WebVRFreeCamera.prototype.detachControl = function (element) {
  80831. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80832. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80833. _super.prototype.detachControl.call(this, element);
  80834. this._attached = false;
  80835. this.getEngine().disableVR();
  80836. };
  80837. /**
  80838. * @returns the name of this class
  80839. */
  80840. WebVRFreeCamera.prototype.getClassName = function () {
  80841. return "WebVRFreeCamera";
  80842. };
  80843. /**
  80844. * Calls resetPose on the vrDisplay
  80845. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80846. */
  80847. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80848. //uses the vrDisplay's "resetPose()".
  80849. //pitch and roll won't be affected.
  80850. this._vrDevice.resetPose();
  80851. };
  80852. /**
  80853. * Updates the rig cameras (left and right eye)
  80854. */
  80855. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80856. var camLeft = this._rigCameras[0];
  80857. var camRight = this._rigCameras[1];
  80858. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80859. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80860. camLeft.position.copyFrom(this._deviceRoomPosition);
  80861. camRight.position.copyFrom(this._deviceRoomPosition);
  80862. };
  80863. /**
  80864. * Updates the cached values of the camera
  80865. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80866. */
  80867. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80868. var _this = this;
  80869. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80870. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80871. if (!this.updateCacheCalled) {
  80872. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80873. this.updateCacheCalled = true;
  80874. this.update();
  80875. }
  80876. // Set working vector to the device position in room space rotated by the new rotation
  80877. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80878. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80879. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80880. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80881. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80882. // Add translation from anchor position
  80883. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80884. this._workingVector.addInPlace(this.position);
  80885. this._workingVector.subtractInPlace(this._cache.position);
  80886. this._deviceToWorld.setTranslation(this._workingVector);
  80887. // Set an inverted matrix to be used when updating the camera
  80888. this._deviceToWorld.invertToRef(this._worldToDevice);
  80889. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80890. this.controllers.forEach(function (controller) {
  80891. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80892. controller.update();
  80893. });
  80894. }
  80895. if (!ignoreParentClass) {
  80896. _super.prototype._updateCache.call(this);
  80897. }
  80898. this.updateCacheCalled = false;
  80899. };
  80900. /**
  80901. * Updates the current device position and rotation in the babylon world
  80902. */
  80903. WebVRFreeCamera.prototype.update = function () {
  80904. // Get current device position in babylon world
  80905. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80906. // Get current device rotation in babylon world
  80907. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80908. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80909. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80910. _super.prototype.update.call(this);
  80911. };
  80912. /**
  80913. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80914. * @returns an identity matrix
  80915. */
  80916. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80917. return BABYLON.Matrix.Identity();
  80918. };
  80919. /**
  80920. * This function is called by the two RIG cameras.
  80921. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80922. */
  80923. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80924. var _this = this;
  80925. // Update the parent camera prior to using a child camera to avoid desynchronization
  80926. var parentCamera = this._cameraRigParams["parentCamera"];
  80927. parentCamera._updateCache();
  80928. //WebVR 1.1
  80929. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80930. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80931. if (!this.getScene().useRightHandedSystem) {
  80932. [2, 6, 8, 9, 14].forEach(function (num) {
  80933. _this._webvrViewMatrix.m[num] *= -1;
  80934. });
  80935. }
  80936. // update the camera rotation matrix
  80937. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80938. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80939. // Computing target and final matrix
  80940. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80941. // should the view matrix be updated with scale and position offset?
  80942. if (parentCamera.deviceScaleFactor !== 1) {
  80943. this._webvrViewMatrix.invert();
  80944. // scale the position, if set
  80945. if (parentCamera.deviceScaleFactor) {
  80946. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80947. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80948. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80949. }
  80950. this._webvrViewMatrix.invert();
  80951. }
  80952. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80953. return this._webvrViewMatrix;
  80954. };
  80955. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80956. var _this = this;
  80957. var parentCamera = this.parent;
  80958. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80959. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80960. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80961. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80962. //babylon compatible matrix
  80963. if (!this.getScene().useRightHandedSystem) {
  80964. [8, 9, 10, 11].forEach(function (num) {
  80965. _this._projectionMatrix.m[num] *= -1;
  80966. });
  80967. }
  80968. return this._projectionMatrix;
  80969. };
  80970. /**
  80971. * Initializes the controllers and their meshes
  80972. */
  80973. WebVRFreeCamera.prototype.initControllers = function () {
  80974. var _this = this;
  80975. this.controllers = [];
  80976. var manager = this.getScene().gamepadManager;
  80977. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80978. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80979. var webVrController = gamepad;
  80980. if (webVrController.defaultModel) {
  80981. webVrController.defaultModel.setEnabled(false);
  80982. }
  80983. if (webVrController.hand === "right") {
  80984. _this._rightController = null;
  80985. }
  80986. if (webVrController.hand === "left") {
  80987. _this._leftController = null;
  80988. }
  80989. var controllerIndex = _this.controllers.indexOf(webVrController);
  80990. if (controllerIndex !== -1) {
  80991. _this.controllers.splice(controllerIndex, 1);
  80992. }
  80993. }
  80994. });
  80995. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80996. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80997. var webVrController_1 = gamepad;
  80998. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80999. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81000. if (_this.webVROptions.controllerMeshes) {
  81001. if (webVrController_1.defaultModel) {
  81002. webVrController_1.defaultModel.setEnabled(true);
  81003. }
  81004. else {
  81005. // Load the meshes
  81006. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81007. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81008. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81009. if (_this.webVROptions.defaultLightingOnControllers) {
  81010. if (!_this._lightOnControllers) {
  81011. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81012. }
  81013. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81014. var children = mesh.getChildren();
  81015. if (children.length !== 0) {
  81016. children.forEach(function (mesh) {
  81017. light.includedOnlyMeshes.push(mesh);
  81018. activateLightOnSubMeshes_1(mesh, light);
  81019. });
  81020. }
  81021. };
  81022. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81023. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81024. }
  81025. });
  81026. }
  81027. }
  81028. webVrController_1.attachToPoseControlledCamera(_this);
  81029. // since this is async - sanity check. Is the controller already stored?
  81030. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81031. //add to the controllers array
  81032. _this.controllers.push(webVrController_1);
  81033. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81034. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81035. // So we're overriding setting left & right manually to be sure
  81036. var firstViveWandDetected = false;
  81037. for (var i = 0; i < _this.controllers.length; i++) {
  81038. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81039. if (!firstViveWandDetected) {
  81040. firstViveWandDetected = true;
  81041. _this.controllers[i].hand = "left";
  81042. }
  81043. else {
  81044. _this.controllers[i].hand = "right";
  81045. }
  81046. }
  81047. }
  81048. //did we find enough controllers? Great! let the developer know.
  81049. if (_this.controllers.length >= 2) {
  81050. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81051. }
  81052. }
  81053. }
  81054. });
  81055. };
  81056. return WebVRFreeCamera;
  81057. }(BABYLON.FreeCamera));
  81058. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81059. })(BABYLON || (BABYLON = {}));
  81060. //# sourceMappingURL=babylon.webVRCamera.js.map
  81061. var BABYLON;
  81062. (function (BABYLON) {
  81063. // We're mainly based on the logic defined into the FreeCamera code
  81064. /**
  81065. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81066. * being tilted forward or back and left or right.
  81067. */
  81068. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81069. __extends(DeviceOrientationCamera, _super);
  81070. /**
  81071. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81072. * @param name The name of the camera
  81073. * @param position The start position camera
  81074. * @param scene The scene the camera belongs to
  81075. */
  81076. function DeviceOrientationCamera(name, position, scene) {
  81077. var _this = _super.call(this, name, position, scene) || this;
  81078. _this._quaternionCache = new BABYLON.Quaternion();
  81079. _this.inputs.addDeviceOrientation();
  81080. return _this;
  81081. }
  81082. /**
  81083. * Gets the current instance class name ("DeviceOrientationCamera").
  81084. * This helps avoiding instanceof at run time.
  81085. * @returns the class name
  81086. */
  81087. DeviceOrientationCamera.prototype.getClassName = function () {
  81088. return "DeviceOrientationCamera";
  81089. };
  81090. /**
  81091. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81092. */
  81093. DeviceOrientationCamera.prototype._checkInputs = function () {
  81094. _super.prototype._checkInputs.call(this);
  81095. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81096. if (this._initialQuaternion) {
  81097. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81098. }
  81099. };
  81100. /**
  81101. * Reset the camera to its default orientation on the specified axis only.
  81102. * @param axis The axis to reset
  81103. */
  81104. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81105. var _this = this;
  81106. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81107. //can only work if this camera has a rotation quaternion already.
  81108. if (!this.rotationQuaternion)
  81109. return;
  81110. if (!this._initialQuaternion) {
  81111. this._initialQuaternion = new BABYLON.Quaternion();
  81112. }
  81113. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81114. ['x', 'y', 'z'].forEach(function (axisName) {
  81115. if (!axis[axisName]) {
  81116. _this._initialQuaternion[axisName] = 0;
  81117. }
  81118. else {
  81119. _this._initialQuaternion[axisName] *= -1;
  81120. }
  81121. });
  81122. this._initialQuaternion.normalize();
  81123. //force rotation update
  81124. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81125. };
  81126. return DeviceOrientationCamera;
  81127. }(BABYLON.FreeCamera));
  81128. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81129. })(BABYLON || (BABYLON = {}));
  81130. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81131. var BABYLON;
  81132. (function (BABYLON) {
  81133. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81134. __extends(VRDeviceOrientationFreeCamera, _super);
  81135. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81136. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81137. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81138. var _this = _super.call(this, name, position, scene) || this;
  81139. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81140. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81141. return _this;
  81142. }
  81143. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81144. return "VRDeviceOrientationFreeCamera";
  81145. };
  81146. return VRDeviceOrientationFreeCamera;
  81147. }(BABYLON.DeviceOrientationCamera));
  81148. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81149. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81150. __extends(VRDeviceOrientationGamepadCamera, _super);
  81151. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81152. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81153. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81154. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81155. _this.inputs.addGamepad();
  81156. return _this;
  81157. }
  81158. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81159. return "VRDeviceOrientationGamepadCamera";
  81160. };
  81161. return VRDeviceOrientationGamepadCamera;
  81162. }(VRDeviceOrientationFreeCamera));
  81163. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81164. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81165. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81166. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81167. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81168. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81169. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81170. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81171. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81172. _this.inputs.addVRDeviceOrientation();
  81173. return _this;
  81174. }
  81175. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81176. return "VRDeviceOrientationArcRotateCamera";
  81177. };
  81178. return VRDeviceOrientationArcRotateCamera;
  81179. }(BABYLON.ArcRotateCamera));
  81180. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81181. })(BABYLON || (BABYLON = {}));
  81182. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81183. var BABYLON;
  81184. (function (BABYLON) {
  81185. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81186. __extends(AnaglyphFreeCamera, _super);
  81187. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81188. var _this = _super.call(this, name, position, scene) || this;
  81189. _this.interaxialDistance = interaxialDistance;
  81190. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81191. return _this;
  81192. }
  81193. AnaglyphFreeCamera.prototype.getClassName = function () {
  81194. return "AnaglyphFreeCamera";
  81195. };
  81196. return AnaglyphFreeCamera;
  81197. }(BABYLON.FreeCamera));
  81198. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81199. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81200. __extends(AnaglyphArcRotateCamera, _super);
  81201. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81202. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81203. _this.interaxialDistance = interaxialDistance;
  81204. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81205. return _this;
  81206. }
  81207. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81208. return "AnaglyphArcRotateCamera";
  81209. };
  81210. return AnaglyphArcRotateCamera;
  81211. }(BABYLON.ArcRotateCamera));
  81212. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81213. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81214. __extends(AnaglyphGamepadCamera, _super);
  81215. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81216. var _this = _super.call(this, name, position, scene) || this;
  81217. _this.interaxialDistance = interaxialDistance;
  81218. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81219. return _this;
  81220. }
  81221. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81222. return "AnaglyphGamepadCamera";
  81223. };
  81224. return AnaglyphGamepadCamera;
  81225. }(BABYLON.GamepadCamera));
  81226. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81227. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81228. __extends(AnaglyphUniversalCamera, _super);
  81229. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81230. var _this = _super.call(this, name, position, scene) || this;
  81231. _this.interaxialDistance = interaxialDistance;
  81232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81233. return _this;
  81234. }
  81235. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81236. return "AnaglyphUniversalCamera";
  81237. };
  81238. return AnaglyphUniversalCamera;
  81239. }(BABYLON.UniversalCamera));
  81240. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81241. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81242. __extends(StereoscopicFreeCamera, _super);
  81243. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81244. var _this = _super.call(this, name, position, scene) || this;
  81245. _this.interaxialDistance = interaxialDistance;
  81246. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81247. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81248. return _this;
  81249. }
  81250. StereoscopicFreeCamera.prototype.getClassName = function () {
  81251. return "StereoscopicFreeCamera";
  81252. };
  81253. return StereoscopicFreeCamera;
  81254. }(BABYLON.FreeCamera));
  81255. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81256. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81257. __extends(StereoscopicArcRotateCamera, _super);
  81258. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81259. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81260. _this.interaxialDistance = interaxialDistance;
  81261. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81262. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81263. return _this;
  81264. }
  81265. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81266. return "StereoscopicArcRotateCamera";
  81267. };
  81268. return StereoscopicArcRotateCamera;
  81269. }(BABYLON.ArcRotateCamera));
  81270. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81271. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81272. __extends(StereoscopicGamepadCamera, _super);
  81273. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81274. var _this = _super.call(this, name, position, scene) || this;
  81275. _this.interaxialDistance = interaxialDistance;
  81276. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81277. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81278. return _this;
  81279. }
  81280. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81281. return "StereoscopicGamepadCamera";
  81282. };
  81283. return StereoscopicGamepadCamera;
  81284. }(BABYLON.GamepadCamera));
  81285. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81286. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81287. __extends(StereoscopicUniversalCamera, _super);
  81288. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81289. var _this = _super.call(this, name, position, scene) || this;
  81290. _this.interaxialDistance = interaxialDistance;
  81291. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81292. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81293. return _this;
  81294. }
  81295. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81296. return "StereoscopicUniversalCamera";
  81297. };
  81298. return StereoscopicUniversalCamera;
  81299. }(BABYLON.UniversalCamera));
  81300. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81301. })(BABYLON || (BABYLON = {}));
  81302. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81303. var BABYLON;
  81304. (function (BABYLON) {
  81305. var VRExperienceHelperGazer = /** @class */ (function () {
  81306. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81307. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81308. this.scene = scene;
  81309. this._pointerDownOnMeshAsked = false;
  81310. this._isActionableMesh = false;
  81311. this._teleportationRequestInitiated = false;
  81312. this._teleportationBackRequestInitiated = false;
  81313. this._dpadPressed = true;
  81314. this._activePointer = false;
  81315. this._id = VRExperienceHelperGazer._idCounter++;
  81316. // Gaze tracker
  81317. if (!gazeTrackerToClone) {
  81318. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81319. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81320. this._gazeTracker.isPickable = false;
  81321. this._gazeTracker.isVisible = false;
  81322. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81323. targetMat.specularColor = BABYLON.Color3.Black();
  81324. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81325. targetMat.backFaceCulling = false;
  81326. this._gazeTracker.material = targetMat;
  81327. }
  81328. else {
  81329. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81330. }
  81331. }
  81332. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81333. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81334. };
  81335. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81336. this._pointerDownOnMeshAsked = true;
  81337. if (this._currentMeshSelected && this._currentHit) {
  81338. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81339. }
  81340. };
  81341. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81342. if (this._currentMeshSelected && this._currentHit) {
  81343. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81344. }
  81345. this._pointerDownOnMeshAsked = false;
  81346. };
  81347. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81348. this._activePointer = true;
  81349. };
  81350. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81351. this._activePointer = false;
  81352. };
  81353. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81354. };
  81355. VRExperienceHelperGazer.prototype.dispose = function () {
  81356. this._interactionsEnabled = false;
  81357. this._teleportationEnabled = false;
  81358. };
  81359. VRExperienceHelperGazer._idCounter = 0;
  81360. return VRExperienceHelperGazer;
  81361. }());
  81362. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81363. __extends(VRExperienceHelperControllerGazer, _super);
  81364. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81365. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81366. _this.webVRController = webVRController;
  81367. // Laser pointer
  81368. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81369. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81370. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81371. laserPointerMaterial.alpha = 0.6;
  81372. _this._laserPointer.material = laserPointerMaterial;
  81373. _this._laserPointer.rotation.x = Math.PI / 2;
  81374. _this._laserPointer.position.z = -0.5;
  81375. _this._laserPointer.isVisible = false;
  81376. if (!webVRController.mesh) {
  81377. // Create an empty mesh that is used prior to loading the high quality model
  81378. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81379. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81380. preloadPointerPose.rotation.x = -0.7;
  81381. preloadMesh.addChild(preloadPointerPose);
  81382. webVRController.attachToMesh(preloadMesh);
  81383. }
  81384. _this._setLaserPointerParent(webVRController.mesh);
  81385. return _this;
  81386. }
  81387. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81388. return this.webVRController.getForwardRay(length);
  81389. };
  81390. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81391. _super.prototype._activatePointer.call(this);
  81392. this._laserPointer.isVisible = true;
  81393. };
  81394. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81395. _super.prototype._deactivatePointer.call(this);
  81396. this._laserPointer.isVisible = false;
  81397. };
  81398. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81399. this._laserPointer.material.emissiveColor = color;
  81400. };
  81401. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81402. var makeNotPick = function (root) {
  81403. root.name += " laserPointer";
  81404. root.getChildMeshes().forEach(function (c) {
  81405. makeNotPick(c);
  81406. });
  81407. };
  81408. makeNotPick(mesh);
  81409. var childMeshes = mesh.getChildMeshes();
  81410. this.webVRController._pointingPoseNode = null;
  81411. for (var i = 0; i < childMeshes.length; i++) {
  81412. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81413. mesh = childMeshes[i];
  81414. this.webVRController._pointingPoseNode = mesh;
  81415. break;
  81416. }
  81417. }
  81418. this._laserPointer.parent = mesh;
  81419. };
  81420. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81421. this._laserPointer.scaling.y = distance;
  81422. this._laserPointer.position.z = -distance / 2;
  81423. };
  81424. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81425. _super.prototype.dispose.call(this);
  81426. this._laserPointer.dispose();
  81427. };
  81428. return VRExperienceHelperControllerGazer;
  81429. }(VRExperienceHelperGazer));
  81430. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81431. __extends(VRExperienceHelperCameraGazer, _super);
  81432. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81433. var _this = _super.call(this, scene) || this;
  81434. _this.getCamera = getCamera;
  81435. return _this;
  81436. }
  81437. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81438. var camera = this.getCamera();
  81439. if (camera) {
  81440. return camera.getForwardRay(length);
  81441. }
  81442. else {
  81443. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81444. }
  81445. };
  81446. return VRExperienceHelperCameraGazer;
  81447. }(VRExperienceHelperGazer));
  81448. /**
  81449. * Helps to quickly add VR support to an existing scene.
  81450. * See http://doc.babylonjs.com/how_to/webvr_helper
  81451. */
  81452. var VRExperienceHelper = /** @class */ (function () {
  81453. /**
  81454. * Instantiates a VRExperienceHelper.
  81455. * Helps to quickly add VR support to an existing scene.
  81456. * @param scene The scene the VRExperienceHelper belongs to.
  81457. * @param webVROptions Options to modify the vr experience helper's behavior.
  81458. */
  81459. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81460. if (webVROptions === void 0) { webVROptions = {}; }
  81461. var _this = this;
  81462. this.webVROptions = webVROptions;
  81463. // Can the system support WebVR, even if a headset isn't plugged in?
  81464. this._webVRsupported = false;
  81465. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81466. this._webVRready = false;
  81467. // Are we waiting for the requestPresent callback to complete?
  81468. this._webVRrequesting = false;
  81469. // Are we presenting to the headset right now?
  81470. this._webVRpresenting = false;
  81471. // Are we presenting in the fullscreen fallback?
  81472. this._fullscreenVRpresenting = false;
  81473. /**
  81474. * Observable raised when entering VR.
  81475. */
  81476. this.onEnteringVRObservable = new BABYLON.Observable();
  81477. /**
  81478. * Observable raised when exiting VR.
  81479. */
  81480. this.onExitingVRObservable = new BABYLON.Observable();
  81481. /**
  81482. * Observable raised when controller mesh is loaded.
  81483. */
  81484. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81485. this._useCustomVRButton = false;
  81486. this._teleportationRequested = false;
  81487. this._teleportActive = false;
  81488. this._floorMeshesCollection = [];
  81489. this._rotationAllowed = true;
  81490. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81491. this._rotationRightAsked = false;
  81492. this._rotationLeftAsked = false;
  81493. this._isDefaultTeleportationTarget = true;
  81494. this._teleportationFillColor = "#444444";
  81495. this._teleportationBorderColor = "#FFFFFF";
  81496. this._rotationAngle = 0;
  81497. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81498. this._padSensibilityUp = 0.65;
  81499. this._padSensibilityDown = 0.35;
  81500. this.leftController = null;
  81501. this.rightController = null;
  81502. /**
  81503. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81504. */
  81505. this.onNewMeshSelected = new BABYLON.Observable();
  81506. /**
  81507. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81508. */
  81509. this.onNewMeshPicked = new BABYLON.Observable();
  81510. /**
  81511. * Observable raised before camera teleportation
  81512. */
  81513. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81514. /**
  81515. * Observable raised after camera teleportation
  81516. */
  81517. this.onAfterCameraTeleport = new BABYLON.Observable();
  81518. /**
  81519. * Observable raised when current selected mesh gets unselected
  81520. */
  81521. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81522. /**
  81523. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81524. */
  81525. this.teleportationEnabled = true;
  81526. this._teleportationInitialized = false;
  81527. this._interactionsEnabled = false;
  81528. this._interactionsRequested = false;
  81529. this._displayGaze = true;
  81530. this._displayLaserPointer = true;
  81531. this._onResize = function () {
  81532. _this.moveButtonToBottomRight();
  81533. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81534. _this.exitVR();
  81535. }
  81536. };
  81537. this._onFullscreenChange = function () {
  81538. if (document.fullscreen !== undefined) {
  81539. _this._fullscreenVRpresenting = document.fullscreen;
  81540. }
  81541. else if (document.mozFullScreen !== undefined) {
  81542. _this._fullscreenVRpresenting = document.mozFullScreen;
  81543. }
  81544. else if (document.webkitIsFullScreen !== undefined) {
  81545. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81546. }
  81547. else if (document.msIsFullScreen !== undefined) {
  81548. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81549. }
  81550. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81551. _this.exitVR();
  81552. if (!_this._useCustomVRButton) {
  81553. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81554. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81555. }
  81556. }
  81557. };
  81558. this.beforeRender = function () {
  81559. if (_this.leftController && _this.leftController._activePointer) {
  81560. _this._castRayAndSelectObject(_this.leftController);
  81561. }
  81562. if (_this.rightController && _this.rightController._activePointer) {
  81563. _this._castRayAndSelectObject(_this.rightController);
  81564. }
  81565. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81566. _this._castRayAndSelectObject(_this._cameraGazer);
  81567. }
  81568. else {
  81569. _this._cameraGazer._gazeTracker.isVisible = false;
  81570. }
  81571. };
  81572. this._onNewGamepadConnected = function (gamepad) {
  81573. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81574. if (gamepad.leftStick) {
  81575. gamepad.onleftstickchanged(function (stickValues) {
  81576. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81577. // Listening to classic/xbox gamepad only if no VR controller is active
  81578. if ((!_this.leftController && !_this.rightController) ||
  81579. ((_this.leftController && !_this.leftController._activePointer) &&
  81580. (_this.rightController && !_this.rightController._activePointer))) {
  81581. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81582. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81583. }
  81584. }
  81585. });
  81586. }
  81587. if (gamepad.rightStick) {
  81588. gamepad.onrightstickchanged(function (stickValues) {
  81589. if (_this._teleportationInitialized) {
  81590. _this._checkRotate(stickValues, _this._cameraGazer);
  81591. }
  81592. });
  81593. }
  81594. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81595. gamepad.onbuttondown(function (buttonPressed) {
  81596. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81597. _this._cameraGazer._selectionPointerDown();
  81598. }
  81599. });
  81600. gamepad.onbuttonup(function (buttonPressed) {
  81601. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81602. _this._cameraGazer._selectionPointerUp();
  81603. }
  81604. });
  81605. }
  81606. }
  81607. else {
  81608. var webVRController = gamepad;
  81609. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81610. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81611. _this.rightController = controller;
  81612. }
  81613. else {
  81614. _this.leftController = controller;
  81615. }
  81616. _this._tryEnableInteractionOnController(controller);
  81617. }
  81618. };
  81619. // 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
  81620. this._tryEnableInteractionOnController = function (controller) {
  81621. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81622. _this._enableInteractionOnController(controller);
  81623. }
  81624. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81625. _this._enableTeleportationOnController(controller);
  81626. }
  81627. };
  81628. this._onNewGamepadDisconnected = function (gamepad) {
  81629. if (gamepad instanceof BABYLON.WebVRController) {
  81630. if (gamepad.hand === "left" && _this.leftController != null) {
  81631. _this.leftController.dispose();
  81632. _this.leftController = null;
  81633. }
  81634. if (gamepad.hand === "right" && _this.rightController != null) {
  81635. _this.rightController.dispose();
  81636. _this.rightController = null;
  81637. }
  81638. }
  81639. };
  81640. this._workingVector = BABYLON.Vector3.Zero();
  81641. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81642. this._workingMatrix = BABYLON.Matrix.Identity();
  81643. this._scene = scene;
  81644. this._canvas = scene.getEngine().getRenderingCanvas();
  81645. // Parse options
  81646. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81647. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81648. }
  81649. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81650. webVROptions.createDeviceOrientationCamera = true;
  81651. }
  81652. if (webVROptions.defaultHeight === undefined) {
  81653. webVROptions.defaultHeight = 1.7;
  81654. }
  81655. if (webVROptions.useCustomVRButton) {
  81656. this._useCustomVRButton = true;
  81657. if (webVROptions.customVRButton) {
  81658. this._btnVR = webVROptions.customVRButton;
  81659. }
  81660. }
  81661. if (webVROptions.rayLength) {
  81662. this._rayLength = webVROptions.rayLength;
  81663. }
  81664. this._defaultHeight = webVROptions.defaultHeight;
  81665. if (webVROptions.positionScale) {
  81666. this._rayLength *= webVROptions.positionScale;
  81667. this._defaultHeight *= webVROptions.positionScale;
  81668. }
  81669. // Set position
  81670. if (this._scene.activeCamera) {
  81671. this._position = this._scene.activeCamera.position.clone();
  81672. }
  81673. else {
  81674. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81675. }
  81676. // Set non-vr camera
  81677. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81678. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81679. // Copy data from existing camera
  81680. if (this._scene.activeCamera) {
  81681. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81682. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81683. // Set rotation from previous camera
  81684. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81685. var targetCamera = this._scene.activeCamera;
  81686. if (targetCamera.rotationQuaternion) {
  81687. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81688. }
  81689. else {
  81690. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81691. }
  81692. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81693. }
  81694. }
  81695. this._scene.activeCamera = this._deviceOrientationCamera;
  81696. if (this._canvas) {
  81697. this._scene.activeCamera.attachControl(this._canvas);
  81698. }
  81699. }
  81700. else {
  81701. this._existingCamera = this._scene.activeCamera;
  81702. }
  81703. // Create VR cameras
  81704. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81705. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81706. }
  81707. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81708. this._webVRCamera.useStandingMatrix();
  81709. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81710. // Create default button
  81711. if (!this._useCustomVRButton) {
  81712. this._btnVR = document.createElement("BUTTON");
  81713. this._btnVR.className = "babylonVRicon";
  81714. this._btnVR.id = "babylonVRiconbtn";
  81715. this._btnVR.title = "Click to switch to VR";
  81716. 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) }";
  81717. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81718. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81719. // css += ".babylonVRicon.vrdisplaysupported { }";
  81720. // css += ".babylonVRicon.vrdisplayready { }";
  81721. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81722. var style = document.createElement('style');
  81723. style.appendChild(document.createTextNode(css));
  81724. document.getElementsByTagName('head')[0].appendChild(style);
  81725. this.moveButtonToBottomRight();
  81726. }
  81727. // VR button click event
  81728. if (this._btnVR) {
  81729. this._btnVR.addEventListener("click", function () {
  81730. if (!_this.isInVRMode) {
  81731. _this.enterVR();
  81732. }
  81733. else {
  81734. _this.exitVR();
  81735. }
  81736. });
  81737. }
  81738. // Window events
  81739. window.addEventListener("resize", this._onResize);
  81740. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81741. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81742. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81743. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81744. // Display vr button when headset is connected
  81745. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81746. this.displayVRButton();
  81747. }
  81748. else {
  81749. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81750. if (e.vrDisplay) {
  81751. _this.displayVRButton();
  81752. }
  81753. });
  81754. }
  81755. // Exiting VR mode using 'ESC' key on desktop
  81756. this._onKeyDown = function (event) {
  81757. if (event.keyCode === 27 && _this.isInVRMode) {
  81758. _this.exitVR();
  81759. }
  81760. };
  81761. document.addEventListener("keydown", this._onKeyDown);
  81762. // Exiting VR mode double tapping the touch screen
  81763. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81764. if (_this.isInVRMode) {
  81765. _this.exitVR();
  81766. if (_this._fullscreenVRpresenting) {
  81767. _this._scene.getEngine().switchFullscreen(true);
  81768. }
  81769. }
  81770. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81771. // Listen for WebVR display changes
  81772. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81773. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81774. this._onVRRequestPresentStart = function () {
  81775. _this._webVRrequesting = true;
  81776. _this.updateButtonVisibility();
  81777. };
  81778. this._onVRRequestPresentComplete = function (success) {
  81779. _this._webVRrequesting = false;
  81780. _this.updateButtonVisibility();
  81781. };
  81782. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81783. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81784. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81785. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81786. scene.onDisposeObservable.add(function () {
  81787. _this.dispose();
  81788. });
  81789. // Gamepad connection events
  81790. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81791. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81792. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81793. this.updateButtonVisibility();
  81794. //create easing functions
  81795. this._circleEase = new BABYLON.CircleEase();
  81796. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81797. }
  81798. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81799. /** Return this.onEnteringVRObservable
  81800. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81801. */
  81802. get: function () {
  81803. return this.onEnteringVRObservable;
  81804. },
  81805. enumerable: true,
  81806. configurable: true
  81807. });
  81808. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81809. /** Return this.onExitingVRObservable
  81810. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81811. */
  81812. get: function () {
  81813. return this.onExitingVRObservable;
  81814. },
  81815. enumerable: true,
  81816. configurable: true
  81817. });
  81818. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81819. /** Return this.onControllerMeshLoadedObservable
  81820. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81821. */
  81822. get: function () {
  81823. return this.onControllerMeshLoadedObservable;
  81824. },
  81825. enumerable: true,
  81826. configurable: true
  81827. });
  81828. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81829. /**
  81830. * The mesh used to display where the user is going to teleport.
  81831. */
  81832. get: function () {
  81833. return this._teleportationTarget;
  81834. },
  81835. /**
  81836. * Sets the mesh to be used to display where the user is going to teleport.
  81837. */
  81838. set: function (value) {
  81839. if (value) {
  81840. value.name = "teleportationTarget";
  81841. this._isDefaultTeleportationTarget = false;
  81842. this._teleportationTarget = value;
  81843. }
  81844. },
  81845. enumerable: true,
  81846. configurable: true
  81847. });
  81848. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81849. /**
  81850. * The mesh used to display where the user is selecting,
  81851. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81852. * See http://doc.babylonjs.com/resources/baking_transformations
  81853. */
  81854. get: function () {
  81855. return this._cameraGazer._gazeTracker;
  81856. },
  81857. set: function (value) {
  81858. if (value) {
  81859. this._cameraGazer._gazeTracker = value;
  81860. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81861. this._cameraGazer._gazeTracker.isPickable = false;
  81862. this._cameraGazer._gazeTracker.isVisible = false;
  81863. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81864. if (this.leftController) {
  81865. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81866. }
  81867. if (this.rightController) {
  81868. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81869. }
  81870. }
  81871. },
  81872. enumerable: true,
  81873. configurable: true
  81874. });
  81875. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81876. /**
  81877. * If the ray of the gaze should be displayed.
  81878. */
  81879. get: function () {
  81880. return this._displayGaze;
  81881. },
  81882. /**
  81883. * Sets if the ray of the gaze should be displayed.
  81884. */
  81885. set: function (value) {
  81886. this._displayGaze = value;
  81887. if (!value) {
  81888. this._cameraGazer._gazeTracker.isVisible = false;
  81889. if (this.leftController) {
  81890. this.leftController._gazeTracker.isVisible = false;
  81891. }
  81892. if (this.rightController) {
  81893. this.rightController._gazeTracker.isVisible = false;
  81894. }
  81895. }
  81896. },
  81897. enumerable: true,
  81898. configurable: true
  81899. });
  81900. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81901. /**
  81902. * If the ray of the LaserPointer should be displayed.
  81903. */
  81904. get: function () {
  81905. return this._displayLaserPointer;
  81906. },
  81907. /**
  81908. * Sets if the ray of the LaserPointer should be displayed.
  81909. */
  81910. set: function (value) {
  81911. this._displayLaserPointer = value;
  81912. if (!value) {
  81913. if (this.rightController) {
  81914. this.rightController._deactivatePointer();
  81915. this.rightController._gazeTracker.isVisible = false;
  81916. }
  81917. if (this.leftController) {
  81918. this.leftController._deactivatePointer();
  81919. this.leftController._gazeTracker.isVisible = false;
  81920. }
  81921. }
  81922. else {
  81923. if (this.rightController) {
  81924. this.rightController._activatePointer();
  81925. }
  81926. else if (this.leftController) {
  81927. this.leftController._activatePointer();
  81928. }
  81929. }
  81930. },
  81931. enumerable: true,
  81932. configurable: true
  81933. });
  81934. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81935. /**
  81936. * The deviceOrientationCamera used as the camera when not in VR.
  81937. */
  81938. get: function () {
  81939. return this._deviceOrientationCamera;
  81940. },
  81941. enumerable: true,
  81942. configurable: true
  81943. });
  81944. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81945. /**
  81946. * Based on the current WebVR support, returns the current VR camera used.
  81947. */
  81948. get: function () {
  81949. if (this._webVRready) {
  81950. return this._webVRCamera;
  81951. }
  81952. else {
  81953. return this._scene.activeCamera;
  81954. }
  81955. },
  81956. enumerable: true,
  81957. configurable: true
  81958. });
  81959. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81960. /**
  81961. * The webVRCamera which is used when in VR.
  81962. */
  81963. get: function () {
  81964. return this._webVRCamera;
  81965. },
  81966. enumerable: true,
  81967. configurable: true
  81968. });
  81969. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81970. /**
  81971. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81972. */
  81973. get: function () {
  81974. return this._vrDeviceOrientationCamera;
  81975. },
  81976. enumerable: true,
  81977. configurable: true
  81978. });
  81979. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81980. get: function () {
  81981. var result = this._cameraGazer._teleportationRequestInitiated
  81982. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81983. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81984. return result;
  81985. },
  81986. enumerable: true,
  81987. configurable: true
  81988. });
  81989. // Raised when one of the controller has loaded successfully its associated default mesh
  81990. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81991. if (this.leftController && this.leftController.webVRController == webVRController) {
  81992. if (webVRController.mesh) {
  81993. this.leftController._setLaserPointerParent(webVRController.mesh);
  81994. }
  81995. }
  81996. if (this.rightController && this.rightController.webVRController == webVRController) {
  81997. if (webVRController.mesh) {
  81998. this.rightController._setLaserPointerParent(webVRController.mesh);
  81999. }
  82000. }
  82001. try {
  82002. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82003. }
  82004. catch (err) {
  82005. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82006. }
  82007. };
  82008. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82009. /**
  82010. * Gets a value indicating if we are currently in VR mode.
  82011. */
  82012. get: function () {
  82013. return this._webVRpresenting || this._fullscreenVRpresenting;
  82014. },
  82015. enumerable: true,
  82016. configurable: true
  82017. });
  82018. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82019. var vrDisplay = this._scene.getEngine().getVRDevice();
  82020. if (vrDisplay) {
  82021. var wasPresenting = this._webVRpresenting;
  82022. // A VR display is connected
  82023. this._webVRpresenting = vrDisplay.isPresenting;
  82024. if (wasPresenting && !this._webVRpresenting)
  82025. this.exitVR();
  82026. }
  82027. else {
  82028. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82029. }
  82030. this.updateButtonVisibility();
  82031. };
  82032. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82033. this._webVRsupported = eventArgs.vrSupported;
  82034. this._webVRready = !!eventArgs.vrDisplay;
  82035. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82036. this.updateButtonVisibility();
  82037. };
  82038. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82039. if (this._canvas && !this._useCustomVRButton) {
  82040. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82041. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82042. }
  82043. };
  82044. VRExperienceHelper.prototype.displayVRButton = function () {
  82045. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82046. document.body.appendChild(this._btnVR);
  82047. this._btnVRDisplayed = true;
  82048. }
  82049. };
  82050. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82051. if (!this._btnVR || this._useCustomVRButton) {
  82052. return;
  82053. }
  82054. this._btnVR.className = "babylonVRicon";
  82055. if (this.isInVRMode) {
  82056. this._btnVR.className += " vrdisplaypresenting";
  82057. }
  82058. else {
  82059. if (this._webVRready)
  82060. this._btnVR.className += " vrdisplayready";
  82061. if (this._webVRsupported)
  82062. this._btnVR.className += " vrdisplaysupported";
  82063. if (this._webVRrequesting)
  82064. this._btnVR.className += " vrdisplayrequesting";
  82065. }
  82066. };
  82067. /**
  82068. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82069. * Otherwise, will use the fullscreen API.
  82070. */
  82071. VRExperienceHelper.prototype.enterVR = function () {
  82072. if (this.onEnteringVRObservable) {
  82073. try {
  82074. this.onEnteringVRObservable.notifyObservers(this);
  82075. }
  82076. catch (err) {
  82077. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82078. }
  82079. }
  82080. if (this._scene.activeCamera) {
  82081. this._position = this._scene.activeCamera.position.clone();
  82082. // make sure that we return to the last active camera
  82083. this._existingCamera = this._scene.activeCamera;
  82084. }
  82085. if (this._webVRrequesting)
  82086. return;
  82087. // If WebVR is supported and a headset is connected
  82088. if (this._webVRready) {
  82089. if (!this._webVRpresenting) {
  82090. this._webVRCamera.position = this._position;
  82091. this._scene.activeCamera = this._webVRCamera;
  82092. }
  82093. }
  82094. else if (this._vrDeviceOrientationCamera) {
  82095. this._vrDeviceOrientationCamera.position = this._position;
  82096. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82097. this._scene.getEngine().switchFullscreen(true);
  82098. this.updateButtonVisibility();
  82099. }
  82100. if (this._scene.activeCamera && this._canvas) {
  82101. this._scene.activeCamera.attachControl(this._canvas);
  82102. }
  82103. if (this._interactionsEnabled) {
  82104. this._scene.registerBeforeRender(this.beforeRender);
  82105. }
  82106. };
  82107. /**
  82108. * Attempt to exit VR, or fullscreen.
  82109. */
  82110. VRExperienceHelper.prototype.exitVR = function () {
  82111. if (this.onExitingVRObservable) {
  82112. try {
  82113. this.onExitingVRObservable.notifyObservers(this);
  82114. }
  82115. catch (err) {
  82116. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82117. }
  82118. }
  82119. if (this._webVRpresenting) {
  82120. this._scene.getEngine().disableVR();
  82121. }
  82122. if (this._scene.activeCamera) {
  82123. this._position = this._scene.activeCamera.position.clone();
  82124. }
  82125. if (this._deviceOrientationCamera) {
  82126. this._deviceOrientationCamera.position = this._position;
  82127. this._scene.activeCamera = this._deviceOrientationCamera;
  82128. if (this._canvas) {
  82129. this._scene.activeCamera.attachControl(this._canvas);
  82130. }
  82131. }
  82132. else if (this._existingCamera) {
  82133. this._existingCamera.position = this._position;
  82134. this._scene.activeCamera = this._existingCamera;
  82135. }
  82136. this.updateButtonVisibility();
  82137. if (this._interactionsEnabled) {
  82138. this._scene.unregisterBeforeRender(this.beforeRender);
  82139. }
  82140. };
  82141. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82142. /**
  82143. * The position of the vr experience helper.
  82144. */
  82145. get: function () {
  82146. return this._position;
  82147. },
  82148. /**
  82149. * Sets the position of the vr experience helper.
  82150. */
  82151. set: function (value) {
  82152. this._position = value;
  82153. if (this._scene.activeCamera) {
  82154. this._scene.activeCamera.position = value;
  82155. }
  82156. },
  82157. enumerable: true,
  82158. configurable: true
  82159. });
  82160. /**
  82161. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82162. */
  82163. VRExperienceHelper.prototype.enableInteractions = function () {
  82164. var _this = this;
  82165. if (!this._interactionsEnabled) {
  82166. this._interactionsRequested = true;
  82167. if (this.leftController) {
  82168. this._enableInteractionOnController(this.leftController);
  82169. }
  82170. if (this.rightController) {
  82171. this._enableInteractionOnController(this.rightController);
  82172. }
  82173. this.raySelectionPredicate = function (mesh) {
  82174. return mesh.isVisible;
  82175. };
  82176. this.meshSelectionPredicate = function (mesh) {
  82177. return true;
  82178. };
  82179. this._raySelectionPredicate = function (mesh) {
  82180. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82181. && mesh.name.indexOf("teleportationTarget") === -1
  82182. && mesh.name.indexOf("torusTeleportation") === -1
  82183. && mesh.name.indexOf("laserPointer") === -1)) {
  82184. return _this.raySelectionPredicate(mesh);
  82185. }
  82186. return false;
  82187. };
  82188. this._interactionsEnabled = true;
  82189. }
  82190. };
  82191. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82192. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82193. if (this._floorMeshesCollection[i].id === mesh.id) {
  82194. return true;
  82195. }
  82196. }
  82197. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82198. return true;
  82199. }
  82200. return false;
  82201. };
  82202. /**
  82203. * Adds a floor mesh to be used for teleportation.
  82204. * @param floorMesh the mesh to be used for teleportation.
  82205. */
  82206. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82207. if (!this._floorMeshesCollection) {
  82208. return;
  82209. }
  82210. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82211. return;
  82212. }
  82213. this._floorMeshesCollection.push(floorMesh);
  82214. };
  82215. /**
  82216. * Removes a floor mesh from being used for teleportation.
  82217. * @param floorMesh the mesh to be removed.
  82218. */
  82219. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82220. if (!this._floorMeshesCollection) {
  82221. return;
  82222. }
  82223. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82224. if (meshIndex !== -1) {
  82225. this._floorMeshesCollection.splice(meshIndex, 1);
  82226. }
  82227. };
  82228. /**
  82229. * Enables interactions and teleportation using the VR controllers and gaze.
  82230. * @param vrTeleportationOptions options to modify teleportation behavior.
  82231. */
  82232. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82233. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82234. if (!this._teleportationInitialized) {
  82235. this._teleportationRequested = true;
  82236. this.enableInteractions();
  82237. if (vrTeleportationOptions.floorMeshName) {
  82238. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82239. }
  82240. if (vrTeleportationOptions.floorMeshes) {
  82241. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82242. }
  82243. if (this.leftController != null) {
  82244. this._enableTeleportationOnController(this.leftController);
  82245. }
  82246. if (this.rightController != null) {
  82247. this._enableTeleportationOnController(this.rightController);
  82248. }
  82249. // Creates an image processing post process for the vignette not relying
  82250. // on the main scene configuration for image processing to reduce setup and spaces
  82251. // (gamma/linear) conflicts.
  82252. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82253. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82254. imageProcessingConfiguration.vignetteEnabled = true;
  82255. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82256. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82257. this._teleportationInitialized = true;
  82258. if (this._isDefaultTeleportationTarget) {
  82259. this._createTeleportationCircles();
  82260. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82261. }
  82262. }
  82263. };
  82264. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82265. var _this = this;
  82266. var controllerMesh = controller.webVRController.mesh;
  82267. if (controllerMesh) {
  82268. controller._interactionsEnabled = true;
  82269. controller._activatePointer();
  82270. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82271. // Enabling / disabling laserPointer
  82272. if (_this._displayLaserPointer && stateObject.value === 1) {
  82273. if (controller._activePointer) {
  82274. controller._deactivatePointer();
  82275. }
  82276. else {
  82277. controller._activatePointer();
  82278. }
  82279. if (_this.displayGaze) {
  82280. controller._gazeTracker.isVisible = controller._activePointer;
  82281. }
  82282. }
  82283. });
  82284. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82285. if (!controller._pointerDownOnMeshAsked) {
  82286. if (stateObject.value > _this._padSensibilityUp) {
  82287. controller._selectionPointerDown();
  82288. }
  82289. }
  82290. else if (stateObject.value < _this._padSensibilityDown) {
  82291. controller._selectionPointerUp();
  82292. }
  82293. });
  82294. }
  82295. };
  82296. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82297. // Dont teleport if another gaze already requested teleportation
  82298. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82299. return;
  82300. }
  82301. if (!gazer._teleportationRequestInitiated) {
  82302. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82303. gazer._activatePointer();
  82304. gazer._teleportationRequestInitiated = true;
  82305. }
  82306. }
  82307. else {
  82308. // Listening to the proper controller values changes to confirm teleportation
  82309. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82310. if (this._teleportActive) {
  82311. this._teleportCamera(this._haloCenter);
  82312. }
  82313. gazer._teleportationRequestInitiated = false;
  82314. }
  82315. }
  82316. };
  82317. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82318. // Only rotate when user is not currently selecting a teleportation location
  82319. if (gazer._teleportationRequestInitiated) {
  82320. return;
  82321. }
  82322. if (!this._rotationLeftAsked) {
  82323. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82324. this._rotationLeftAsked = true;
  82325. if (this._rotationAllowed) {
  82326. this._rotateCamera(false);
  82327. }
  82328. }
  82329. }
  82330. else {
  82331. if (stateObject.x > -this._padSensibilityDown) {
  82332. this._rotationLeftAsked = false;
  82333. }
  82334. }
  82335. if (!this._rotationRightAsked) {
  82336. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82337. this._rotationRightAsked = true;
  82338. if (this._rotationAllowed) {
  82339. this._rotateCamera(true);
  82340. }
  82341. }
  82342. }
  82343. else {
  82344. if (stateObject.x < this._padSensibilityDown) {
  82345. this._rotationRightAsked = false;
  82346. }
  82347. }
  82348. };
  82349. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82350. // Only teleport backwards when user is not currently selecting a teleportation location
  82351. if (gazer._teleportationRequestInitiated) {
  82352. return;
  82353. }
  82354. // Teleport backwards
  82355. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82356. if (!gazer._teleportationBackRequestInitiated) {
  82357. if (!this.currentVRCamera) {
  82358. return;
  82359. }
  82360. // Get rotation and position of the current camera
  82361. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82362. var position = this.currentVRCamera.position;
  82363. // If the camera has device position, use that instead
  82364. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82365. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82366. position = this.currentVRCamera.devicePosition;
  82367. }
  82368. // Get matrix with only the y rotation of the device rotation
  82369. rotation.toEulerAnglesToRef(this._workingVector);
  82370. this._workingVector.z = 0;
  82371. this._workingVector.x = 0;
  82372. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82373. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82374. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82375. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82376. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82377. var ray = new BABYLON.Ray(position, this._workingVector);
  82378. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82379. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82380. this._teleportCamera(hit.pickedPoint);
  82381. }
  82382. gazer._teleportationBackRequestInitiated = true;
  82383. }
  82384. }
  82385. else {
  82386. gazer._teleportationBackRequestInitiated = false;
  82387. }
  82388. };
  82389. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82390. var _this = this;
  82391. var controllerMesh = controller.webVRController.mesh;
  82392. if (controllerMesh) {
  82393. if (!controller._interactionsEnabled) {
  82394. this._enableInteractionOnController(controller);
  82395. }
  82396. controller._interactionsEnabled = true;
  82397. controller._teleportationEnabled = true;
  82398. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82399. controller._dpadPressed = false;
  82400. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82401. controller._dpadPressed = stateObject.pressed;
  82402. if (!controller._dpadPressed) {
  82403. _this._rotationLeftAsked = false;
  82404. _this._rotationRightAsked = false;
  82405. controller._teleportationBackRequestInitiated = false;
  82406. }
  82407. });
  82408. }
  82409. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82410. if (_this.teleportationEnabled) {
  82411. _this._checkTeleportBackwards(stateObject, controller);
  82412. _this._checkTeleportWithRay(stateObject, controller);
  82413. }
  82414. _this._checkRotate(stateObject, controller);
  82415. });
  82416. }
  82417. };
  82418. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82419. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82420. this._teleportationTarget.isPickable = false;
  82421. var length = 512;
  82422. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82423. dynamicTexture.hasAlpha = true;
  82424. var context = dynamicTexture.getContext();
  82425. var centerX = length / 2;
  82426. var centerY = length / 2;
  82427. var radius = 200;
  82428. context.beginPath();
  82429. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82430. context.fillStyle = this._teleportationFillColor;
  82431. context.fill();
  82432. context.lineWidth = 10;
  82433. context.strokeStyle = this._teleportationBorderColor;
  82434. context.stroke();
  82435. context.closePath();
  82436. dynamicTexture.update();
  82437. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82438. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82439. this._teleportationTarget.material = teleportationCircleMaterial;
  82440. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82441. torus.isPickable = false;
  82442. torus.parent = this._teleportationTarget;
  82443. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82444. var keys = [];
  82445. keys.push({
  82446. frame: 0,
  82447. value: 0
  82448. });
  82449. keys.push({
  82450. frame: 30,
  82451. value: 0.4
  82452. });
  82453. keys.push({
  82454. frame: 60,
  82455. value: 0
  82456. });
  82457. animationInnerCircle.setKeys(keys);
  82458. var easingFunction = new BABYLON.SineEase();
  82459. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82460. animationInnerCircle.setEasingFunction(easingFunction);
  82461. torus.animations = [];
  82462. torus.animations.push(animationInnerCircle);
  82463. this._scene.beginAnimation(torus, 0, 60, true);
  82464. this._hideTeleportationTarget();
  82465. };
  82466. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82467. this._teleportActive = true;
  82468. if (this._teleportationInitialized) {
  82469. this._teleportationTarget.isVisible = true;
  82470. if (this._isDefaultTeleportationTarget) {
  82471. this._teleportationTarget.getChildren()[0].isVisible = true;
  82472. }
  82473. }
  82474. };
  82475. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82476. this._teleportActive = false;
  82477. if (this._teleportationInitialized) {
  82478. this._teleportationTarget.isVisible = false;
  82479. if (this._isDefaultTeleportationTarget) {
  82480. this._teleportationTarget.getChildren()[0].isVisible = false;
  82481. }
  82482. }
  82483. };
  82484. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82485. var _this = this;
  82486. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82487. return;
  82488. }
  82489. if (right) {
  82490. this._rotationAngle++;
  82491. }
  82492. else {
  82493. this._rotationAngle--;
  82494. }
  82495. this.currentVRCamera.animations = [];
  82496. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82497. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82498. var animationRotationKeys = [];
  82499. animationRotationKeys.push({
  82500. frame: 0,
  82501. value: this.currentVRCamera.rotationQuaternion
  82502. });
  82503. animationRotationKeys.push({
  82504. frame: 6,
  82505. value: target
  82506. });
  82507. animationRotation.setKeys(animationRotationKeys);
  82508. animationRotation.setEasingFunction(this._circleEase);
  82509. this.currentVRCamera.animations.push(animationRotation);
  82510. this._postProcessMove.animations = [];
  82511. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82512. var vignetteWeightKeys = [];
  82513. vignetteWeightKeys.push({
  82514. frame: 0,
  82515. value: 0
  82516. });
  82517. vignetteWeightKeys.push({
  82518. frame: 3,
  82519. value: 4
  82520. });
  82521. vignetteWeightKeys.push({
  82522. frame: 6,
  82523. value: 0
  82524. });
  82525. animationPP.setKeys(vignetteWeightKeys);
  82526. animationPP.setEasingFunction(this._circleEase);
  82527. this._postProcessMove.animations.push(animationPP);
  82528. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82529. var vignetteStretchKeys = [];
  82530. vignetteStretchKeys.push({
  82531. frame: 0,
  82532. value: 0
  82533. });
  82534. vignetteStretchKeys.push({
  82535. frame: 3,
  82536. value: 10
  82537. });
  82538. vignetteStretchKeys.push({
  82539. frame: 6,
  82540. value: 0
  82541. });
  82542. animationPP2.setKeys(vignetteStretchKeys);
  82543. animationPP2.setEasingFunction(this._circleEase);
  82544. this._postProcessMove.animations.push(animationPP2);
  82545. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82546. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82547. this._postProcessMove.samples = 4;
  82548. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82549. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82550. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82551. });
  82552. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82553. };
  82554. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82555. if (hit.pickedPoint) {
  82556. if (gazer._teleportationRequestInitiated) {
  82557. this._displayTeleportationTarget();
  82558. this._haloCenter.copyFrom(hit.pickedPoint);
  82559. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82560. }
  82561. var pickNormal = hit.getNormal(true, false);
  82562. if (pickNormal) {
  82563. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82564. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82565. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82566. }
  82567. this._teleportationTarget.position.y += 0.1;
  82568. }
  82569. };
  82570. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82571. var _this = this;
  82572. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82573. return;
  82574. }
  82575. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82576. // offset of the headset from the anchor.
  82577. if (this.webVRCamera.leftCamera) {
  82578. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82579. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82580. location.subtractToRef(this._workingVector, this._workingVector);
  82581. }
  82582. else {
  82583. this._workingVector.copyFrom(location);
  82584. }
  82585. // Add height to account for user's height offset
  82586. if (this.isInVRMode) {
  82587. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82588. }
  82589. else {
  82590. this._workingVector.y += this._defaultHeight;
  82591. }
  82592. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82593. // Create animation from the camera's position to the new location
  82594. this.currentVRCamera.animations = [];
  82595. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82596. var animationCameraTeleportationKeys = [{
  82597. frame: 0,
  82598. value: this.currentVRCamera.position
  82599. },
  82600. {
  82601. frame: 11,
  82602. value: this._workingVector
  82603. }
  82604. ];
  82605. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82606. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82607. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82608. this._postProcessMove.animations = [];
  82609. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82610. var vignetteWeightKeys = [];
  82611. vignetteWeightKeys.push({
  82612. frame: 0,
  82613. value: 0
  82614. });
  82615. vignetteWeightKeys.push({
  82616. frame: 5,
  82617. value: 8
  82618. });
  82619. vignetteWeightKeys.push({
  82620. frame: 11,
  82621. value: 0
  82622. });
  82623. animationPP.setKeys(vignetteWeightKeys);
  82624. this._postProcessMove.animations.push(animationPP);
  82625. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82626. var vignetteStretchKeys = [];
  82627. vignetteStretchKeys.push({
  82628. frame: 0,
  82629. value: 0
  82630. });
  82631. vignetteStretchKeys.push({
  82632. frame: 5,
  82633. value: 10
  82634. });
  82635. vignetteStretchKeys.push({
  82636. frame: 11,
  82637. value: 0
  82638. });
  82639. animationPP2.setKeys(vignetteStretchKeys);
  82640. this._postProcessMove.animations.push(animationPP2);
  82641. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82642. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82643. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82644. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82645. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82646. });
  82647. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82648. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82649. });
  82650. this._hideTeleportationTarget();
  82651. };
  82652. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82653. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82654. return;
  82655. }
  82656. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82657. // Moving the gazeTracker on the mesh face targetted
  82658. if (hit && hit.pickedPoint) {
  82659. if (this._displayGaze) {
  82660. var multiplier = 1;
  82661. gazer._gazeTracker.isVisible = true;
  82662. if (gazer._isActionableMesh) {
  82663. multiplier = 3;
  82664. }
  82665. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82666. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82667. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82668. var pickNormal = hit.getNormal();
  82669. // To avoid z-fighting
  82670. var deltaFighting = 0.002;
  82671. if (pickNormal) {
  82672. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82673. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82674. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82675. }
  82676. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82677. if (gazer._gazeTracker.position.x < 0) {
  82678. gazer._gazeTracker.position.x += deltaFighting;
  82679. }
  82680. else {
  82681. gazer._gazeTracker.position.x -= deltaFighting;
  82682. }
  82683. if (gazer._gazeTracker.position.y < 0) {
  82684. gazer._gazeTracker.position.y += deltaFighting;
  82685. }
  82686. else {
  82687. gazer._gazeTracker.position.y -= deltaFighting;
  82688. }
  82689. if (gazer._gazeTracker.position.z < 0) {
  82690. gazer._gazeTracker.position.z += deltaFighting;
  82691. }
  82692. else {
  82693. gazer._gazeTracker.position.z -= deltaFighting;
  82694. }
  82695. }
  82696. // Changing the size of the laser pointer based on the distance from the targetted point
  82697. gazer._updatePointerDistance(hit.distance);
  82698. }
  82699. else {
  82700. gazer._gazeTracker.isVisible = false;
  82701. }
  82702. if (hit && hit.pickedMesh) {
  82703. gazer._currentHit = hit;
  82704. if (gazer._pointerDownOnMeshAsked) {
  82705. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82706. }
  82707. // The object selected is the floor, we're in a teleportation scenario
  82708. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82709. // Moving the teleportation area to this targetted point
  82710. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82711. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82712. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82713. }
  82714. gazer._currentMeshSelected = null;
  82715. if (gazer._teleportationRequestInitiated) {
  82716. this._moveTeleportationSelectorTo(hit, gazer);
  82717. }
  82718. return;
  82719. }
  82720. // If not, we're in a selection scenario
  82721. //this._teleportationAllowed = false;
  82722. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82723. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82724. this.onNewMeshPicked.notifyObservers(hit);
  82725. gazer._currentMeshSelected = hit.pickedMesh;
  82726. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82727. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82728. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82729. gazer._isActionableMesh = true;
  82730. }
  82731. else {
  82732. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82733. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82734. gazer._isActionableMesh = false;
  82735. }
  82736. try {
  82737. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82738. }
  82739. catch (err) {
  82740. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82741. }
  82742. }
  82743. else {
  82744. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82745. gazer._currentMeshSelected = null;
  82746. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82747. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82748. }
  82749. }
  82750. }
  82751. else {
  82752. gazer._currentHit = null;
  82753. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82754. gazer._currentMeshSelected = null;
  82755. //this._teleportationAllowed = false;
  82756. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82757. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82758. }
  82759. };
  82760. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82761. if (mesh) {
  82762. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82763. }
  82764. };
  82765. /**
  82766. * Sets the color of the laser ray from the vr controllers.
  82767. * @param color new color for the ray.
  82768. */
  82769. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82770. if (this.leftController) {
  82771. this.leftController._setLaserPointerColor(color);
  82772. }
  82773. if (this.rightController) {
  82774. this.rightController._setLaserPointerColor(color);
  82775. }
  82776. };
  82777. /**
  82778. * Sets the color of the ray from the vr headsets gaze.
  82779. * @param color new color for the ray.
  82780. */
  82781. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82782. if (!this._cameraGazer._gazeTracker.material) {
  82783. return;
  82784. }
  82785. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82786. if (this.leftController) {
  82787. this.leftController._gazeTracker.material.emissiveColor = color;
  82788. }
  82789. if (this.rightController) {
  82790. this.rightController._gazeTracker.material.emissiveColor = color;
  82791. }
  82792. };
  82793. /**
  82794. * Exits VR and disposes of the vr experience helper
  82795. */
  82796. VRExperienceHelper.prototype.dispose = function () {
  82797. if (this.isInVRMode) {
  82798. this.exitVR();
  82799. }
  82800. if (this._postProcessMove) {
  82801. this._postProcessMove.dispose();
  82802. }
  82803. if (this._webVRCamera) {
  82804. this._webVRCamera.dispose();
  82805. }
  82806. if (this._vrDeviceOrientationCamera) {
  82807. this._vrDeviceOrientationCamera.dispose();
  82808. }
  82809. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82810. document.body.removeChild(this._btnVR);
  82811. }
  82812. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82813. this._deviceOrientationCamera.dispose();
  82814. }
  82815. if (this._cameraGazer) {
  82816. this._cameraGazer.dispose();
  82817. }
  82818. if (this.leftController) {
  82819. this.leftController.dispose();
  82820. }
  82821. if (this.rightController) {
  82822. this.rightController.dispose();
  82823. }
  82824. if (this._teleportationTarget) {
  82825. this._teleportationTarget.dispose();
  82826. }
  82827. this._floorMeshesCollection = [];
  82828. document.removeEventListener("keydown", this._onKeyDown);
  82829. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82830. window.removeEventListener("resize", this._onResize);
  82831. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82832. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82833. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82834. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82835. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82836. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82837. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82838. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82839. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82840. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82841. this._scene.unregisterBeforeRender(this.beforeRender);
  82842. };
  82843. /**
  82844. * Gets the name of the VRExperienceHelper class
  82845. * @returns "VRExperienceHelper"
  82846. */
  82847. VRExperienceHelper.prototype.getClassName = function () {
  82848. return "VRExperienceHelper";
  82849. };
  82850. return VRExperienceHelper;
  82851. }());
  82852. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82853. })(BABYLON || (BABYLON = {}));
  82854. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82855. // Mainly based on these 2 articles :
  82856. // 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
  82857. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82858. var BABYLON;
  82859. (function (BABYLON) {
  82860. var JoystickAxis;
  82861. (function (JoystickAxis) {
  82862. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82863. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82864. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82865. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82866. var VirtualJoystick = /** @class */ (function () {
  82867. function VirtualJoystick(leftJoystick) {
  82868. var _this = this;
  82869. if (leftJoystick) {
  82870. this._leftJoystick = true;
  82871. }
  82872. else {
  82873. this._leftJoystick = false;
  82874. }
  82875. VirtualJoystick._globalJoystickIndex++;
  82876. // By default left & right arrow keys are moving the X
  82877. // and up & down keys are moving the Y
  82878. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82879. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82880. this.reverseLeftRight = false;
  82881. this.reverseUpDown = false;
  82882. // collections of pointers
  82883. this._touches = new BABYLON.StringDictionary();
  82884. this.deltaPosition = BABYLON.Vector3.Zero();
  82885. this._joystickSensibility = 25;
  82886. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82887. this._onResize = function (evt) {
  82888. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82889. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82890. if (VirtualJoystick.vjCanvas) {
  82891. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82892. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82893. }
  82894. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82895. };
  82896. // injecting a canvas element on top of the canvas 3D game
  82897. if (!VirtualJoystick.vjCanvas) {
  82898. window.addEventListener("resize", this._onResize, false);
  82899. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82900. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82901. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82902. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82903. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82904. VirtualJoystick.vjCanvas.style.width = "100%";
  82905. VirtualJoystick.vjCanvas.style.height = "100%";
  82906. VirtualJoystick.vjCanvas.style.position = "absolute";
  82907. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82908. VirtualJoystick.vjCanvas.style.top = "0px";
  82909. VirtualJoystick.vjCanvas.style.left = "0px";
  82910. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82911. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82912. // Support for jQuery PEP polyfill
  82913. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82914. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82915. if (!context) {
  82916. throw new Error("Unable to create canvas for virtual joystick");
  82917. }
  82918. VirtualJoystick.vjCanvasContext = context;
  82919. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82920. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82921. document.body.appendChild(VirtualJoystick.vjCanvas);
  82922. }
  82923. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82924. this.pressed = false;
  82925. // default joystick color
  82926. this._joystickColor = "cyan";
  82927. this._joystickPointerID = -1;
  82928. // current joystick position
  82929. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82930. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82931. // origin joystick position
  82932. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82933. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82934. this._onPointerDownHandlerRef = function (evt) {
  82935. _this._onPointerDown(evt);
  82936. };
  82937. this._onPointerMoveHandlerRef = function (evt) {
  82938. _this._onPointerMove(evt);
  82939. };
  82940. this._onPointerUpHandlerRef = function (evt) {
  82941. _this._onPointerUp(evt);
  82942. };
  82943. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82944. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82945. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82946. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82947. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82948. evt.preventDefault(); // Disables system menu
  82949. }, false);
  82950. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82951. }
  82952. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82953. this._joystickSensibility = newJoystickSensibility;
  82954. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82955. };
  82956. VirtualJoystick.prototype._onPointerDown = function (e) {
  82957. var positionOnScreenCondition;
  82958. e.preventDefault();
  82959. if (this._leftJoystick === true) {
  82960. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82961. }
  82962. else {
  82963. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82964. }
  82965. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82966. // First contact will be dedicated to the virtual joystick
  82967. this._joystickPointerID = e.pointerId;
  82968. this._joystickPointerStartPos.x = e.clientX;
  82969. this._joystickPointerStartPos.y = e.clientY;
  82970. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82971. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82972. this._deltaJoystickVector.x = 0;
  82973. this._deltaJoystickVector.y = 0;
  82974. this.pressed = true;
  82975. this._touches.add(e.pointerId.toString(), e);
  82976. }
  82977. else {
  82978. // You can only trigger the action buttons with a joystick declared
  82979. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82980. this._action();
  82981. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82982. }
  82983. }
  82984. };
  82985. VirtualJoystick.prototype._onPointerMove = function (e) {
  82986. // If the current pointer is the one associated to the joystick (first touch contact)
  82987. if (this._joystickPointerID == e.pointerId) {
  82988. this._joystickPointerPos.x = e.clientX;
  82989. this._joystickPointerPos.y = e.clientY;
  82990. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82991. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82992. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82993. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82994. switch (this._axisTargetedByLeftAndRight) {
  82995. case JoystickAxis.X:
  82996. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82997. break;
  82998. case JoystickAxis.Y:
  82999. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83000. break;
  83001. case JoystickAxis.Z:
  83002. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83003. break;
  83004. }
  83005. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83006. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83007. switch (this._axisTargetedByUpAndDown) {
  83008. case JoystickAxis.X:
  83009. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83010. break;
  83011. case JoystickAxis.Y:
  83012. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83013. break;
  83014. case JoystickAxis.Z:
  83015. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83016. break;
  83017. }
  83018. }
  83019. else {
  83020. var data = this._touches.get(e.pointerId.toString());
  83021. if (data) {
  83022. data.x = e.clientX;
  83023. data.y = e.clientY;
  83024. }
  83025. }
  83026. };
  83027. VirtualJoystick.prototype._onPointerUp = function (e) {
  83028. if (this._joystickPointerID == e.pointerId) {
  83029. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83030. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83031. this._joystickPointerID = -1;
  83032. this.pressed = false;
  83033. }
  83034. else {
  83035. var touch = this._touches.get(e.pointerId.toString());
  83036. if (touch) {
  83037. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83038. }
  83039. }
  83040. this._deltaJoystickVector.x = 0;
  83041. this._deltaJoystickVector.y = 0;
  83042. this._touches.remove(e.pointerId.toString());
  83043. };
  83044. /**
  83045. * Change the color of the virtual joystick
  83046. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83047. */
  83048. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83049. this._joystickColor = newColor;
  83050. };
  83051. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83052. this._action = action;
  83053. };
  83054. // Define which axis you'd like to control for left & right
  83055. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83056. switch (axis) {
  83057. case JoystickAxis.X:
  83058. case JoystickAxis.Y:
  83059. case JoystickAxis.Z:
  83060. this._axisTargetedByLeftAndRight = axis;
  83061. break;
  83062. default:
  83063. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83064. break;
  83065. }
  83066. };
  83067. // Define which axis you'd like to control for up & down
  83068. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83069. switch (axis) {
  83070. case JoystickAxis.X:
  83071. case JoystickAxis.Y:
  83072. case JoystickAxis.Z:
  83073. this._axisTargetedByUpAndDown = axis;
  83074. break;
  83075. default:
  83076. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83077. break;
  83078. }
  83079. };
  83080. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83081. var _this = this;
  83082. if (this.pressed) {
  83083. this._touches.forEach(function (key, touch) {
  83084. if (touch.pointerId === _this._joystickPointerID) {
  83085. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83086. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83087. VirtualJoystick.vjCanvasContext.beginPath();
  83088. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83089. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83090. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83091. VirtualJoystick.vjCanvasContext.stroke();
  83092. VirtualJoystick.vjCanvasContext.closePath();
  83093. VirtualJoystick.vjCanvasContext.beginPath();
  83094. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83095. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83096. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83097. VirtualJoystick.vjCanvasContext.stroke();
  83098. VirtualJoystick.vjCanvasContext.closePath();
  83099. VirtualJoystick.vjCanvasContext.beginPath();
  83100. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83101. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83102. VirtualJoystick.vjCanvasContext.stroke();
  83103. VirtualJoystick.vjCanvasContext.closePath();
  83104. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83105. }
  83106. else {
  83107. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83108. VirtualJoystick.vjCanvasContext.beginPath();
  83109. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83110. VirtualJoystick.vjCanvasContext.beginPath();
  83111. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83112. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83113. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83114. VirtualJoystick.vjCanvasContext.stroke();
  83115. VirtualJoystick.vjCanvasContext.closePath();
  83116. touch.prevX = touch.x;
  83117. touch.prevY = touch.y;
  83118. }
  83119. ;
  83120. });
  83121. }
  83122. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83123. };
  83124. VirtualJoystick.prototype.releaseCanvas = function () {
  83125. if (VirtualJoystick.vjCanvas) {
  83126. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83127. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83128. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83129. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83130. window.removeEventListener("resize", this._onResize);
  83131. document.body.removeChild(VirtualJoystick.vjCanvas);
  83132. VirtualJoystick.vjCanvas = null;
  83133. }
  83134. };
  83135. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83136. VirtualJoystick._globalJoystickIndex = 0;
  83137. return VirtualJoystick;
  83138. }());
  83139. BABYLON.VirtualJoystick = VirtualJoystick;
  83140. })(BABYLON || (BABYLON = {}));
  83141. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83142. var BABYLON;
  83143. (function (BABYLON) {
  83144. // We're mainly based on the logic defined into the FreeCamera code
  83145. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83146. __extends(VirtualJoysticksCamera, _super);
  83147. function VirtualJoysticksCamera(name, position, scene) {
  83148. var _this = _super.call(this, name, position, scene) || this;
  83149. _this.inputs.addVirtualJoystick();
  83150. return _this;
  83151. }
  83152. VirtualJoysticksCamera.prototype.getClassName = function () {
  83153. return "VirtualJoysticksCamera";
  83154. };
  83155. return VirtualJoysticksCamera;
  83156. }(BABYLON.FreeCamera));
  83157. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83158. })(BABYLON || (BABYLON = {}));
  83159. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83160. var BABYLON;
  83161. (function (BABYLON) {
  83162. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83163. function FreeCameraVirtualJoystickInput() {
  83164. }
  83165. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83166. return this._leftjoystick;
  83167. };
  83168. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83169. return this._rightjoystick;
  83170. };
  83171. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83172. if (this._leftjoystick) {
  83173. var camera = this.camera;
  83174. var speed = camera._computeLocalCameraSpeed() * 50;
  83175. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83176. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83177. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83178. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83179. if (!this._leftjoystick.pressed) {
  83180. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83181. }
  83182. if (!this._rightjoystick.pressed) {
  83183. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83184. }
  83185. }
  83186. };
  83187. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83188. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83189. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83190. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83191. this._leftjoystick.setJoystickSensibility(0.15);
  83192. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83193. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83194. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83195. this._rightjoystick.reverseUpDown = true;
  83196. this._rightjoystick.setJoystickSensibility(0.05);
  83197. this._rightjoystick.setJoystickColor("yellow");
  83198. };
  83199. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83200. this._leftjoystick.releaseCanvas();
  83201. this._rightjoystick.releaseCanvas();
  83202. };
  83203. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83204. return "FreeCameraVirtualJoystickInput";
  83205. };
  83206. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83207. return "virtualJoystick";
  83208. };
  83209. return FreeCameraVirtualJoystickInput;
  83210. }());
  83211. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83212. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83213. })(BABYLON || (BABYLON = {}));
  83214. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83215. var BABYLON;
  83216. (function (BABYLON) {
  83217. var SimplificationSettings = /** @class */ (function () {
  83218. function SimplificationSettings(quality, distance, optimizeMesh) {
  83219. this.quality = quality;
  83220. this.distance = distance;
  83221. this.optimizeMesh = optimizeMesh;
  83222. }
  83223. return SimplificationSettings;
  83224. }());
  83225. BABYLON.SimplificationSettings = SimplificationSettings;
  83226. var SimplificationQueue = /** @class */ (function () {
  83227. function SimplificationQueue() {
  83228. this.running = false;
  83229. this._simplificationArray = [];
  83230. }
  83231. SimplificationQueue.prototype.addTask = function (task) {
  83232. this._simplificationArray.push(task);
  83233. };
  83234. SimplificationQueue.prototype.executeNext = function () {
  83235. var task = this._simplificationArray.pop();
  83236. if (task) {
  83237. this.running = true;
  83238. this.runSimplification(task);
  83239. }
  83240. else {
  83241. this.running = false;
  83242. }
  83243. };
  83244. SimplificationQueue.prototype.runSimplification = function (task) {
  83245. var _this = this;
  83246. if (task.parallelProcessing) {
  83247. //parallel simplifier
  83248. task.settings.forEach(function (setting) {
  83249. var simplifier = _this.getSimplifier(task);
  83250. simplifier.simplify(setting, function (newMesh) {
  83251. task.mesh.addLODLevel(setting.distance, newMesh);
  83252. newMesh.isVisible = true;
  83253. //check if it is the last
  83254. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83255. //all done, run the success callback.
  83256. task.successCallback();
  83257. }
  83258. _this.executeNext();
  83259. });
  83260. });
  83261. }
  83262. else {
  83263. //single simplifier.
  83264. var simplifier = this.getSimplifier(task);
  83265. var runDecimation = function (setting, callback) {
  83266. simplifier.simplify(setting, function (newMesh) {
  83267. task.mesh.addLODLevel(setting.distance, newMesh);
  83268. newMesh.isVisible = true;
  83269. //run the next quality level
  83270. callback();
  83271. });
  83272. };
  83273. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83274. runDecimation(task.settings[loop.index], function () {
  83275. loop.executeNext();
  83276. });
  83277. }, function () {
  83278. //execution ended, run the success callback.
  83279. if (task.successCallback) {
  83280. task.successCallback();
  83281. }
  83282. _this.executeNext();
  83283. });
  83284. }
  83285. };
  83286. SimplificationQueue.prototype.getSimplifier = function (task) {
  83287. switch (task.simplificationType) {
  83288. case SimplificationType.QUADRATIC:
  83289. default:
  83290. return new QuadraticErrorSimplification(task.mesh);
  83291. }
  83292. };
  83293. return SimplificationQueue;
  83294. }());
  83295. BABYLON.SimplificationQueue = SimplificationQueue;
  83296. /**
  83297. * The implemented types of simplification.
  83298. * At the moment only Quadratic Error Decimation is implemented.
  83299. */
  83300. var SimplificationType;
  83301. (function (SimplificationType) {
  83302. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83303. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83304. var DecimationTriangle = /** @class */ (function () {
  83305. function DecimationTriangle(vertices) {
  83306. this.vertices = vertices;
  83307. this.error = new Array(4);
  83308. this.deleted = false;
  83309. this.isDirty = false;
  83310. this.deletePending = false;
  83311. this.borderFactor = 0;
  83312. }
  83313. return DecimationTriangle;
  83314. }());
  83315. BABYLON.DecimationTriangle = DecimationTriangle;
  83316. var DecimationVertex = /** @class */ (function () {
  83317. function DecimationVertex(position, id) {
  83318. this.position = position;
  83319. this.id = id;
  83320. this.isBorder = true;
  83321. this.q = new QuadraticMatrix();
  83322. this.triangleCount = 0;
  83323. this.triangleStart = 0;
  83324. this.originalOffsets = [];
  83325. }
  83326. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83327. this.position.copyFrom(newPosition);
  83328. };
  83329. return DecimationVertex;
  83330. }());
  83331. BABYLON.DecimationVertex = DecimationVertex;
  83332. var QuadraticMatrix = /** @class */ (function () {
  83333. function QuadraticMatrix(data) {
  83334. this.data = new Array(10);
  83335. for (var i = 0; i < 10; ++i) {
  83336. if (data && data[i]) {
  83337. this.data[i] = data[i];
  83338. }
  83339. else {
  83340. this.data[i] = 0;
  83341. }
  83342. }
  83343. }
  83344. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83345. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83346. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83347. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83348. return det;
  83349. };
  83350. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83351. for (var i = 0; i < 10; ++i) {
  83352. this.data[i] += matrix.data[i];
  83353. }
  83354. };
  83355. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83356. for (var i = 0; i < 10; ++i) {
  83357. this.data[i] += data[i];
  83358. }
  83359. };
  83360. QuadraticMatrix.prototype.add = function (matrix) {
  83361. var m = new QuadraticMatrix();
  83362. for (var i = 0; i < 10; ++i) {
  83363. m.data[i] = this.data[i] + matrix.data[i];
  83364. }
  83365. return m;
  83366. };
  83367. QuadraticMatrix.FromData = function (a, b, c, d) {
  83368. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83369. };
  83370. //returning an array to avoid garbage collection
  83371. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83372. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83373. };
  83374. return QuadraticMatrix;
  83375. }());
  83376. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83377. var Reference = /** @class */ (function () {
  83378. function Reference(vertexId, triangleId) {
  83379. this.vertexId = vertexId;
  83380. this.triangleId = triangleId;
  83381. }
  83382. return Reference;
  83383. }());
  83384. BABYLON.Reference = Reference;
  83385. /**
  83386. * An implementation of the Quadratic Error simplification algorithm.
  83387. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83388. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83389. * @author RaananW
  83390. */
  83391. var QuadraticErrorSimplification = /** @class */ (function () {
  83392. function QuadraticErrorSimplification(_mesh) {
  83393. this._mesh = _mesh;
  83394. this.syncIterations = 5000;
  83395. this.aggressiveness = 7;
  83396. this.decimationIterations = 100;
  83397. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83398. }
  83399. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83400. var _this = this;
  83401. this.initDecimatedMesh();
  83402. //iterating through the submeshes array, one after the other.
  83403. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83404. _this.initWithMesh(loop.index, function () {
  83405. _this.runDecimation(settings, loop.index, function () {
  83406. loop.executeNext();
  83407. });
  83408. }, settings.optimizeMesh);
  83409. }, function () {
  83410. setTimeout(function () {
  83411. successCallback(_this._reconstructedMesh);
  83412. }, 0);
  83413. });
  83414. };
  83415. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83416. var _this = this;
  83417. var targetCount = ~~(this.triangles.length * settings.quality);
  83418. var deletedTriangles = 0;
  83419. var triangleCount = this.triangles.length;
  83420. var iterationFunction = function (iteration, callback) {
  83421. setTimeout(function () {
  83422. if (iteration % 5 === 0) {
  83423. _this.updateMesh(iteration === 0);
  83424. }
  83425. for (var i = 0; i < _this.triangles.length; ++i) {
  83426. _this.triangles[i].isDirty = false;
  83427. }
  83428. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83429. var trianglesIterator = function (i) {
  83430. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83431. var t = _this.triangles[tIdx];
  83432. if (!t)
  83433. return;
  83434. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83435. return;
  83436. }
  83437. for (var j = 0; j < 3; ++j) {
  83438. if (t.error[j] < threshold) {
  83439. var deleted0 = [];
  83440. var deleted1 = [];
  83441. var v0 = t.vertices[j];
  83442. var v1 = t.vertices[(j + 1) % 3];
  83443. if (v0.isBorder || v1.isBorder)
  83444. continue;
  83445. var p = BABYLON.Vector3.Zero();
  83446. var n = BABYLON.Vector3.Zero();
  83447. var uv = BABYLON.Vector2.Zero();
  83448. var color = new BABYLON.Color4(0, 0, 0, 1);
  83449. _this.calculateError(v0, v1, p, n, uv, color);
  83450. var delTr = new Array();
  83451. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83452. continue;
  83453. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83454. continue;
  83455. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83456. continue;
  83457. var uniqueArray = new Array();
  83458. delTr.forEach(function (deletedT) {
  83459. if (uniqueArray.indexOf(deletedT) === -1) {
  83460. deletedT.deletePending = true;
  83461. uniqueArray.push(deletedT);
  83462. }
  83463. });
  83464. if (uniqueArray.length % 2 !== 0) {
  83465. continue;
  83466. }
  83467. v0.q = v1.q.add(v0.q);
  83468. v0.updatePosition(p);
  83469. var tStart = _this.references.length;
  83470. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83471. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83472. var tCount = _this.references.length - tStart;
  83473. if (tCount <= v0.triangleCount) {
  83474. if (tCount) {
  83475. for (var c = 0; c < tCount; c++) {
  83476. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83477. }
  83478. }
  83479. }
  83480. else {
  83481. v0.triangleStart = tStart;
  83482. }
  83483. v0.triangleCount = tCount;
  83484. break;
  83485. }
  83486. }
  83487. };
  83488. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83489. }, 0);
  83490. };
  83491. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83492. if (triangleCount - deletedTriangles <= targetCount)
  83493. loop.breakLoop();
  83494. else {
  83495. iterationFunction(loop.index, function () {
  83496. loop.executeNext();
  83497. });
  83498. }
  83499. }, function () {
  83500. setTimeout(function () {
  83501. //reconstruct this part of the mesh
  83502. _this.reconstructMesh(submeshIndex);
  83503. successCallback();
  83504. }, 0);
  83505. });
  83506. };
  83507. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83508. var _this = this;
  83509. this.vertices = [];
  83510. this.triangles = [];
  83511. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83512. var indices = this._mesh.getIndices();
  83513. var submesh = this._mesh.subMeshes[submeshIndex];
  83514. var findInVertices = function (positionToSearch) {
  83515. if (optimizeMesh) {
  83516. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83517. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83518. return _this.vertices[ii];
  83519. }
  83520. }
  83521. }
  83522. return null;
  83523. };
  83524. var vertexReferences = [];
  83525. var vertexInit = function (i) {
  83526. if (!positionData) {
  83527. return;
  83528. }
  83529. var offset = i + submesh.verticesStart;
  83530. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83531. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83532. vertex.originalOffsets.push(offset);
  83533. if (vertex.id === _this.vertices.length) {
  83534. _this.vertices.push(vertex);
  83535. }
  83536. vertexReferences.push(vertex.id);
  83537. };
  83538. //var totalVertices = mesh.getTotalVertices();
  83539. var totalVertices = submesh.verticesCount;
  83540. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83541. var indicesInit = function (i) {
  83542. if (!indices) {
  83543. return;
  83544. }
  83545. var offset = (submesh.indexStart / 3) + i;
  83546. var pos = (offset * 3);
  83547. var i0 = indices[pos + 0];
  83548. var i1 = indices[pos + 1];
  83549. var i2 = indices[pos + 2];
  83550. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83551. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83552. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83553. var triangle = new DecimationTriangle([v0, v1, v2]);
  83554. triangle.originalOffset = pos;
  83555. _this.triangles.push(triangle);
  83556. };
  83557. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83558. _this.init(callback);
  83559. });
  83560. });
  83561. };
  83562. QuadraticErrorSimplification.prototype.init = function (callback) {
  83563. var _this = this;
  83564. var triangleInit1 = function (i) {
  83565. var t = _this.triangles[i];
  83566. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83567. for (var j = 0; j < 3; j++) {
  83568. 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))));
  83569. }
  83570. };
  83571. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83572. var triangleInit2 = function (i) {
  83573. var t = _this.triangles[i];
  83574. for (var j = 0; j < 3; ++j) {
  83575. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83576. }
  83577. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83578. };
  83579. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83580. callback();
  83581. });
  83582. });
  83583. };
  83584. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83585. var newTriangles = [];
  83586. var i;
  83587. for (i = 0; i < this.vertices.length; ++i) {
  83588. this.vertices[i].triangleCount = 0;
  83589. }
  83590. var t;
  83591. var j;
  83592. for (i = 0; i < this.triangles.length; ++i) {
  83593. if (!this.triangles[i].deleted) {
  83594. t = this.triangles[i];
  83595. for (j = 0; j < 3; ++j) {
  83596. t.vertices[j].triangleCount = 1;
  83597. }
  83598. newTriangles.push(t);
  83599. }
  83600. }
  83601. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83602. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83603. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83604. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83605. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83606. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83607. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83608. var vertexCount = 0;
  83609. for (i = 0; i < this.vertices.length; ++i) {
  83610. var vertex = this.vertices[i];
  83611. vertex.id = vertexCount;
  83612. if (vertex.triangleCount) {
  83613. vertex.originalOffsets.forEach(function (originalOffset) {
  83614. if (!normalData) {
  83615. return;
  83616. }
  83617. newPositionData.push(vertex.position.x);
  83618. newPositionData.push(vertex.position.y);
  83619. newPositionData.push(vertex.position.z);
  83620. newNormalData.push(normalData[originalOffset * 3]);
  83621. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83622. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83623. if (uvs && uvs.length) {
  83624. newUVsData.push(uvs[(originalOffset * 2)]);
  83625. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83626. }
  83627. else if (colorsData && colorsData.length) {
  83628. newColorsData.push(colorsData[(originalOffset * 4)]);
  83629. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83630. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83631. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83632. }
  83633. ++vertexCount;
  83634. });
  83635. }
  83636. }
  83637. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83638. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83639. var submeshesArray = this._reconstructedMesh.subMeshes;
  83640. this._reconstructedMesh.subMeshes = [];
  83641. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83642. var originalIndices = this._mesh.getIndices();
  83643. for (i = 0; i < newTriangles.length; ++i) {
  83644. t = newTriangles[i]; //now get the new referencing point for each vertex
  83645. [0, 1, 2].forEach(function (idx) {
  83646. var id = originalIndices[t.originalOffset + idx];
  83647. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83648. if (offset < 0)
  83649. offset = 0;
  83650. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83651. });
  83652. }
  83653. //overwriting the old vertex buffers and indices.
  83654. this._reconstructedMesh.setIndices(newIndicesArray);
  83655. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83656. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83657. if (newUVsData.length > 0)
  83658. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83659. if (newColorsData.length > 0)
  83660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83661. //create submesh
  83662. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83663. if (submeshIndex > 0) {
  83664. this._reconstructedMesh.subMeshes = [];
  83665. submeshesArray.forEach(function (submesh) {
  83666. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83667. });
  83668. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83669. }
  83670. };
  83671. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83672. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83673. this._reconstructedMesh.material = this._mesh.material;
  83674. this._reconstructedMesh.parent = this._mesh.parent;
  83675. this._reconstructedMesh.isVisible = false;
  83676. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83677. };
  83678. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83679. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83680. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83681. if (t.deleted)
  83682. continue;
  83683. var s = this.references[vertex1.triangleStart + i].vertexId;
  83684. var v1 = t.vertices[(s + 1) % 3];
  83685. var v2 = t.vertices[(s + 2) % 3];
  83686. if ((v1 === vertex2 || v2 === vertex2)) {
  83687. deletedArray[i] = true;
  83688. delTr.push(t);
  83689. continue;
  83690. }
  83691. var d1 = v1.position.subtract(point);
  83692. d1 = d1.normalize();
  83693. var d2 = v2.position.subtract(point);
  83694. d2 = d2.normalize();
  83695. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83696. return true;
  83697. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83698. deletedArray[i] = false;
  83699. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83700. return true;
  83701. }
  83702. return false;
  83703. };
  83704. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83705. var newDeleted = deletedTriangles;
  83706. for (var i = 0; i < vertex.triangleCount; ++i) {
  83707. var ref = this.references[vertex.triangleStart + i];
  83708. var t = this.triangles[ref.triangleId];
  83709. if (t.deleted)
  83710. continue;
  83711. if (deletedArray[i] && t.deletePending) {
  83712. t.deleted = true;
  83713. newDeleted++;
  83714. continue;
  83715. }
  83716. t.vertices[ref.vertexId] = origVertex;
  83717. t.isDirty = true;
  83718. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83719. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83720. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83721. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83722. this.references.push(ref);
  83723. }
  83724. return newDeleted;
  83725. };
  83726. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83727. for (var i = 0; i < this.vertices.length; ++i) {
  83728. var vCount = [];
  83729. var vId = [];
  83730. var v = this.vertices[i];
  83731. var j;
  83732. for (j = 0; j < v.triangleCount; ++j) {
  83733. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83734. for (var ii = 0; ii < 3; ii++) {
  83735. var ofs = 0;
  83736. var vv = triangle.vertices[ii];
  83737. while (ofs < vCount.length) {
  83738. if (vId[ofs] === vv.id)
  83739. break;
  83740. ++ofs;
  83741. }
  83742. if (ofs === vCount.length) {
  83743. vCount.push(1);
  83744. vId.push(vv.id);
  83745. }
  83746. else {
  83747. vCount[ofs]++;
  83748. }
  83749. }
  83750. }
  83751. for (j = 0; j < vCount.length; ++j) {
  83752. if (vCount[j] === 1) {
  83753. this.vertices[vId[j]].isBorder = true;
  83754. }
  83755. else {
  83756. this.vertices[vId[j]].isBorder = false;
  83757. }
  83758. }
  83759. }
  83760. };
  83761. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83762. if (identifyBorders === void 0) { identifyBorders = false; }
  83763. var i;
  83764. if (!identifyBorders) {
  83765. var newTrianglesVector = [];
  83766. for (i = 0; i < this.triangles.length; ++i) {
  83767. if (!this.triangles[i].deleted) {
  83768. newTrianglesVector.push(this.triangles[i]);
  83769. }
  83770. }
  83771. this.triangles = newTrianglesVector;
  83772. }
  83773. for (i = 0; i < this.vertices.length; ++i) {
  83774. this.vertices[i].triangleCount = 0;
  83775. this.vertices[i].triangleStart = 0;
  83776. }
  83777. var t;
  83778. var j;
  83779. var v;
  83780. for (i = 0; i < this.triangles.length; ++i) {
  83781. t = this.triangles[i];
  83782. for (j = 0; j < 3; ++j) {
  83783. v = t.vertices[j];
  83784. v.triangleCount++;
  83785. }
  83786. }
  83787. var tStart = 0;
  83788. for (i = 0; i < this.vertices.length; ++i) {
  83789. this.vertices[i].triangleStart = tStart;
  83790. tStart += this.vertices[i].triangleCount;
  83791. this.vertices[i].triangleCount = 0;
  83792. }
  83793. var newReferences = new Array(this.triangles.length * 3);
  83794. for (i = 0; i < this.triangles.length; ++i) {
  83795. t = this.triangles[i];
  83796. for (j = 0; j < 3; ++j) {
  83797. v = t.vertices[j];
  83798. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83799. v.triangleCount++;
  83800. }
  83801. }
  83802. this.references = newReferences;
  83803. if (identifyBorders) {
  83804. this.identifyBorder();
  83805. }
  83806. };
  83807. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83808. var x = point.x;
  83809. var y = point.y;
  83810. var z = point.z;
  83811. 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
  83812. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83813. };
  83814. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83815. var q = vertex1.q.add(vertex2.q);
  83816. var border = vertex1.isBorder && vertex2.isBorder;
  83817. var error = 0;
  83818. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83819. if (qDet !== 0 && !border) {
  83820. if (!pointResult) {
  83821. pointResult = BABYLON.Vector3.Zero();
  83822. }
  83823. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83824. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83825. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83826. error = this.vertexError(q, pointResult);
  83827. }
  83828. else {
  83829. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83830. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83831. var error1 = this.vertexError(q, vertex1.position);
  83832. var error2 = this.vertexError(q, vertex2.position);
  83833. var error3 = this.vertexError(q, p3);
  83834. error = Math.min(error1, error2, error3);
  83835. if (error === error1) {
  83836. if (pointResult) {
  83837. pointResult.copyFrom(vertex1.position);
  83838. }
  83839. }
  83840. else if (error === error2) {
  83841. if (pointResult) {
  83842. pointResult.copyFrom(vertex2.position);
  83843. }
  83844. }
  83845. else {
  83846. if (pointResult) {
  83847. pointResult.copyFrom(p3);
  83848. }
  83849. }
  83850. }
  83851. return error;
  83852. };
  83853. return QuadraticErrorSimplification;
  83854. }());
  83855. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83856. })(BABYLON || (BABYLON = {}));
  83857. //# sourceMappingURL=babylon.meshSimplification.js.map
  83858. var BABYLON;
  83859. (function (BABYLON) {
  83860. var MeshLODLevel = /** @class */ (function () {
  83861. function MeshLODLevel(distance, mesh) {
  83862. this.distance = distance;
  83863. this.mesh = mesh;
  83864. }
  83865. return MeshLODLevel;
  83866. }());
  83867. BABYLON.MeshLODLevel = MeshLODLevel;
  83868. })(BABYLON || (BABYLON = {}));
  83869. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83870. var BABYLON;
  83871. (function (BABYLON) {
  83872. /**
  83873. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83875. */
  83876. var SceneOptimization = /** @class */ (function () {
  83877. /**
  83878. * Creates the SceneOptimization object
  83879. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83880. * @param desc defines the description associated with the optimization
  83881. */
  83882. function SceneOptimization(
  83883. /**
  83884. * Defines the priority of this optimization (0 by default which means first in the list)
  83885. */
  83886. priority) {
  83887. if (priority === void 0) { priority = 0; }
  83888. this.priority = priority;
  83889. }
  83890. /**
  83891. * Gets a string describing the action executed by the current optimization
  83892. * @returns description string
  83893. */
  83894. SceneOptimization.prototype.getDescription = function () {
  83895. return "";
  83896. };
  83897. /**
  83898. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83899. * @param scene defines the current scene where to apply this optimization
  83900. * @param optimizer defines the current optimizer
  83901. * @returns true if everything that can be done was applied
  83902. */
  83903. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83904. return true;
  83905. };
  83906. ;
  83907. return SceneOptimization;
  83908. }());
  83909. BABYLON.SceneOptimization = SceneOptimization;
  83910. /**
  83911. * Defines an optimization used to reduce the size of render target textures
  83912. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83913. */
  83914. var TextureOptimization = /** @class */ (function (_super) {
  83915. __extends(TextureOptimization, _super);
  83916. /**
  83917. * Creates the TextureOptimization object
  83918. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83919. * @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
  83920. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83921. */
  83922. function TextureOptimization(
  83923. /**
  83924. * Defines the priority of this optimization (0 by default which means first in the list)
  83925. */
  83926. priority,
  83927. /**
  83928. * 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
  83929. */
  83930. maximumSize,
  83931. /**
  83932. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83933. */
  83934. step) {
  83935. if (priority === void 0) { priority = 0; }
  83936. if (maximumSize === void 0) { maximumSize = 1024; }
  83937. if (step === void 0) { step = 0.5; }
  83938. var _this = _super.call(this, priority) || this;
  83939. _this.priority = priority;
  83940. _this.maximumSize = maximumSize;
  83941. _this.step = step;
  83942. return _this;
  83943. }
  83944. /**
  83945. * Gets a string describing the action executed by the current optimization
  83946. * @returns description string
  83947. */
  83948. TextureOptimization.prototype.getDescription = function () {
  83949. return "Reducing render target texture size to " + this.maximumSize;
  83950. };
  83951. /**
  83952. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83953. * @param scene defines the current scene where to apply this optimization
  83954. * @param optimizer defines the current optimizer
  83955. * @returns true if everything that can be done was applied
  83956. */
  83957. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83958. var allDone = true;
  83959. for (var index = 0; index < scene.textures.length; index++) {
  83960. var texture = scene.textures[index];
  83961. if (!texture.canRescale || texture.getContext) {
  83962. continue;
  83963. }
  83964. var currentSize = texture.getSize();
  83965. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83966. if (maxDimension > this.maximumSize) {
  83967. texture.scale(this.step);
  83968. allDone = false;
  83969. }
  83970. }
  83971. return allDone;
  83972. };
  83973. return TextureOptimization;
  83974. }(SceneOptimization));
  83975. BABYLON.TextureOptimization = TextureOptimization;
  83976. /**
  83977. * Defines an optimization used to increase or decrease the rendering resolution
  83978. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83979. */
  83980. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83981. __extends(HardwareScalingOptimization, _super);
  83982. /**
  83983. * Creates the HardwareScalingOptimization object
  83984. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83985. * @param maximumScale defines the maximum scale to use (2 by default)
  83986. * @param step defines the step to use between two passes (0.5 by default)
  83987. */
  83988. function HardwareScalingOptimization(
  83989. /**
  83990. * Defines the priority of this optimization (0 by default which means first in the list)
  83991. */
  83992. priority,
  83993. /**
  83994. * Defines the maximum scale to use (2 by default)
  83995. */
  83996. maximumScale,
  83997. /**
  83998. * Defines the step to use between two passes (0.5 by default)
  83999. */
  84000. step) {
  84001. if (priority === void 0) { priority = 0; }
  84002. if (maximumScale === void 0) { maximumScale = 2; }
  84003. if (step === void 0) { step = 0.25; }
  84004. var _this = _super.call(this, priority) || this;
  84005. _this.priority = priority;
  84006. _this.maximumScale = maximumScale;
  84007. _this.step = step;
  84008. _this._currentScale = -1;
  84009. _this._directionOffset = 1;
  84010. return _this;
  84011. }
  84012. /**
  84013. * Gets a string describing the action executed by the current optimization
  84014. * @return description string
  84015. */
  84016. HardwareScalingOptimization.prototype.getDescription = function () {
  84017. return "Setting hardware scaling level to " + this._currentScale;
  84018. };
  84019. /**
  84020. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84021. * @param scene defines the current scene where to apply this optimization
  84022. * @param optimizer defines the current optimizer
  84023. * @returns true if everything that can be done was applied
  84024. */
  84025. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84026. if (this._currentScale === -1) {
  84027. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84028. if (this._currentScale > this.maximumScale) {
  84029. this._directionOffset = -1;
  84030. }
  84031. }
  84032. this._currentScale += this._directionOffset * this.step;
  84033. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84034. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84035. };
  84036. ;
  84037. return HardwareScalingOptimization;
  84038. }(SceneOptimization));
  84039. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84040. /**
  84041. * Defines an optimization used to remove shadows
  84042. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84043. */
  84044. var ShadowsOptimization = /** @class */ (function (_super) {
  84045. __extends(ShadowsOptimization, _super);
  84046. function ShadowsOptimization() {
  84047. return _super !== null && _super.apply(this, arguments) || this;
  84048. }
  84049. /**
  84050. * Gets a string describing the action executed by the current optimization
  84051. * @return description string
  84052. */
  84053. ShadowsOptimization.prototype.getDescription = function () {
  84054. return "Turning shadows on/off";
  84055. };
  84056. /**
  84057. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84058. * @param scene defines the current scene where to apply this optimization
  84059. * @param optimizer defines the current optimizer
  84060. * @returns true if everything that can be done was applied
  84061. */
  84062. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84063. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84064. return true;
  84065. };
  84066. ;
  84067. return ShadowsOptimization;
  84068. }(SceneOptimization));
  84069. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84070. /**
  84071. * Defines an optimization used to turn post-processes off
  84072. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84073. */
  84074. var PostProcessesOptimization = /** @class */ (function (_super) {
  84075. __extends(PostProcessesOptimization, _super);
  84076. function PostProcessesOptimization() {
  84077. return _super !== null && _super.apply(this, arguments) || this;
  84078. }
  84079. /**
  84080. * Gets a string describing the action executed by the current optimization
  84081. * @return description string
  84082. */
  84083. PostProcessesOptimization.prototype.getDescription = function () {
  84084. return "Turning post-processes on/off";
  84085. };
  84086. /**
  84087. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84088. * @param scene defines the current scene where to apply this optimization
  84089. * @param optimizer defines the current optimizer
  84090. * @returns true if everything that can be done was applied
  84091. */
  84092. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84093. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84094. return true;
  84095. };
  84096. ;
  84097. return PostProcessesOptimization;
  84098. }(SceneOptimization));
  84099. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84100. /**
  84101. * Defines an optimization used to turn lens flares off
  84102. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84103. */
  84104. var LensFlaresOptimization = /** @class */ (function (_super) {
  84105. __extends(LensFlaresOptimization, _super);
  84106. function LensFlaresOptimization() {
  84107. return _super !== null && _super.apply(this, arguments) || this;
  84108. }
  84109. /**
  84110. * Gets a string describing the action executed by the current optimization
  84111. * @return description string
  84112. */
  84113. LensFlaresOptimization.prototype.getDescription = function () {
  84114. return "Turning lens flares on/off";
  84115. };
  84116. /**
  84117. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84118. * @param scene defines the current scene where to apply this optimization
  84119. * @param optimizer defines the current optimizer
  84120. * @returns true if everything that can be done was applied
  84121. */
  84122. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84123. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84124. return true;
  84125. };
  84126. ;
  84127. return LensFlaresOptimization;
  84128. }(SceneOptimization));
  84129. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84130. /**
  84131. * Defines an optimization based on user defined callback.
  84132. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84133. */
  84134. var CustomOptimization = /** @class */ (function (_super) {
  84135. __extends(CustomOptimization, _super);
  84136. function CustomOptimization() {
  84137. return _super !== null && _super.apply(this, arguments) || this;
  84138. }
  84139. /**
  84140. * Gets a string describing the action executed by the current optimization
  84141. * @returns description string
  84142. */
  84143. CustomOptimization.prototype.getDescription = function () {
  84144. if (this.onGetDescription) {
  84145. return this.onGetDescription();
  84146. }
  84147. return "Running user defined callback";
  84148. };
  84149. /**
  84150. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84151. * @param scene defines the current scene where to apply this optimization
  84152. * @param optimizer defines the current optimizer
  84153. * @returns true if everything that can be done was applied
  84154. */
  84155. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84156. if (this.onApply) {
  84157. return this.onApply(scene, optimizer);
  84158. }
  84159. return true;
  84160. };
  84161. ;
  84162. return CustomOptimization;
  84163. }(SceneOptimization));
  84164. BABYLON.CustomOptimization = CustomOptimization;
  84165. /**
  84166. * Defines an optimization used to turn particles off
  84167. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84168. */
  84169. var ParticlesOptimization = /** @class */ (function (_super) {
  84170. __extends(ParticlesOptimization, _super);
  84171. function ParticlesOptimization() {
  84172. return _super !== null && _super.apply(this, arguments) || this;
  84173. }
  84174. /**
  84175. * Gets a string describing the action executed by the current optimization
  84176. * @return description string
  84177. */
  84178. ParticlesOptimization.prototype.getDescription = function () {
  84179. return "Turning particles on/off";
  84180. };
  84181. /**
  84182. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84183. * @param scene defines the current scene where to apply this optimization
  84184. * @param optimizer defines the current optimizer
  84185. * @returns true if everything that can be done was applied
  84186. */
  84187. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84188. scene.particlesEnabled = optimizer.isInImprovementMode;
  84189. return true;
  84190. };
  84191. ;
  84192. return ParticlesOptimization;
  84193. }(SceneOptimization));
  84194. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84195. /**
  84196. * Defines an optimization used to turn render targets off
  84197. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84198. */
  84199. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84200. __extends(RenderTargetsOptimization, _super);
  84201. function RenderTargetsOptimization() {
  84202. return _super !== null && _super.apply(this, arguments) || this;
  84203. }
  84204. /**
  84205. * Gets a string describing the action executed by the current optimization
  84206. * @return description string
  84207. */
  84208. RenderTargetsOptimization.prototype.getDescription = function () {
  84209. return "Turning render targets off";
  84210. };
  84211. /**
  84212. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84213. * @param scene defines the current scene where to apply this optimization
  84214. * @param optimizer defines the current optimizer
  84215. * @returns true if everything that can be done was applied
  84216. */
  84217. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84218. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84219. return true;
  84220. };
  84221. ;
  84222. return RenderTargetsOptimization;
  84223. }(SceneOptimization));
  84224. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84225. /**
  84226. * Defines an optimization used to merge meshes with compatible materials
  84227. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84228. */
  84229. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84230. __extends(MergeMeshesOptimization, _super);
  84231. function MergeMeshesOptimization() {
  84232. var _this = _super !== null && _super.apply(this, arguments) || this;
  84233. _this._canBeMerged = function (abstractMesh) {
  84234. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84235. return false;
  84236. }
  84237. var mesh = abstractMesh;
  84238. if (!mesh.isVisible || !mesh.isEnabled()) {
  84239. return false;
  84240. }
  84241. if (mesh.instances.length > 0) {
  84242. return false;
  84243. }
  84244. if (mesh.skeleton || mesh.hasLODLevels) {
  84245. return false;
  84246. }
  84247. if (mesh.parent) {
  84248. return false;
  84249. }
  84250. return true;
  84251. };
  84252. return _this;
  84253. }
  84254. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84255. /**
  84256. * Gets or sets a boolean which defines if optimization octree has to be updated
  84257. */
  84258. get: function () {
  84259. return MergeMeshesOptimization._UpdateSelectionTree;
  84260. },
  84261. /**
  84262. * Gets or sets a boolean which defines if optimization octree has to be updated
  84263. */
  84264. set: function (value) {
  84265. MergeMeshesOptimization._UpdateSelectionTree = value;
  84266. },
  84267. enumerable: true,
  84268. configurable: true
  84269. });
  84270. /**
  84271. * Gets a string describing the action executed by the current optimization
  84272. * @return description string
  84273. */
  84274. MergeMeshesOptimization.prototype.getDescription = function () {
  84275. return "Merging similar meshes together";
  84276. };
  84277. /**
  84278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84279. * @param scene defines the current scene where to apply this optimization
  84280. * @param optimizer defines the current optimizer
  84281. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84282. * @returns true if everything that can be done was applied
  84283. */
  84284. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84285. var globalPool = scene.meshes.slice(0);
  84286. var globalLength = globalPool.length;
  84287. for (var index = 0; index < globalLength; index++) {
  84288. var currentPool = new Array();
  84289. var current = globalPool[index];
  84290. // Checks
  84291. if (!this._canBeMerged(current)) {
  84292. continue;
  84293. }
  84294. currentPool.push(current);
  84295. // Find compatible meshes
  84296. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84297. var otherMesh = globalPool[subIndex];
  84298. if (!this._canBeMerged(otherMesh)) {
  84299. continue;
  84300. }
  84301. if (otherMesh.material !== current.material) {
  84302. continue;
  84303. }
  84304. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84305. continue;
  84306. }
  84307. currentPool.push(otherMesh);
  84308. globalLength--;
  84309. globalPool.splice(subIndex, 1);
  84310. subIndex--;
  84311. }
  84312. if (currentPool.length < 2) {
  84313. continue;
  84314. }
  84315. // Merge meshes
  84316. BABYLON.Mesh.MergeMeshes(currentPool);
  84317. }
  84318. if (updateSelectionTree != undefined) {
  84319. if (updateSelectionTree) {
  84320. scene.createOrUpdateSelectionOctree();
  84321. }
  84322. }
  84323. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84324. scene.createOrUpdateSelectionOctree();
  84325. }
  84326. return true;
  84327. };
  84328. ;
  84329. MergeMeshesOptimization._UpdateSelectionTree = false;
  84330. return MergeMeshesOptimization;
  84331. }(SceneOptimization));
  84332. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84333. /**
  84334. * Defines a list of options used by SceneOptimizer
  84335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84336. */
  84337. var SceneOptimizerOptions = /** @class */ (function () {
  84338. /**
  84339. * Creates a new list of options used by SceneOptimizer
  84340. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84341. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84342. */
  84343. function SceneOptimizerOptions(
  84344. /**
  84345. * Defines the target frame rate to reach (60 by default)
  84346. */
  84347. targetFrameRate,
  84348. /**
  84349. * Defines the interval between two checkes (2000ms by default)
  84350. */
  84351. trackerDuration) {
  84352. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84353. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84354. this.targetFrameRate = targetFrameRate;
  84355. this.trackerDuration = trackerDuration;
  84356. /**
  84357. * Gets the list of optimizations to apply
  84358. */
  84359. this.optimizations = new Array();
  84360. }
  84361. /**
  84362. * Add a new optimization
  84363. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84364. * @returns the current SceneOptimizerOptions
  84365. */
  84366. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84367. this.optimizations.push(optimization);
  84368. return this;
  84369. };
  84370. /**
  84371. * Add a new custom optimization
  84372. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84373. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84374. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84375. * @returns the current SceneOptimizerOptions
  84376. */
  84377. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84378. if (priority === void 0) { priority = 0; }
  84379. var optimization = new CustomOptimization(priority);
  84380. optimization.onApply = onApply;
  84381. optimization.onGetDescription = onGetDescription;
  84382. this.optimizations.push(optimization);
  84383. return this;
  84384. };
  84385. /**
  84386. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84387. * @param targetFrameRate defines the target frame rate (60 by default)
  84388. * @returns a SceneOptimizerOptions object
  84389. */
  84390. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84391. var result = new SceneOptimizerOptions(targetFrameRate);
  84392. var priority = 0;
  84393. result.addOptimization(new MergeMeshesOptimization(priority));
  84394. result.addOptimization(new ShadowsOptimization(priority));
  84395. result.addOptimization(new LensFlaresOptimization(priority));
  84396. // Next priority
  84397. priority++;
  84398. result.addOptimization(new PostProcessesOptimization(priority));
  84399. result.addOptimization(new ParticlesOptimization(priority));
  84400. // Next priority
  84401. priority++;
  84402. result.addOptimization(new TextureOptimization(priority, 1024));
  84403. return result;
  84404. };
  84405. /**
  84406. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84407. * @param targetFrameRate defines the target frame rate (60 by default)
  84408. * @returns a SceneOptimizerOptions object
  84409. */
  84410. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84411. var result = new SceneOptimizerOptions(targetFrameRate);
  84412. var priority = 0;
  84413. result.addOptimization(new MergeMeshesOptimization(priority));
  84414. result.addOptimization(new ShadowsOptimization(priority));
  84415. result.addOptimization(new LensFlaresOptimization(priority));
  84416. // Next priority
  84417. priority++;
  84418. result.addOptimization(new PostProcessesOptimization(priority));
  84419. result.addOptimization(new ParticlesOptimization(priority));
  84420. // Next priority
  84421. priority++;
  84422. result.addOptimization(new TextureOptimization(priority, 512));
  84423. // Next priority
  84424. priority++;
  84425. result.addOptimization(new RenderTargetsOptimization(priority));
  84426. // Next priority
  84427. priority++;
  84428. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84429. return result;
  84430. };
  84431. /**
  84432. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84433. * @param targetFrameRate defines the target frame rate (60 by default)
  84434. * @returns a SceneOptimizerOptions object
  84435. */
  84436. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84437. var result = new SceneOptimizerOptions(targetFrameRate);
  84438. var priority = 0;
  84439. result.addOptimization(new MergeMeshesOptimization(priority));
  84440. result.addOptimization(new ShadowsOptimization(priority));
  84441. result.addOptimization(new LensFlaresOptimization(priority));
  84442. // Next priority
  84443. priority++;
  84444. result.addOptimization(new PostProcessesOptimization(priority));
  84445. result.addOptimization(new ParticlesOptimization(priority));
  84446. // Next priority
  84447. priority++;
  84448. result.addOptimization(new TextureOptimization(priority, 256));
  84449. // Next priority
  84450. priority++;
  84451. result.addOptimization(new RenderTargetsOptimization(priority));
  84452. // Next priority
  84453. priority++;
  84454. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84455. return result;
  84456. };
  84457. return SceneOptimizerOptions;
  84458. }());
  84459. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84460. /**
  84461. * Class used to run optimizations in order to reach a target frame rate
  84462. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84463. */
  84464. var SceneOptimizer = /** @class */ (function () {
  84465. /**
  84466. * Creates a new SceneOptimizer
  84467. * @param scene defines the scene to work on
  84468. * @param options defines the options to use with the SceneOptimizer
  84469. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84470. * @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)
  84471. */
  84472. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84473. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84474. if (improvementMode === void 0) { improvementMode = false; }
  84475. var _this = this;
  84476. this._isRunning = false;
  84477. this._currentPriorityLevel = 0;
  84478. this._targetFrameRate = 60;
  84479. this._trackerDuration = 2000;
  84480. this._currentFrameRate = 0;
  84481. this._improvementMode = false;
  84482. /**
  84483. * Defines an observable called when the optimizer reaches the target frame rate
  84484. */
  84485. this.onSuccessObservable = new BABYLON.Observable();
  84486. /**
  84487. * Defines an observable called when the optimizer enables an optimization
  84488. */
  84489. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84490. /**
  84491. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84492. */
  84493. this.onFailureObservable = new BABYLON.Observable();
  84494. if (!options) {
  84495. this._options = new SceneOptimizerOptions();
  84496. }
  84497. else {
  84498. this._options = options;
  84499. }
  84500. if (this._options.targetFrameRate) {
  84501. this._targetFrameRate = this._options.targetFrameRate;
  84502. }
  84503. if (this._options.trackerDuration) {
  84504. this._trackerDuration = this._options.trackerDuration;
  84505. }
  84506. if (autoGeneratePriorities) {
  84507. var priority = 0;
  84508. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84509. var optim = _a[_i];
  84510. optim.priority = priority++;
  84511. }
  84512. }
  84513. this._improvementMode = improvementMode;
  84514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84515. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84516. _this._sceneDisposeObserver = null;
  84517. _this.dispose();
  84518. });
  84519. }
  84520. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84521. /**
  84522. * Gets a boolean indicating if the optimizer is in improvement mode
  84523. */
  84524. get: function () {
  84525. return this._improvementMode;
  84526. },
  84527. enumerable: true,
  84528. configurable: true
  84529. });
  84530. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84531. /**
  84532. * Gets the current priority level (0 at start)
  84533. */
  84534. get: function () {
  84535. return this._currentPriorityLevel;
  84536. },
  84537. enumerable: true,
  84538. configurable: true
  84539. });
  84540. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84541. /**
  84542. * Gets the current frame rate checked by the SceneOptimizer
  84543. */
  84544. get: function () {
  84545. return this._currentFrameRate;
  84546. },
  84547. enumerable: true,
  84548. configurable: true
  84549. });
  84550. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84551. /**
  84552. * Gets or sets the current target frame rate (60 by default)
  84553. */
  84554. get: function () {
  84555. return this._targetFrameRate;
  84556. },
  84557. /**
  84558. * Gets or sets the current target frame rate (60 by default)
  84559. */
  84560. set: function (value) {
  84561. this._targetFrameRate = value;
  84562. },
  84563. enumerable: true,
  84564. configurable: true
  84565. });
  84566. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84567. /**
  84568. * Gets or sets the current interval between two checks (every 2000ms by default)
  84569. */
  84570. get: function () {
  84571. return this._trackerDuration;
  84572. },
  84573. /**
  84574. * Gets or sets the current interval between two checks (every 2000ms by default)
  84575. */
  84576. set: function (value) {
  84577. this._trackerDuration = value;
  84578. },
  84579. enumerable: true,
  84580. configurable: true
  84581. });
  84582. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84583. /**
  84584. * Gets the list of active optimizations
  84585. */
  84586. get: function () {
  84587. return this._options.optimizations;
  84588. },
  84589. enumerable: true,
  84590. configurable: true
  84591. });
  84592. /**
  84593. * Stops the current optimizer
  84594. */
  84595. SceneOptimizer.prototype.stop = function () {
  84596. this._isRunning = false;
  84597. };
  84598. /**
  84599. * Reset the optimizer to initial step (current priority level = 0)
  84600. */
  84601. SceneOptimizer.prototype.reset = function () {
  84602. this._currentPriorityLevel = 0;
  84603. };
  84604. /**
  84605. * Start the optimizer. By default it will try to reach a specific framerate
  84606. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84607. */
  84608. SceneOptimizer.prototype.start = function () {
  84609. var _this = this;
  84610. if (this._isRunning) {
  84611. return;
  84612. }
  84613. this._isRunning = true;
  84614. // Let's wait for the scene to be ready before running our check
  84615. this._scene.executeWhenReady(function () {
  84616. setTimeout(function () {
  84617. _this._checkCurrentState();
  84618. }, _this._trackerDuration);
  84619. });
  84620. };
  84621. SceneOptimizer.prototype._checkCurrentState = function () {
  84622. var _this = this;
  84623. if (!this._isRunning) {
  84624. return;
  84625. }
  84626. var scene = this._scene;
  84627. var options = this._options;
  84628. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84629. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84630. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84631. this._isRunning = false;
  84632. this.onSuccessObservable.notifyObservers(this);
  84633. return;
  84634. }
  84635. // Apply current level of optimizations
  84636. var allDone = true;
  84637. var noOptimizationApplied = true;
  84638. for (var index = 0; index < options.optimizations.length; index++) {
  84639. var optimization = options.optimizations[index];
  84640. if (optimization.priority === this._currentPriorityLevel) {
  84641. noOptimizationApplied = false;
  84642. allDone = allDone && optimization.apply(scene, this);
  84643. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84644. }
  84645. }
  84646. // If no optimization was applied, this is a failure :(
  84647. if (noOptimizationApplied) {
  84648. this._isRunning = false;
  84649. this.onFailureObservable.notifyObservers(this);
  84650. return;
  84651. }
  84652. // If all optimizations were done, move to next level
  84653. if (allDone) {
  84654. this._currentPriorityLevel++;
  84655. }
  84656. // Let's the system running for a specific amount of time before checking FPS
  84657. scene.executeWhenReady(function () {
  84658. setTimeout(function () {
  84659. _this._checkCurrentState();
  84660. }, _this._trackerDuration);
  84661. });
  84662. };
  84663. /**
  84664. * Release all resources
  84665. */
  84666. SceneOptimizer.prototype.dispose = function () {
  84667. this.stop();
  84668. this.onSuccessObservable.clear();
  84669. this.onFailureObservable.clear();
  84670. this.onNewOptimizationAppliedObservable.clear();
  84671. if (this._sceneDisposeObserver) {
  84672. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84673. }
  84674. };
  84675. /**
  84676. * Helper function to create a SceneOptimizer with one single line of code
  84677. * @param scene defines the scene to work on
  84678. * @param options defines the options to use with the SceneOptimizer
  84679. * @param onSuccess defines a callback to call on success
  84680. * @param onFailure defines a callback to call on failure
  84681. * @returns the new SceneOptimizer object
  84682. */
  84683. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84684. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84685. if (onSuccess) {
  84686. optimizer.onSuccessObservable.add(function () {
  84687. onSuccess();
  84688. });
  84689. }
  84690. if (onFailure) {
  84691. optimizer.onFailureObservable.add(function () {
  84692. onFailure();
  84693. });
  84694. }
  84695. optimizer.start();
  84696. return optimizer;
  84697. };
  84698. return SceneOptimizer;
  84699. }());
  84700. BABYLON.SceneOptimizer = SceneOptimizer;
  84701. })(BABYLON || (BABYLON = {}));
  84702. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84703. var BABYLON;
  84704. (function (BABYLON) {
  84705. var OutlineRenderer = /** @class */ (function () {
  84706. function OutlineRenderer(scene) {
  84707. this.zOffset = 1;
  84708. this._scene = scene;
  84709. }
  84710. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84711. var _this = this;
  84712. if (useOverlay === void 0) { useOverlay = false; }
  84713. var scene = this._scene;
  84714. var engine = this._scene.getEngine();
  84715. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84716. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84717. return;
  84718. }
  84719. var mesh = subMesh.getRenderingMesh();
  84720. var material = subMesh.getMaterial();
  84721. if (!material || !scene.activeCamera) {
  84722. return;
  84723. }
  84724. engine.enableEffect(this._effect);
  84725. // Logarithmic depth
  84726. if (material.useLogarithmicDepth) {
  84727. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84728. }
  84729. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84730. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84731. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84732. // Bones
  84733. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84734. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84735. }
  84736. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84737. // Alpha test
  84738. if (material && material.needAlphaTesting()) {
  84739. var alphaTexture = material.getAlphaTestTexture();
  84740. if (alphaTexture) {
  84741. this._effect.setTexture("diffuseSampler", alphaTexture);
  84742. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84743. }
  84744. }
  84745. engine.setZOffset(-this.zOffset);
  84746. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84747. engine.setZOffset(0);
  84748. };
  84749. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84750. var defines = [];
  84751. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84752. var mesh = subMesh.getMesh();
  84753. var material = subMesh.getMaterial();
  84754. if (material) {
  84755. // Alpha test
  84756. if (material.needAlphaTesting()) {
  84757. defines.push("#define ALPHATEST");
  84758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84759. attribs.push(BABYLON.VertexBuffer.UVKind);
  84760. defines.push("#define UV1");
  84761. }
  84762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84764. defines.push("#define UV2");
  84765. }
  84766. }
  84767. //Logarithmic depth
  84768. if (material.useLogarithmicDepth) {
  84769. defines.push("#define LOGARITHMICDEPTH");
  84770. }
  84771. }
  84772. // Bones
  84773. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84776. if (mesh.numBoneInfluencers > 4) {
  84777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84779. }
  84780. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84781. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84782. }
  84783. else {
  84784. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84785. }
  84786. // Instances
  84787. if (useInstances) {
  84788. defines.push("#define INSTANCES");
  84789. attribs.push("world0");
  84790. attribs.push("world1");
  84791. attribs.push("world2");
  84792. attribs.push("world3");
  84793. }
  84794. // Get correct effect
  84795. var join = defines.join("\n");
  84796. if (this._cachedDefines !== join) {
  84797. this._cachedDefines = join;
  84798. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84799. }
  84800. return this._effect.isReady();
  84801. };
  84802. return OutlineRenderer;
  84803. }());
  84804. BABYLON.OutlineRenderer = OutlineRenderer;
  84805. })(BABYLON || (BABYLON = {}));
  84806. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84807. var BABYLON;
  84808. (function (BABYLON) {
  84809. var FaceAdjacencies = /** @class */ (function () {
  84810. function FaceAdjacencies() {
  84811. this.edges = new Array();
  84812. this.edgesConnectedCount = 0;
  84813. }
  84814. return FaceAdjacencies;
  84815. }());
  84816. var EdgesRenderer = /** @class */ (function () {
  84817. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84818. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84819. if (epsilon === void 0) { epsilon = 0.95; }
  84820. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84821. this.edgesWidthScalerForOrthographic = 1000.0;
  84822. this.edgesWidthScalerForPerspective = 50.0;
  84823. this._linesPositions = new Array();
  84824. this._linesNormals = new Array();
  84825. this._linesIndices = new Array();
  84826. this._buffers = {};
  84827. this._checkVerticesInsteadOfIndices = false;
  84828. this._source = source;
  84829. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84830. this._epsilon = epsilon;
  84831. this._prepareRessources();
  84832. this._generateEdgesLines();
  84833. }
  84834. EdgesRenderer.prototype._prepareRessources = function () {
  84835. if (this._lineShader) {
  84836. return;
  84837. }
  84838. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84839. attributes: ["position", "normal"],
  84840. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84841. });
  84842. this._lineShader.disableDepthWrite = true;
  84843. this._lineShader.backFaceCulling = false;
  84844. };
  84845. EdgesRenderer.prototype._rebuild = function () {
  84846. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84847. if (buffer) {
  84848. buffer._rebuild();
  84849. }
  84850. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84851. if (buffer) {
  84852. buffer._rebuild();
  84853. }
  84854. var scene = this._source.getScene();
  84855. var engine = scene.getEngine();
  84856. this._ib = engine.createIndexBuffer(this._linesIndices);
  84857. };
  84858. EdgesRenderer.prototype.dispose = function () {
  84859. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84860. if (buffer) {
  84861. buffer.dispose();
  84862. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84863. }
  84864. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84865. if (buffer) {
  84866. buffer.dispose();
  84867. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84868. }
  84869. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84870. this._lineShader.dispose();
  84871. };
  84872. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84873. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84874. return 0;
  84875. }
  84876. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84877. return 1;
  84878. }
  84879. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84880. return 2;
  84881. }
  84882. return -1;
  84883. };
  84884. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84885. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84886. return 0;
  84887. }
  84888. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84889. return 1;
  84890. }
  84891. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84892. return 2;
  84893. }
  84894. return -1;
  84895. };
  84896. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84897. var needToCreateLine;
  84898. if (edge === undefined) {
  84899. needToCreateLine = true;
  84900. }
  84901. else {
  84902. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84903. needToCreateLine = dotProduct < this._epsilon;
  84904. }
  84905. if (needToCreateLine) {
  84906. var offset = this._linesPositions.length / 3;
  84907. var normal = p0.subtract(p1);
  84908. normal.normalize();
  84909. // Positions
  84910. this._linesPositions.push(p0.x);
  84911. this._linesPositions.push(p0.y);
  84912. this._linesPositions.push(p0.z);
  84913. this._linesPositions.push(p0.x);
  84914. this._linesPositions.push(p0.y);
  84915. this._linesPositions.push(p0.z);
  84916. this._linesPositions.push(p1.x);
  84917. this._linesPositions.push(p1.y);
  84918. this._linesPositions.push(p1.z);
  84919. this._linesPositions.push(p1.x);
  84920. this._linesPositions.push(p1.y);
  84921. this._linesPositions.push(p1.z);
  84922. // Normals
  84923. this._linesNormals.push(p1.x);
  84924. this._linesNormals.push(p1.y);
  84925. this._linesNormals.push(p1.z);
  84926. this._linesNormals.push(-1);
  84927. this._linesNormals.push(p1.x);
  84928. this._linesNormals.push(p1.y);
  84929. this._linesNormals.push(p1.z);
  84930. this._linesNormals.push(1);
  84931. this._linesNormals.push(p0.x);
  84932. this._linesNormals.push(p0.y);
  84933. this._linesNormals.push(p0.z);
  84934. this._linesNormals.push(-1);
  84935. this._linesNormals.push(p0.x);
  84936. this._linesNormals.push(p0.y);
  84937. this._linesNormals.push(p0.z);
  84938. this._linesNormals.push(1);
  84939. // Indices
  84940. this._linesIndices.push(offset);
  84941. this._linesIndices.push(offset + 1);
  84942. this._linesIndices.push(offset + 2);
  84943. this._linesIndices.push(offset);
  84944. this._linesIndices.push(offset + 2);
  84945. this._linesIndices.push(offset + 3);
  84946. }
  84947. };
  84948. EdgesRenderer.prototype._generateEdgesLines = function () {
  84949. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84950. var indices = this._source.getIndices();
  84951. if (!indices || !positions) {
  84952. return;
  84953. }
  84954. // First let's find adjacencies
  84955. var adjacencies = new Array();
  84956. var faceNormals = new Array();
  84957. var index;
  84958. var faceAdjacencies;
  84959. // Prepare faces
  84960. for (index = 0; index < indices.length; index += 3) {
  84961. faceAdjacencies = new FaceAdjacencies();
  84962. var p0Index = indices[index];
  84963. var p1Index = indices[index + 1];
  84964. var p2Index = indices[index + 2];
  84965. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84966. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84967. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84968. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84969. faceNormal.normalize();
  84970. faceNormals.push(faceNormal);
  84971. adjacencies.push(faceAdjacencies);
  84972. }
  84973. // Scan
  84974. for (index = 0; index < adjacencies.length; index++) {
  84975. faceAdjacencies = adjacencies[index];
  84976. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84977. var otherFaceAdjacencies = adjacencies[otherIndex];
  84978. if (faceAdjacencies.edgesConnectedCount === 3) {
  84979. break;
  84980. }
  84981. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84982. continue;
  84983. }
  84984. var otherP0 = indices[otherIndex * 3];
  84985. var otherP1 = indices[otherIndex * 3 + 1];
  84986. var otherP2 = indices[otherIndex * 3 + 2];
  84987. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84988. var otherEdgeIndex = 0;
  84989. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84990. continue;
  84991. }
  84992. switch (edgeIndex) {
  84993. case 0:
  84994. if (this._checkVerticesInsteadOfIndices) {
  84995. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84996. }
  84997. else {
  84998. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84999. }
  85000. break;
  85001. case 1:
  85002. if (this._checkVerticesInsteadOfIndices) {
  85003. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85004. }
  85005. else {
  85006. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85007. }
  85008. break;
  85009. case 2:
  85010. if (this._checkVerticesInsteadOfIndices) {
  85011. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85012. }
  85013. else {
  85014. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85015. }
  85016. break;
  85017. }
  85018. if (otherEdgeIndex === -1) {
  85019. continue;
  85020. }
  85021. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85022. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85023. faceAdjacencies.edgesConnectedCount++;
  85024. otherFaceAdjacencies.edgesConnectedCount++;
  85025. if (faceAdjacencies.edgesConnectedCount === 3) {
  85026. break;
  85027. }
  85028. }
  85029. }
  85030. }
  85031. // Create lines
  85032. for (index = 0; index < adjacencies.length; index++) {
  85033. // 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
  85034. var current = adjacencies[index];
  85035. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85036. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85037. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85038. }
  85039. // Merge into a single mesh
  85040. var engine = this._source.getScene().getEngine();
  85041. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85042. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85043. this._ib = engine.createIndexBuffer(this._linesIndices);
  85044. this._indicesCount = this._linesIndices.length;
  85045. };
  85046. EdgesRenderer.prototype.render = function () {
  85047. var scene = this._source.getScene();
  85048. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85049. return;
  85050. }
  85051. var engine = scene.getEngine();
  85052. this._lineShader._preBind();
  85053. // VBOs
  85054. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85055. scene.resetCachedMaterial();
  85056. this._lineShader.setColor4("color", this._source.edgesColor);
  85057. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85058. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85059. }
  85060. else {
  85061. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85062. }
  85063. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85064. this._lineShader.bind(this._source.getWorldMatrix());
  85065. // Draw order
  85066. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85067. this._lineShader.unbind();
  85068. engine.setDepthWrite(true);
  85069. };
  85070. return EdgesRenderer;
  85071. }());
  85072. BABYLON.EdgesRenderer = EdgesRenderer;
  85073. })(BABYLON || (BABYLON = {}));
  85074. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85075. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85076. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85077. s = arguments[i];
  85078. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85079. t[p] = s[p];
  85080. }
  85081. return t;
  85082. };
  85083. var BABYLON;
  85084. (function (BABYLON) {
  85085. /**
  85086. * The effect layer Helps adding post process effect blended with the main pass.
  85087. *
  85088. * This can be for instance use to generate glow or higlight effects on the scene.
  85089. *
  85090. * The effect layer class can not be used directly and is intented to inherited from to be
  85091. * customized per effects.
  85092. */
  85093. var EffectLayer = /** @class */ (function () {
  85094. /**
  85095. * Instantiates a new effect Layer and references it in the scene.
  85096. * @param name The name of the layer
  85097. * @param scene The scene to use the layer in
  85098. */
  85099. function EffectLayer(
  85100. /** The Friendly of the effect in the scene */
  85101. name, scene) {
  85102. this.name = name;
  85103. this._vertexBuffers = {};
  85104. this._maxSize = 0;
  85105. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85106. this._shouldRender = true;
  85107. this._postProcesses = [];
  85108. this._textures = [];
  85109. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85110. /**
  85111. * The clear color of the texture used to generate the glow map.
  85112. */
  85113. this.neutralColor = new BABYLON.Color4();
  85114. /**
  85115. * Specifies wether the highlight layer is enabled or not.
  85116. */
  85117. this.isEnabled = true;
  85118. /**
  85119. * An event triggered when the effect layer has been disposed.
  85120. */
  85121. this.onDisposeObservable = new BABYLON.Observable();
  85122. /**
  85123. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85124. */
  85125. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85126. /**
  85127. * An event triggered when the generated texture is being merged in the scene.
  85128. */
  85129. this.onBeforeComposeObservable = new BABYLON.Observable();
  85130. /**
  85131. * An event triggered when the generated texture has been merged in the scene.
  85132. */
  85133. this.onAfterComposeObservable = new BABYLON.Observable();
  85134. /**
  85135. * An event triggered when the efffect layer changes its size.
  85136. */
  85137. this.onSizeChangedObservable = new BABYLON.Observable();
  85138. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85139. this._engine = scene.getEngine();
  85140. this._maxSize = this._engine.getCaps().maxTextureSize;
  85141. this._scene.effectLayers.push(this);
  85142. // Generate Buffers
  85143. this._generateIndexBuffer();
  85144. this._genrateVertexBuffer();
  85145. }
  85146. Object.defineProperty(EffectLayer.prototype, "camera", {
  85147. /**
  85148. * Gets the camera attached to the layer.
  85149. */
  85150. get: function () {
  85151. return this._effectLayerOptions.camera;
  85152. },
  85153. enumerable: true,
  85154. configurable: true
  85155. });
  85156. /**
  85157. * Initializes the effect layer with the required options.
  85158. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85159. */
  85160. EffectLayer.prototype._init = function (options) {
  85161. // Adapt options
  85162. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85163. this._setMainTextureSize();
  85164. this._createMainTexture();
  85165. this._createTextureAndPostProcesses();
  85166. this._mergeEffect = this._createMergeEffect();
  85167. };
  85168. /**
  85169. * Generates the index buffer of the full screen quad blending to the main canvas.
  85170. */
  85171. EffectLayer.prototype._generateIndexBuffer = function () {
  85172. // Indices
  85173. var indices = [];
  85174. indices.push(0);
  85175. indices.push(1);
  85176. indices.push(2);
  85177. indices.push(0);
  85178. indices.push(2);
  85179. indices.push(3);
  85180. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85181. };
  85182. /**
  85183. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85184. */
  85185. EffectLayer.prototype._genrateVertexBuffer = function () {
  85186. // VBO
  85187. var vertices = [];
  85188. vertices.push(1, 1);
  85189. vertices.push(-1, 1);
  85190. vertices.push(-1, -1);
  85191. vertices.push(1, -1);
  85192. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85194. };
  85195. /**
  85196. * Sets the main texture desired size which is the closest power of two
  85197. * of the engine canvas size.
  85198. */
  85199. EffectLayer.prototype._setMainTextureSize = function () {
  85200. if (this._effectLayerOptions.mainTextureFixedSize) {
  85201. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85202. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85203. }
  85204. else {
  85205. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85206. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85207. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85208. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85209. }
  85210. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85211. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85212. };
  85213. /**
  85214. * Creates the main texture for the effect layer.
  85215. */
  85216. EffectLayer.prototype._createMainTexture = function () {
  85217. var _this = this;
  85218. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85219. width: this._mainTextureDesiredSize.width,
  85220. height: this._mainTextureDesiredSize.height
  85221. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85222. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85223. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85224. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85225. this._mainTexture.anisotropicFilteringLevel = 1;
  85226. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85227. this._mainTexture.renderParticles = false;
  85228. this._mainTexture.renderList = null;
  85229. this._mainTexture.ignoreCameraViewport = true;
  85230. // Custom render function
  85231. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85232. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85233. var index;
  85234. var engine = _this._scene.getEngine();
  85235. if (depthOnlySubMeshes.length) {
  85236. engine.setColorWrite(false);
  85237. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85238. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85239. }
  85240. engine.setColorWrite(true);
  85241. }
  85242. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85243. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85244. }
  85245. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85246. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85247. }
  85248. for (index = 0; index < transparentSubMeshes.length; index++) {
  85249. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85250. }
  85251. };
  85252. this._mainTexture.onClearObservable.add(function (engine) {
  85253. engine.clear(_this.neutralColor, true, true, true);
  85254. });
  85255. };
  85256. /**
  85257. * Checks for the readiness of the element composing the layer.
  85258. * @param subMesh the mesh to check for
  85259. * @param useInstances specify wether or not to use instances to render the mesh
  85260. * @param emissiveTexture the associated emissive texture used to generate the glow
  85261. * @return true if ready otherwise, false
  85262. */
  85263. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85264. var material = subMesh.getMaterial();
  85265. if (!material) {
  85266. return false;
  85267. }
  85268. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85269. return false;
  85270. }
  85271. var defines = [];
  85272. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85273. var mesh = subMesh.getMesh();
  85274. var uv1 = false;
  85275. var uv2 = false;
  85276. // Alpha test
  85277. if (material && material.needAlphaTesting()) {
  85278. var alphaTexture = material.getAlphaTestTexture();
  85279. if (alphaTexture) {
  85280. defines.push("#define ALPHATEST");
  85281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85282. alphaTexture.coordinatesIndex === 1) {
  85283. defines.push("#define DIFFUSEUV2");
  85284. uv2 = true;
  85285. }
  85286. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85287. defines.push("#define DIFFUSEUV1");
  85288. uv1 = true;
  85289. }
  85290. }
  85291. }
  85292. // Emissive
  85293. if (emissiveTexture) {
  85294. defines.push("#define EMISSIVE");
  85295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85296. emissiveTexture.coordinatesIndex === 1) {
  85297. defines.push("#define EMISSIVEUV2");
  85298. uv2 = true;
  85299. }
  85300. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85301. defines.push("#define EMISSIVEUV1");
  85302. uv1 = true;
  85303. }
  85304. }
  85305. if (uv1) {
  85306. attribs.push(BABYLON.VertexBuffer.UVKind);
  85307. defines.push("#define UV1");
  85308. }
  85309. if (uv2) {
  85310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85311. defines.push("#define UV2");
  85312. }
  85313. // Bones
  85314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85317. if (mesh.numBoneInfluencers > 4) {
  85318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85320. }
  85321. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85322. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85323. }
  85324. else {
  85325. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85326. }
  85327. // Instances
  85328. if (useInstances) {
  85329. defines.push("#define INSTANCES");
  85330. attribs.push("world0");
  85331. attribs.push("world1");
  85332. attribs.push("world2");
  85333. attribs.push("world3");
  85334. }
  85335. // Get correct effect
  85336. var join = defines.join("\n");
  85337. if (this._cachedDefines !== join) {
  85338. this._cachedDefines = join;
  85339. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85340. }
  85341. return this._effectLayerMapGenerationEffect.isReady();
  85342. };
  85343. /**
  85344. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85345. */
  85346. EffectLayer.prototype.render = function () {
  85347. var currentEffect = this._mergeEffect;
  85348. // Check
  85349. if (!currentEffect.isReady())
  85350. return;
  85351. for (var i = 0; i < this._postProcesses.length; i++) {
  85352. if (!this._postProcesses[i].isReady()) {
  85353. return;
  85354. }
  85355. }
  85356. var engine = this._scene.getEngine();
  85357. this.onBeforeComposeObservable.notifyObservers(this);
  85358. // Render
  85359. engine.enableEffect(currentEffect);
  85360. engine.setState(false);
  85361. // VBOs
  85362. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85363. // Cache
  85364. var previousAlphaMode = engine.getAlphaMode();
  85365. // Go Blend.
  85366. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85367. // Blends the map on the main canvas.
  85368. this._internalRender(currentEffect);
  85369. // Restore Alpha
  85370. engine.setAlphaMode(previousAlphaMode);
  85371. this.onAfterComposeObservable.notifyObservers(this);
  85372. // Handle size changes.
  85373. var size = this._mainTexture.getSize();
  85374. this._setMainTextureSize();
  85375. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85376. // Recreate RTT and post processes on size change.
  85377. this.onSizeChangedObservable.notifyObservers(this);
  85378. this._disposeTextureAndPostProcesses();
  85379. this._createMainTexture();
  85380. this._createTextureAndPostProcesses();
  85381. }
  85382. };
  85383. /**
  85384. * Determine if a given mesh will be used in the current effect.
  85385. * @param mesh mesh to test
  85386. * @returns true if the mesh will be used
  85387. */
  85388. EffectLayer.prototype.hasMesh = function (mesh) {
  85389. return true;
  85390. };
  85391. /**
  85392. * Returns true if the layer contains information to display, otherwise false.
  85393. * @returns true if the glow layer should be rendered
  85394. */
  85395. EffectLayer.prototype.shouldRender = function () {
  85396. return this.isEnabled && this._shouldRender;
  85397. };
  85398. /**
  85399. * Returns true if the mesh should render, otherwise false.
  85400. * @param mesh The mesh to render
  85401. * @returns true if it should render otherwise false
  85402. */
  85403. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85404. return true;
  85405. };
  85406. /**
  85407. * Returns true if the mesh should render, otherwise false.
  85408. * @param mesh The mesh to render
  85409. * @returns true if it should render otherwise false
  85410. */
  85411. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85412. return true;
  85413. };
  85414. /**
  85415. * Renders the submesh passed in parameter to the generation map.
  85416. */
  85417. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85418. var _this = this;
  85419. if (!this.shouldRender()) {
  85420. return;
  85421. }
  85422. var material = subMesh.getMaterial();
  85423. var mesh = subMesh.getRenderingMesh();
  85424. var scene = this._scene;
  85425. var engine = scene.getEngine();
  85426. if (!material) {
  85427. return;
  85428. }
  85429. // Do not block in blend mode.
  85430. if (material.needAlphaBlendingForMesh(mesh)) {
  85431. return;
  85432. }
  85433. // Culling
  85434. engine.setState(material.backFaceCulling);
  85435. // Managing instances
  85436. var batch = mesh._getInstancesRenderList(subMesh._id);
  85437. if (batch.mustReturn) {
  85438. return;
  85439. }
  85440. // Early Exit per mesh
  85441. if (!this._shouldRenderMesh(mesh)) {
  85442. return;
  85443. }
  85444. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85445. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85446. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85447. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85448. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85449. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85450. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85451. // Alpha test
  85452. if (material && material.needAlphaTesting()) {
  85453. var alphaTexture = material.getAlphaTestTexture();
  85454. if (alphaTexture) {
  85455. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85456. var textureMatrix = alphaTexture.getTextureMatrix();
  85457. if (textureMatrix) {
  85458. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85459. }
  85460. }
  85461. }
  85462. // Glow emissive only
  85463. if (this._emissiveTextureAndColor.texture) {
  85464. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85465. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85466. }
  85467. // Bones
  85468. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85469. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85470. }
  85471. // Draw
  85472. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85473. }
  85474. else {
  85475. // Need to reset refresh rate of the shadowMap
  85476. this._mainTexture.resetRefreshCounter();
  85477. }
  85478. };
  85479. /**
  85480. * Rebuild the required buffers.
  85481. * @ignore Internal use only.
  85482. */
  85483. EffectLayer.prototype._rebuild = function () {
  85484. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85485. if (vb) {
  85486. vb._rebuild();
  85487. }
  85488. this._generateIndexBuffer();
  85489. };
  85490. /**
  85491. * Dispose only the render target textures and post process.
  85492. */
  85493. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85494. this._mainTexture.dispose();
  85495. for (var i = 0; i < this._postProcesses.length; i++) {
  85496. if (this._postProcesses[i]) {
  85497. this._postProcesses[i].dispose();
  85498. }
  85499. }
  85500. this._postProcesses = [];
  85501. for (var i = 0; i < this._textures.length; i++) {
  85502. if (this._textures[i]) {
  85503. this._textures[i].dispose();
  85504. }
  85505. }
  85506. this._textures = [];
  85507. };
  85508. /**
  85509. * Dispose the highlight layer and free resources.
  85510. */
  85511. EffectLayer.prototype.dispose = function () {
  85512. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85513. if (vertexBuffer) {
  85514. vertexBuffer.dispose();
  85515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85516. }
  85517. if (this._indexBuffer) {
  85518. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85519. this._indexBuffer = null;
  85520. }
  85521. // Clean textures and post processes
  85522. this._disposeTextureAndPostProcesses();
  85523. // Remove from scene
  85524. var index = this._scene.effectLayers.indexOf(this, 0);
  85525. if (index > -1) {
  85526. this._scene.effectLayers.splice(index, 1);
  85527. }
  85528. // Callback
  85529. this.onDisposeObservable.notifyObservers(this);
  85530. this.onDisposeObservable.clear();
  85531. this.onBeforeRenderMainTextureObservable.clear();
  85532. this.onBeforeComposeObservable.clear();
  85533. this.onAfterComposeObservable.clear();
  85534. this.onSizeChangedObservable.clear();
  85535. };
  85536. return EffectLayer;
  85537. }());
  85538. BABYLON.EffectLayer = EffectLayer;
  85539. })(BABYLON || (BABYLON = {}));
  85540. //# sourceMappingURL=babylon.effectLayer.js.map
  85541. var BABYLON;
  85542. (function (BABYLON) {
  85543. /**
  85544. * Special Glow Blur post process only blurring the alpha channel
  85545. * It enforces keeping the most luminous color in the color channel.
  85546. */
  85547. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85548. __extends(GlowBlurPostProcess, _super);
  85549. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85551. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85552. _this.direction = direction;
  85553. _this.kernel = kernel;
  85554. _this.onApplyObservable.add(function (effect) {
  85555. effect.setFloat2("screenSize", _this.width, _this.height);
  85556. effect.setVector2("direction", _this.direction);
  85557. effect.setFloat("blurWidth", _this.kernel);
  85558. });
  85559. return _this;
  85560. }
  85561. return GlowBlurPostProcess;
  85562. }(BABYLON.PostProcess));
  85563. /**
  85564. * The highlight layer Helps adding a glow effect around a mesh.
  85565. *
  85566. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85567. * glowy meshes to your scene.
  85568. *
  85569. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85570. */
  85571. var HighlightLayer = /** @class */ (function (_super) {
  85572. __extends(HighlightLayer, _super);
  85573. /**
  85574. * Instantiates a new highlight Layer and references it to the scene..
  85575. * @param name The name of the layer
  85576. * @param scene The scene to use the layer in
  85577. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85578. */
  85579. function HighlightLayer(name, scene, options) {
  85580. var _this = _super.call(this, name, scene) || this;
  85581. _this.name = name;
  85582. /**
  85583. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85584. */
  85585. _this.innerGlow = true;
  85586. /**
  85587. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85588. */
  85589. _this.outerGlow = true;
  85590. /**
  85591. * An event triggered when the highlight layer is being blurred.
  85592. */
  85593. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85594. /**
  85595. * An event triggered when the highlight layer has been blurred.
  85596. */
  85597. _this.onAfterBlurObservable = new BABYLON.Observable();
  85598. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85599. _this._meshes = {};
  85600. _this._excludedMeshes = {};
  85601. _this.neutralColor = HighlightLayer.NeutralColor;
  85602. // Warn on stencil
  85603. if (!_this._engine.isStencilEnable) {
  85604. 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 }");
  85605. }
  85606. // Adapt options
  85607. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85608. // Initialize the layer
  85609. _this._init({
  85610. alphaBlendingMode: _this._options.alphaBlendingMode,
  85611. camera: _this._options.camera,
  85612. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85613. mainTextureRatio: _this._options.mainTextureRatio
  85614. });
  85615. // Do not render as long as no meshes have been added
  85616. _this._shouldRender = false;
  85617. return _this;
  85618. }
  85619. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85620. /**
  85621. * Gets the horizontal size of the blur.
  85622. */
  85623. get: function () {
  85624. return this._horizontalBlurPostprocess.kernel;
  85625. },
  85626. /**
  85627. * Specifies the horizontal size of the blur.
  85628. */
  85629. set: function (value) {
  85630. this._horizontalBlurPostprocess.kernel = value;
  85631. },
  85632. enumerable: true,
  85633. configurable: true
  85634. });
  85635. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85636. /**
  85637. * Gets the vertical size of the blur.
  85638. */
  85639. get: function () {
  85640. return this._verticalBlurPostprocess.kernel;
  85641. },
  85642. /**
  85643. * Specifies the vertical size of the blur.
  85644. */
  85645. set: function (value) {
  85646. this._verticalBlurPostprocess.kernel = value;
  85647. },
  85648. enumerable: true,
  85649. configurable: true
  85650. });
  85651. /**
  85652. * Get the effect name of the layer.
  85653. * @return The effect name
  85654. */
  85655. HighlightLayer.prototype.getEffectName = function () {
  85656. return HighlightLayer.EffectName;
  85657. };
  85658. /**
  85659. * Create the merge effect. This is the shader use to blit the information back
  85660. * to the main canvas at the end of the scene rendering.
  85661. */
  85662. HighlightLayer.prototype._createMergeEffect = function () {
  85663. // Effect
  85664. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85665. };
  85666. /**
  85667. * Creates the render target textures and post processes used in the highlight layer.
  85668. */
  85669. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85670. var _this = this;
  85671. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85672. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85673. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85674. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85675. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85676. width: blurTextureWidth,
  85677. height: blurTextureHeight
  85678. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85679. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85680. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85681. this._blurTexture.anisotropicFilteringLevel = 16;
  85682. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85683. this._blurTexture.renderParticles = false;
  85684. this._blurTexture.ignoreCameraViewport = true;
  85685. this._textures = [this._blurTexture];
  85686. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85687. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85688. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85689. effect.setTexture("textureSampler", _this._mainTexture);
  85690. });
  85691. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85692. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85693. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85694. });
  85695. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85696. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85697. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85698. });
  85699. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85700. }
  85701. else {
  85702. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85703. width: blurTextureWidth,
  85704. height: blurTextureHeight
  85705. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85706. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85707. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85708. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85709. effect.setTexture("textureSampler", _this._mainTexture);
  85710. });
  85711. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85712. width: blurTextureWidth,
  85713. height: blurTextureHeight
  85714. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85715. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85716. }
  85717. this._mainTexture.onAfterUnbindObservable.add(function () {
  85718. _this.onBeforeBlurObservable.notifyObservers(_this);
  85719. var internalTexture = _this._blurTexture.getInternalTexture();
  85720. if (internalTexture) {
  85721. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85722. }
  85723. _this.onAfterBlurObservable.notifyObservers(_this);
  85724. });
  85725. // Prevent autoClear.
  85726. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85727. };
  85728. /**
  85729. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85730. */
  85731. HighlightLayer.prototype.needStencil = function () {
  85732. return true;
  85733. };
  85734. /**
  85735. * Checks for the readiness of the element composing the layer.
  85736. * @param subMesh the mesh to check for
  85737. * @param useInstances specify wether or not to use instances to render the mesh
  85738. * @param emissiveTexture the associated emissive texture used to generate the glow
  85739. * @return true if ready otherwise, false
  85740. */
  85741. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85742. var material = subMesh.getMaterial();
  85743. var mesh = subMesh.getRenderingMesh();
  85744. if (!material || !mesh || !this._meshes) {
  85745. return false;
  85746. }
  85747. var emissiveTexture = null;
  85748. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85749. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85750. emissiveTexture = material.emissiveTexture;
  85751. }
  85752. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85753. };
  85754. /**
  85755. * Implementation specific of rendering the generating effect on the main canvas.
  85756. * @param effect The effect used to render through
  85757. */
  85758. HighlightLayer.prototype._internalRender = function (effect) {
  85759. // Texture
  85760. effect.setTexture("textureSampler", this._blurTexture);
  85761. // Cache
  85762. var engine = this._engine;
  85763. var previousStencilBuffer = engine.getStencilBuffer();
  85764. var previousStencilFunction = engine.getStencilFunction();
  85765. var previousStencilMask = engine.getStencilMask();
  85766. var previousStencilOperationPass = engine.getStencilOperationPass();
  85767. var previousStencilOperationFail = engine.getStencilOperationFail();
  85768. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85769. var previousStencilReference = engine.getStencilFunctionReference();
  85770. // Stencil operations
  85771. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85772. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85773. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85774. // Draw order
  85775. engine.setStencilMask(0x00);
  85776. engine.setStencilBuffer(true);
  85777. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85778. // 2 passes inner outer
  85779. if (this.outerGlow) {
  85780. effect.setFloat("offset", 0);
  85781. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85783. }
  85784. if (this.innerGlow) {
  85785. effect.setFloat("offset", 1);
  85786. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85788. }
  85789. // Restore Cache
  85790. engine.setStencilFunction(previousStencilFunction);
  85791. engine.setStencilMask(previousStencilMask);
  85792. engine.setStencilBuffer(previousStencilBuffer);
  85793. engine.setStencilOperationPass(previousStencilOperationPass);
  85794. engine.setStencilOperationFail(previousStencilOperationFail);
  85795. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85796. engine.setStencilFunctionReference(previousStencilReference);
  85797. };
  85798. /**
  85799. * Returns true if the layer contains information to display, otherwise false.
  85800. */
  85801. HighlightLayer.prototype.shouldRender = function () {
  85802. if (_super.prototype.shouldRender.call(this)) {
  85803. return this._meshes ? true : false;
  85804. }
  85805. return false;
  85806. };
  85807. /**
  85808. * Returns true if the mesh should render, otherwise false.
  85809. * @param mesh The mesh to render
  85810. * @returns true if it should render otherwise false
  85811. */
  85812. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85813. // Excluded Mesh
  85814. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85815. return false;
  85816. }
  85817. ;
  85818. return true;
  85819. };
  85820. /**
  85821. * Sets the required values for both the emissive texture and and the main color.
  85822. */
  85823. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85824. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85825. if (highlightLayerMesh) {
  85826. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85827. }
  85828. else {
  85829. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85830. }
  85831. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85832. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85833. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85834. }
  85835. else {
  85836. this._emissiveTextureAndColor.texture = null;
  85837. }
  85838. };
  85839. /**
  85840. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85841. * @param mesh The mesh to exclude from the highlight layer
  85842. */
  85843. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85844. if (!this._excludedMeshes) {
  85845. return;
  85846. }
  85847. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85848. if (!meshExcluded) {
  85849. this._excludedMeshes[mesh.uniqueId] = {
  85850. mesh: mesh,
  85851. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85852. mesh.getEngine().setStencilBuffer(false);
  85853. }),
  85854. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85855. mesh.getEngine().setStencilBuffer(true);
  85856. }),
  85857. };
  85858. }
  85859. };
  85860. /**
  85861. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85862. * @param mesh The mesh to highlight
  85863. */
  85864. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85865. if (!this._excludedMeshes) {
  85866. return;
  85867. }
  85868. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85869. if (meshExcluded) {
  85870. if (meshExcluded.beforeRender) {
  85871. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85872. }
  85873. if (meshExcluded.afterRender) {
  85874. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85875. }
  85876. }
  85877. this._excludedMeshes[mesh.uniqueId] = null;
  85878. };
  85879. /**
  85880. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85881. * @param mesh mesh to test
  85882. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85883. */
  85884. HighlightLayer.prototype.hasMesh = function (mesh) {
  85885. if (!this._meshes) {
  85886. return false;
  85887. }
  85888. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85889. };
  85890. /**
  85891. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85892. * @param mesh The mesh to highlight
  85893. * @param color The color of the highlight
  85894. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85895. */
  85896. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85897. var _this = this;
  85898. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85899. if (!this._meshes) {
  85900. return;
  85901. }
  85902. var meshHighlight = this._meshes[mesh.uniqueId];
  85903. if (meshHighlight) {
  85904. meshHighlight.color = color;
  85905. }
  85906. else {
  85907. this._meshes[mesh.uniqueId] = {
  85908. mesh: mesh,
  85909. color: color,
  85910. // Lambda required for capture due to Observable this context
  85911. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85912. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85913. _this._defaultStencilReference(mesh);
  85914. }
  85915. else {
  85916. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85917. }
  85918. }),
  85919. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85920. glowEmissiveOnly: glowEmissiveOnly
  85921. };
  85922. }
  85923. this._shouldRender = true;
  85924. };
  85925. /**
  85926. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85927. * @param mesh The mesh to highlight
  85928. */
  85929. HighlightLayer.prototype.removeMesh = function (mesh) {
  85930. if (!this._meshes) {
  85931. return;
  85932. }
  85933. var meshHighlight = this._meshes[mesh.uniqueId];
  85934. if (meshHighlight) {
  85935. if (meshHighlight.observerHighlight) {
  85936. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85937. }
  85938. if (meshHighlight.observerDefault) {
  85939. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85940. }
  85941. delete this._meshes[mesh.uniqueId];
  85942. }
  85943. this._shouldRender = false;
  85944. for (var meshHighlightToCheck in this._meshes) {
  85945. if (this._meshes[meshHighlightToCheck]) {
  85946. this._shouldRender = true;
  85947. break;
  85948. }
  85949. }
  85950. };
  85951. /**
  85952. * Force the stencil to the normal expected value for none glowing parts
  85953. */
  85954. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85955. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85956. };
  85957. /**
  85958. * Free any resources and references associated to a mesh.
  85959. * Internal use
  85960. * @param mesh The mesh to free.
  85961. */
  85962. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85963. this.removeMesh(mesh);
  85964. this.removeExcludedMesh(mesh);
  85965. };
  85966. /**
  85967. * Dispose the highlight layer and free resources.
  85968. */
  85969. HighlightLayer.prototype.dispose = function () {
  85970. if (this._meshes) {
  85971. // Clean mesh references
  85972. for (var id in this._meshes) {
  85973. var meshHighlight = this._meshes[id];
  85974. if (meshHighlight && meshHighlight.mesh) {
  85975. if (meshHighlight.observerHighlight) {
  85976. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85977. }
  85978. if (meshHighlight.observerDefault) {
  85979. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85980. }
  85981. }
  85982. }
  85983. this._meshes = null;
  85984. }
  85985. if (this._excludedMeshes) {
  85986. for (var id in this._excludedMeshes) {
  85987. var meshHighlight = this._excludedMeshes[id];
  85988. if (meshHighlight) {
  85989. if (meshHighlight.beforeRender) {
  85990. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85991. }
  85992. if (meshHighlight.afterRender) {
  85993. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85994. }
  85995. }
  85996. }
  85997. this._excludedMeshes = null;
  85998. }
  85999. _super.prototype.dispose.call(this);
  86000. };
  86001. /**
  86002. * Effect Name of the highlight layer.
  86003. */
  86004. HighlightLayer.EffectName = "HighlightLayer";
  86005. /**
  86006. * The neutral color used during the preparation of the glow effect.
  86007. * This is black by default as the blend operation is a blend operation.
  86008. */
  86009. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86010. /**
  86011. * Stencil value used for glowing meshes.
  86012. */
  86013. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86014. /**
  86015. * Stencil value used for the other meshes in the scene.
  86016. */
  86017. HighlightLayer.NormalMeshStencilReference = 0x01;
  86018. return HighlightLayer;
  86019. }(BABYLON.EffectLayer));
  86020. BABYLON.HighlightLayer = HighlightLayer;
  86021. })(BABYLON || (BABYLON = {}));
  86022. //# sourceMappingURL=babylon.highlightLayer.js.map
  86023. var BABYLON;
  86024. (function (BABYLON) {
  86025. /**
  86026. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86027. *
  86028. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86029. * glowy meshes to your scene.
  86030. *
  86031. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86032. */
  86033. var GlowLayer = /** @class */ (function (_super) {
  86034. __extends(GlowLayer, _super);
  86035. /**
  86036. * Instantiates a new glow Layer and references it to the scene.
  86037. * @param name The name of the layer
  86038. * @param scene The scene to use the layer in
  86039. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86040. */
  86041. function GlowLayer(name, scene, options) {
  86042. var _this = _super.call(this, name, scene) || this;
  86043. _this.name = name;
  86044. _this._intensity = 1.0;
  86045. _this._includedOnlyMeshes = [];
  86046. _this._excludedMeshes = [];
  86047. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86048. // Adapt options
  86049. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86050. // Initialize the layer
  86051. _this._init({
  86052. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86053. camera: _this._options.camera,
  86054. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86055. mainTextureRatio: _this._options.mainTextureRatio
  86056. });
  86057. return _this;
  86058. }
  86059. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86060. /**
  86061. * Gets the kernel size of the blur.
  86062. */
  86063. get: function () {
  86064. return this._horizontalBlurPostprocess1.kernel;
  86065. },
  86066. /**
  86067. * Sets the kernel size of the blur.
  86068. */
  86069. set: function (value) {
  86070. this._horizontalBlurPostprocess1.kernel = value;
  86071. this._verticalBlurPostprocess1.kernel = value;
  86072. this._horizontalBlurPostprocess2.kernel = value;
  86073. this._verticalBlurPostprocess2.kernel = value;
  86074. },
  86075. enumerable: true,
  86076. configurable: true
  86077. });
  86078. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86079. /**
  86080. * Gets the glow intensity.
  86081. */
  86082. get: function () {
  86083. return this._intensity;
  86084. },
  86085. /**
  86086. * Sets the glow intensity.
  86087. */
  86088. set: function (value) {
  86089. this._intensity = value;
  86090. },
  86091. enumerable: true,
  86092. configurable: true
  86093. });
  86094. /**
  86095. * Get the effect name of the layer.
  86096. * @return The effect name
  86097. */
  86098. GlowLayer.prototype.getEffectName = function () {
  86099. return GlowLayer.EffectName;
  86100. };
  86101. /**
  86102. * Create the merge effect. This is the shader use to blit the information back
  86103. * to the main canvas at the end of the scene rendering.
  86104. */
  86105. GlowLayer.prototype._createMergeEffect = function () {
  86106. // Effect
  86107. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86108. };
  86109. /**
  86110. * Creates the render target textures and post processes used in the glow layer.
  86111. */
  86112. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86113. var _this = this;
  86114. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86115. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86116. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86117. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86118. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86119. width: blurTextureWidth,
  86120. height: blurTextureHeight
  86121. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86122. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86123. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86124. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86125. this._blurTexture1.renderParticles = false;
  86126. this._blurTexture1.ignoreCameraViewport = true;
  86127. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86128. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86129. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86130. width: blurTextureWidth2,
  86131. height: blurTextureHeight2
  86132. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86133. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86134. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86135. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86136. this._blurTexture2.renderParticles = false;
  86137. this._blurTexture2.ignoreCameraViewport = true;
  86138. this._textures = [this._blurTexture1, this._blurTexture2];
  86139. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86140. width: blurTextureWidth,
  86141. height: blurTextureHeight
  86142. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86143. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86144. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86145. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86146. effect.setTexture("textureSampler", _this._mainTexture);
  86147. });
  86148. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86149. width: blurTextureWidth,
  86150. height: blurTextureHeight
  86151. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86152. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86153. width: blurTextureWidth2,
  86154. height: blurTextureHeight2
  86155. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86156. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86157. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86158. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86159. effect.setTexture("textureSampler", _this._blurTexture1);
  86160. });
  86161. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86162. width: blurTextureWidth2,
  86163. height: blurTextureHeight2
  86164. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86165. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86166. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86167. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86168. this._mainTexture.samples = this._options.mainTextureSamples;
  86169. this._mainTexture.onAfterUnbindObservable.add(function () {
  86170. var internalTexture = _this._blurTexture1.getInternalTexture();
  86171. if (internalTexture) {
  86172. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86173. internalTexture = _this._blurTexture2.getInternalTexture();
  86174. if (internalTexture) {
  86175. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86176. }
  86177. }
  86178. });
  86179. // Prevent autoClear.
  86180. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86181. };
  86182. /**
  86183. * Checks for the readiness of the element composing the layer.
  86184. * @param subMesh the mesh to check for
  86185. * @param useInstances specify wether or not to use instances to render the mesh
  86186. * @param emissiveTexture the associated emissive texture used to generate the glow
  86187. * @return true if ready otherwise, false
  86188. */
  86189. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86190. var material = subMesh.getMaterial();
  86191. var mesh = subMesh.getRenderingMesh();
  86192. if (!material || !mesh) {
  86193. return false;
  86194. }
  86195. var emissiveTexture = material.emissiveTexture;
  86196. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86197. };
  86198. /**
  86199. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86200. */
  86201. GlowLayer.prototype.needStencil = function () {
  86202. return false;
  86203. };
  86204. /**
  86205. * Implementation specific of rendering the generating effect on the main canvas.
  86206. * @param effect The effect used to render through
  86207. */
  86208. GlowLayer.prototype._internalRender = function (effect) {
  86209. // Texture
  86210. effect.setTexture("textureSampler", this._blurTexture1);
  86211. effect.setTexture("textureSampler2", this._blurTexture2);
  86212. effect.setFloat("offset", this._intensity);
  86213. // Cache
  86214. var engine = this._engine;
  86215. var previousStencilBuffer = engine.getStencilBuffer();
  86216. // Draw order
  86217. engine.setStencilBuffer(false);
  86218. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86219. // Draw order
  86220. engine.setStencilBuffer(previousStencilBuffer);
  86221. };
  86222. /**
  86223. * Sets the required values for both the emissive texture and and the main color.
  86224. */
  86225. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86226. var textureLevel = 1.0;
  86227. if (this.customEmissiveTextureSelector) {
  86228. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86229. }
  86230. else {
  86231. if (material) {
  86232. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86233. if (this._emissiveTextureAndColor.texture) {
  86234. textureLevel = this._emissiveTextureAndColor.texture.level;
  86235. }
  86236. }
  86237. else {
  86238. this._emissiveTextureAndColor.texture = null;
  86239. }
  86240. }
  86241. if (this.customEmissiveColorSelector) {
  86242. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86243. }
  86244. else {
  86245. if (material.emissiveColor) {
  86246. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86247. }
  86248. else {
  86249. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86250. }
  86251. }
  86252. };
  86253. /**
  86254. * Returns true if the mesh should render, otherwise false.
  86255. * @param mesh The mesh to render
  86256. * @returns true if it should render otherwise false
  86257. */
  86258. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86259. return this.hasMesh(mesh);
  86260. };
  86261. /**
  86262. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86263. * @param mesh The mesh to exclude from the glow layer
  86264. */
  86265. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86266. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86267. this._excludedMeshes.push(mesh.uniqueId);
  86268. }
  86269. };
  86270. /**
  86271. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86272. * @param mesh The mesh to remove
  86273. */
  86274. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86275. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86276. if (index !== -1) {
  86277. this._excludedMeshes.splice(index, 1);
  86278. }
  86279. };
  86280. /**
  86281. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86282. * @param mesh The mesh to include in the glow layer
  86283. */
  86284. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86285. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86286. this._includedOnlyMeshes.push(mesh.uniqueId);
  86287. }
  86288. };
  86289. /**
  86290. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86291. * @param mesh The mesh to remove
  86292. */
  86293. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86294. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86295. if (index !== -1) {
  86296. this._includedOnlyMeshes.splice(index, 1);
  86297. }
  86298. };
  86299. /**
  86300. * Determine if a given mesh will be used in the glow layer
  86301. * @param mesh The mesh to test
  86302. * @returns true if the mesh will be highlighted by the current glow layer
  86303. */
  86304. GlowLayer.prototype.hasMesh = function (mesh) {
  86305. // Included Mesh
  86306. if (this._includedOnlyMeshes.length) {
  86307. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86308. }
  86309. ;
  86310. // Excluded Mesh
  86311. if (this._excludedMeshes.length) {
  86312. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86313. }
  86314. ;
  86315. return true;
  86316. };
  86317. /**
  86318. * Free any resources and references associated to a mesh.
  86319. * Internal use
  86320. * @param mesh The mesh to free.
  86321. */
  86322. GlowLayer.prototype._disposeMesh = function (mesh) {
  86323. this.removeIncludedOnlyMesh(mesh);
  86324. this.removeExcludedMesh(mesh);
  86325. };
  86326. /**
  86327. * Effect Name of the layer.
  86328. */
  86329. GlowLayer.EffectName = "GlowLayer";
  86330. /**
  86331. * The default blur kernel size used for the glow.
  86332. */
  86333. GlowLayer.DefaultBlurKernelSize = 32;
  86334. /**
  86335. * The default texture size ratio used for the glow.
  86336. */
  86337. GlowLayer.DefaultTextureRatio = 0.5;
  86338. return GlowLayer;
  86339. }(BABYLON.EffectLayer));
  86340. BABYLON.GlowLayer = GlowLayer;
  86341. })(BABYLON || (BABYLON = {}));
  86342. //# sourceMappingURL=babylon.glowLayer.js.map
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. /**
  86346. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86347. */
  86348. var AssetTaskState;
  86349. (function (AssetTaskState) {
  86350. /**
  86351. * Initialization
  86352. */
  86353. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86354. /**
  86355. * Running
  86356. */
  86357. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86358. /**
  86359. * Done
  86360. */
  86361. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86362. /**
  86363. * Error
  86364. */
  86365. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86366. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86367. /**
  86368. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86369. */
  86370. var AbstractAssetTask = /** @class */ (function () {
  86371. /**
  86372. * Creates a new {BABYLON.AssetsManager}
  86373. * @param name defines the name of the task
  86374. */
  86375. function AbstractAssetTask(
  86376. /**
  86377. * Task name
  86378. */ name) {
  86379. this.name = name;
  86380. this._isCompleted = false;
  86381. this._taskState = AssetTaskState.INIT;
  86382. }
  86383. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86384. /**
  86385. * Get if the task is completed
  86386. */
  86387. get: function () {
  86388. return this._isCompleted;
  86389. },
  86390. enumerable: true,
  86391. configurable: true
  86392. });
  86393. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86394. /**
  86395. * Gets the current state of the task
  86396. */
  86397. get: function () {
  86398. return this._taskState;
  86399. },
  86400. enumerable: true,
  86401. configurable: true
  86402. });
  86403. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86404. /**
  86405. * Gets the current error object (if task is in error)
  86406. */
  86407. get: function () {
  86408. return this._errorObject;
  86409. },
  86410. enumerable: true,
  86411. configurable: true
  86412. });
  86413. /**
  86414. * Internal only
  86415. * @ignore
  86416. */
  86417. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86418. if (this._errorObject) {
  86419. return;
  86420. }
  86421. this._errorObject = {
  86422. message: message,
  86423. exception: exception
  86424. };
  86425. };
  86426. /**
  86427. * Execute the current task
  86428. * @param scene defines the scene where you want your assets to be loaded
  86429. * @param onSuccess is a callback called when the task is successfully executed
  86430. * @param onError is a callback called if an error occurs
  86431. */
  86432. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86433. var _this = this;
  86434. this._taskState = AssetTaskState.RUNNING;
  86435. this.runTask(scene, function () {
  86436. _this.onDoneCallback(onSuccess, onError);
  86437. }, function (msg, exception) {
  86438. _this.onErrorCallback(onError, msg, exception);
  86439. });
  86440. };
  86441. /**
  86442. * Execute the current task
  86443. * @param scene defines the scene where you want your assets to be loaded
  86444. * @param onSuccess is a callback called when the task is successfully executed
  86445. * @param onError is a callback called if an error occurs
  86446. */
  86447. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86448. throw new Error("runTask is not implemented");
  86449. };
  86450. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86451. this._taskState = AssetTaskState.ERROR;
  86452. this._errorObject = {
  86453. message: message,
  86454. exception: exception
  86455. };
  86456. if (this.onError) {
  86457. this.onError(this, message, exception);
  86458. }
  86459. onError();
  86460. };
  86461. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86462. try {
  86463. this._taskState = AssetTaskState.DONE;
  86464. this._isCompleted = true;
  86465. if (this.onSuccess) {
  86466. this.onSuccess(this);
  86467. }
  86468. onSuccess();
  86469. }
  86470. catch (e) {
  86471. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86472. }
  86473. };
  86474. return AbstractAssetTask;
  86475. }());
  86476. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86477. /**
  86478. * Class used to share progress information about assets loading
  86479. */
  86480. var AssetsProgressEvent = /** @class */ (function () {
  86481. /**
  86482. * Creates a {BABYLON.AssetsProgressEvent}
  86483. * @param remainingCount defines the number of remaining tasks to process
  86484. * @param totalCount defines the total number of tasks
  86485. * @param task defines the task that was just processed
  86486. */
  86487. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86488. this.remainingCount = remainingCount;
  86489. this.totalCount = totalCount;
  86490. this.task = task;
  86491. }
  86492. return AssetsProgressEvent;
  86493. }());
  86494. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86495. /**
  86496. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86497. */
  86498. var MeshAssetTask = /** @class */ (function (_super) {
  86499. __extends(MeshAssetTask, _super);
  86500. /**
  86501. * Creates a new {BABYLON.MeshAssetTask}
  86502. * @param name defines the name of the task
  86503. * @param meshesNames defines the list of mesh's names you want to load
  86504. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86505. * @param sceneFilename defines the filename of the scene to load from
  86506. */
  86507. function MeshAssetTask(
  86508. /**
  86509. * Defines the name of the task
  86510. */
  86511. name,
  86512. /**
  86513. * Defines the list of mesh's names you want to load
  86514. */
  86515. meshesNames,
  86516. /**
  86517. * Defines the root url to use as a base to load your meshes and associated resources
  86518. */
  86519. rootUrl,
  86520. /**
  86521. * Defines the filename of the scene to load from
  86522. */
  86523. sceneFilename) {
  86524. var _this = _super.call(this, name) || this;
  86525. _this.name = name;
  86526. _this.meshesNames = meshesNames;
  86527. _this.rootUrl = rootUrl;
  86528. _this.sceneFilename = sceneFilename;
  86529. return _this;
  86530. }
  86531. /**
  86532. * Execute the current task
  86533. * @param scene defines the scene where you want your assets to be loaded
  86534. * @param onSuccess is a callback called when the task is successfully executed
  86535. * @param onError is a callback called if an error occurs
  86536. */
  86537. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86538. var _this = this;
  86539. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86540. _this.loadedMeshes = meshes;
  86541. _this.loadedParticleSystems = particleSystems;
  86542. _this.loadedSkeletons = skeletons;
  86543. onSuccess();
  86544. }, null, function (scene, message, exception) {
  86545. onError(message, exception);
  86546. });
  86547. };
  86548. return MeshAssetTask;
  86549. }(AbstractAssetTask));
  86550. BABYLON.MeshAssetTask = MeshAssetTask;
  86551. /**
  86552. * Define a task used by {BABYLON.AssetsManager} to load text content
  86553. */
  86554. var TextFileAssetTask = /** @class */ (function (_super) {
  86555. __extends(TextFileAssetTask, _super);
  86556. /**
  86557. * Creates a new TextFileAssetTask object
  86558. * @param name defines the name of the task
  86559. * @param url defines the location of the file to load
  86560. */
  86561. function TextFileAssetTask(
  86562. /**
  86563. * Defines the name of the task
  86564. */
  86565. name,
  86566. /**
  86567. * Defines the location of the file to load
  86568. */
  86569. url) {
  86570. var _this = _super.call(this, name) || this;
  86571. _this.name = name;
  86572. _this.url = url;
  86573. return _this;
  86574. }
  86575. /**
  86576. * Execute the current task
  86577. * @param scene defines the scene where you want your assets to be loaded
  86578. * @param onSuccess is a callback called when the task is successfully executed
  86579. * @param onError is a callback called if an error occurs
  86580. */
  86581. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86582. var _this = this;
  86583. scene._loadFile(this.url, function (data) {
  86584. _this.text = data;
  86585. onSuccess();
  86586. }, undefined, false, false, function (request, exception) {
  86587. if (request) {
  86588. onError(request.status + " " + request.statusText, exception);
  86589. }
  86590. });
  86591. };
  86592. return TextFileAssetTask;
  86593. }(AbstractAssetTask));
  86594. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86595. /**
  86596. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86597. */
  86598. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86599. __extends(BinaryFileAssetTask, _super);
  86600. /**
  86601. * Creates a new BinaryFileAssetTask object
  86602. * @param name defines the name of the new task
  86603. * @param url defines the location of the file to load
  86604. */
  86605. function BinaryFileAssetTask(
  86606. /**
  86607. * Defines the name of the task
  86608. */
  86609. name,
  86610. /**
  86611. * Defines the location of the file to load
  86612. */
  86613. url) {
  86614. var _this = _super.call(this, name) || this;
  86615. _this.name = name;
  86616. _this.url = url;
  86617. return _this;
  86618. }
  86619. /**
  86620. * Execute the current task
  86621. * @param scene defines the scene where you want your assets to be loaded
  86622. * @param onSuccess is a callback called when the task is successfully executed
  86623. * @param onError is a callback called if an error occurs
  86624. */
  86625. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86626. var _this = this;
  86627. scene._loadFile(this.url, function (data) {
  86628. _this.data = data;
  86629. onSuccess();
  86630. }, undefined, true, true, function (request, exception) {
  86631. if (request) {
  86632. onError(request.status + " " + request.statusText, exception);
  86633. }
  86634. });
  86635. };
  86636. return BinaryFileAssetTask;
  86637. }(AbstractAssetTask));
  86638. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86639. /**
  86640. * Define a task used by {BABYLON.AssetsManager} to load images
  86641. */
  86642. var ImageAssetTask = /** @class */ (function (_super) {
  86643. __extends(ImageAssetTask, _super);
  86644. /**
  86645. * Creates a new ImageAssetTask
  86646. * @param name defines the name of the task
  86647. * @param url defines the location of the image to load
  86648. */
  86649. function ImageAssetTask(
  86650. /**
  86651. * Defines the name of the task
  86652. */
  86653. name,
  86654. /**
  86655. * Defines the location of the image to load
  86656. */
  86657. url) {
  86658. var _this = _super.call(this, name) || this;
  86659. _this.name = name;
  86660. _this.url = url;
  86661. return _this;
  86662. }
  86663. /**
  86664. * Execute the current task
  86665. * @param scene defines the scene where you want your assets to be loaded
  86666. * @param onSuccess is a callback called when the task is successfully executed
  86667. * @param onError is a callback called if an error occurs
  86668. */
  86669. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86670. var _this = this;
  86671. var img = new Image();
  86672. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86673. img.onload = function () {
  86674. _this.image = img;
  86675. onSuccess();
  86676. };
  86677. img.onerror = function (err) {
  86678. onError("Error loading image", err);
  86679. };
  86680. img.src = this.url;
  86681. };
  86682. return ImageAssetTask;
  86683. }(AbstractAssetTask));
  86684. BABYLON.ImageAssetTask = ImageAssetTask;
  86685. /**
  86686. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86687. */
  86688. var TextureAssetTask = /** @class */ (function (_super) {
  86689. __extends(TextureAssetTask, _super);
  86690. /**
  86691. * Creates a new TextureAssetTask object
  86692. * @param name defines the name of the task
  86693. * @param url defines the location of the file to load
  86694. * @param noMipmap defines if mipmap should not be generated (default is false)
  86695. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86696. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86697. */
  86698. function TextureAssetTask(
  86699. /**
  86700. * Defines the name of the task
  86701. */
  86702. name,
  86703. /**
  86704. * Defines the location of the file to load
  86705. */
  86706. url,
  86707. /**
  86708. * Defines if mipmap should not be generated (default is false)
  86709. */
  86710. noMipmap,
  86711. /**
  86712. * Defines if texture must be inverted on Y axis (default is false)
  86713. */
  86714. invertY,
  86715. /**
  86716. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86717. */
  86718. samplingMode) {
  86719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86720. var _this = _super.call(this, name) || this;
  86721. _this.name = name;
  86722. _this.url = url;
  86723. _this.noMipmap = noMipmap;
  86724. _this.invertY = invertY;
  86725. _this.samplingMode = samplingMode;
  86726. return _this;
  86727. }
  86728. /**
  86729. * Execute the current task
  86730. * @param scene defines the scene where you want your assets to be loaded
  86731. * @param onSuccess is a callback called when the task is successfully executed
  86732. * @param onError is a callback called if an error occurs
  86733. */
  86734. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86735. var onload = function () {
  86736. onSuccess();
  86737. };
  86738. var onerror = function (message, exception) {
  86739. onError(message, exception);
  86740. };
  86741. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86742. };
  86743. return TextureAssetTask;
  86744. }(AbstractAssetTask));
  86745. BABYLON.TextureAssetTask = TextureAssetTask;
  86746. /**
  86747. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86748. */
  86749. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86750. __extends(CubeTextureAssetTask, _super);
  86751. /**
  86752. * Creates a new CubeTextureAssetTask
  86753. * @param name defines the name of the task
  86754. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86755. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86756. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86757. * @param files defines the explicit list of files (undefined by default)
  86758. */
  86759. function CubeTextureAssetTask(
  86760. /**
  86761. * Defines the name of the task
  86762. */
  86763. name,
  86764. /**
  86765. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86766. */
  86767. url,
  86768. /**
  86769. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86770. */
  86771. extensions,
  86772. /**
  86773. * Defines if mipmaps should not be generated (default is false)
  86774. */
  86775. noMipmap,
  86776. /**
  86777. * Defines the explicit list of files (undefined by default)
  86778. */
  86779. files) {
  86780. var _this = _super.call(this, name) || this;
  86781. _this.name = name;
  86782. _this.url = url;
  86783. _this.extensions = extensions;
  86784. _this.noMipmap = noMipmap;
  86785. _this.files = files;
  86786. return _this;
  86787. }
  86788. /**
  86789. * Execute the current task
  86790. * @param scene defines the scene where you want your assets to be loaded
  86791. * @param onSuccess is a callback called when the task is successfully executed
  86792. * @param onError is a callback called if an error occurs
  86793. */
  86794. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86795. var onload = function () {
  86796. onSuccess();
  86797. };
  86798. var onerror = function (message, exception) {
  86799. onError(message, exception);
  86800. };
  86801. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86802. };
  86803. return CubeTextureAssetTask;
  86804. }(AbstractAssetTask));
  86805. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86806. /**
  86807. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86808. */
  86809. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86810. __extends(HDRCubeTextureAssetTask, _super);
  86811. /**
  86812. * Creates a new HDRCubeTextureAssetTask object
  86813. * @param name defines the name of the task
  86814. * @param url defines the location of the file to load
  86815. * @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.
  86816. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86817. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86818. * @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)
  86819. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86820. */
  86821. function HDRCubeTextureAssetTask(
  86822. /**
  86823. * Defines the name of the task
  86824. */
  86825. name,
  86826. /**
  86827. * Defines the location of the file to load
  86828. */
  86829. url,
  86830. /**
  86831. * 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.
  86832. */
  86833. size,
  86834. /**
  86835. * Defines if mipmaps should not be generated (default is false)
  86836. */
  86837. noMipmap,
  86838. /**
  86839. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86840. */
  86841. generateHarmonics,
  86842. /**
  86843. * 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)
  86844. */
  86845. useInGammaSpace,
  86846. /**
  86847. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86848. */
  86849. usePMREMGenerator) {
  86850. if (noMipmap === void 0) { noMipmap = false; }
  86851. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86852. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86853. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86854. var _this = _super.call(this, name) || this;
  86855. _this.name = name;
  86856. _this.url = url;
  86857. _this.size = size;
  86858. _this.noMipmap = noMipmap;
  86859. _this.generateHarmonics = generateHarmonics;
  86860. _this.useInGammaSpace = useInGammaSpace;
  86861. _this.usePMREMGenerator = usePMREMGenerator;
  86862. return _this;
  86863. }
  86864. /**
  86865. * Execute the current task
  86866. * @param scene defines the scene where you want your assets to be loaded
  86867. * @param onSuccess is a callback called when the task is successfully executed
  86868. * @param onError is a callback called if an error occurs
  86869. */
  86870. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86871. var onload = function () {
  86872. onSuccess();
  86873. };
  86874. var onerror = function (message, exception) {
  86875. onError(message, exception);
  86876. };
  86877. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86878. };
  86879. return HDRCubeTextureAssetTask;
  86880. }(AbstractAssetTask));
  86881. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86882. /**
  86883. * This class can be used to easily import assets into a scene
  86884. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86885. */
  86886. var AssetsManager = /** @class */ (function () {
  86887. /**
  86888. * Creates a new AssetsManager
  86889. * @param scene defines the scene to work on
  86890. */
  86891. function AssetsManager(scene) {
  86892. this._isLoading = false;
  86893. this._tasks = new Array();
  86894. this._waitingTasksCount = 0;
  86895. this._totalTasksCount = 0;
  86896. /**
  86897. * Observable called when all tasks are processed
  86898. */
  86899. this.onTaskSuccessObservable = new BABYLON.Observable();
  86900. /**
  86901. * Observable called when a task had an error
  86902. */
  86903. this.onTaskErrorObservable = new BABYLON.Observable();
  86904. /**
  86905. * Observable called when a task is successful
  86906. */
  86907. this.onTasksDoneObservable = new BABYLON.Observable();
  86908. /**
  86909. * Observable called when a task is done (whatever the result is)
  86910. */
  86911. this.onProgressObservable = new BABYLON.Observable();
  86912. /**
  86913. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86914. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86915. */
  86916. this.useDefaultLoadingScreen = true;
  86917. this._scene = scene;
  86918. }
  86919. /**
  86920. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86921. * @param taskName defines the name of the new task
  86922. * @param meshesNames defines the name of meshes to load
  86923. * @param rootUrl defines the root url to use to locate files
  86924. * @param sceneFilename defines the filename of the scene file
  86925. * @returns a new {BABYLON.MeshAssetTask} object
  86926. */
  86927. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86928. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86929. this._tasks.push(task);
  86930. return task;
  86931. };
  86932. /**
  86933. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86934. * @param taskName defines the name of the new task
  86935. * @param url defines the url of the file to load
  86936. * @returns a new {BABYLON.TextFileAssetTask} object
  86937. */
  86938. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86939. var task = new TextFileAssetTask(taskName, url);
  86940. this._tasks.push(task);
  86941. return task;
  86942. };
  86943. /**
  86944. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86945. * @param taskName defines the name of the new task
  86946. * @param url defines the url of the file to load
  86947. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86948. */
  86949. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86950. var task = new BinaryFileAssetTask(taskName, url);
  86951. this._tasks.push(task);
  86952. return task;
  86953. };
  86954. /**
  86955. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86956. * @param taskName defines the name of the new task
  86957. * @param url defines the url of the file to load
  86958. * @returns a new {BABYLON.ImageAssetTask} object
  86959. */
  86960. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86961. var task = new ImageAssetTask(taskName, url);
  86962. this._tasks.push(task);
  86963. return task;
  86964. };
  86965. /**
  86966. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86967. * @param taskName defines the name of the new task
  86968. * @param url defines the url of the file to load
  86969. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86970. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86971. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86972. * @returns a new {BABYLON.TextureAssetTask} object
  86973. */
  86974. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86976. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86977. this._tasks.push(task);
  86978. return task;
  86979. };
  86980. /**
  86981. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86982. * @param taskName defines the name of the new task
  86983. * @param url defines the url of the file to load
  86984. * @param extensions defines the extension to use to load the cube map (can be null)
  86985. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86986. * @param files defines the list of files to load (can be null)
  86987. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86988. */
  86989. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86990. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86991. this._tasks.push(task);
  86992. return task;
  86993. };
  86994. /**
  86995. *
  86996. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86997. * @param taskName defines the name of the new task
  86998. * @param url defines the url of the file to load
  86999. * @param size defines the size you want for the cubemap (can be null)
  87000. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87001. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87002. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87003. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87004. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87005. */
  87006. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87007. if (noMipmap === void 0) { noMipmap = false; }
  87008. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87009. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87010. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87011. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87012. this._tasks.push(task);
  87013. return task;
  87014. };
  87015. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87016. var _this = this;
  87017. this._waitingTasksCount--;
  87018. try {
  87019. if (task.taskState === AssetTaskState.DONE) {
  87020. // Let's remove successfull tasks
  87021. BABYLON.Tools.SetImmediate(function () {
  87022. var index = _this._tasks.indexOf(task);
  87023. if (index > -1) {
  87024. _this._tasks.splice(index, 1);
  87025. }
  87026. });
  87027. }
  87028. if (this.onProgress) {
  87029. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87030. }
  87031. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87032. }
  87033. catch (e) {
  87034. BABYLON.Tools.Error("Error running progress callbacks.");
  87035. console.log(e);
  87036. }
  87037. if (this._waitingTasksCount === 0) {
  87038. try {
  87039. if (this.onFinish) {
  87040. this.onFinish(this._tasks);
  87041. }
  87042. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87043. }
  87044. catch (e) {
  87045. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87046. console.log(e);
  87047. }
  87048. this._isLoading = false;
  87049. this._scene.getEngine().hideLoadingUI();
  87050. }
  87051. };
  87052. AssetsManager.prototype._runTask = function (task) {
  87053. var _this = this;
  87054. var done = function () {
  87055. try {
  87056. if (_this.onTaskSuccess) {
  87057. _this.onTaskSuccess(task);
  87058. }
  87059. _this.onTaskSuccessObservable.notifyObservers(task);
  87060. _this._decreaseWaitingTasksCount(task);
  87061. }
  87062. catch (e) {
  87063. error("Error executing task success callbacks", e);
  87064. }
  87065. };
  87066. var error = function (message, exception) {
  87067. task._setErrorObject(message, exception);
  87068. if (_this.onTaskError) {
  87069. _this.onTaskError(task);
  87070. }
  87071. _this.onTaskErrorObservable.notifyObservers(task);
  87072. _this._decreaseWaitingTasksCount(task);
  87073. };
  87074. task.run(this._scene, done, error);
  87075. };
  87076. /**
  87077. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87078. * @return the current instance of the {BABYLON.AssetsManager}
  87079. */
  87080. AssetsManager.prototype.reset = function () {
  87081. this._isLoading = false;
  87082. this._tasks = new Array();
  87083. return this;
  87084. };
  87085. /**
  87086. * Start the loading process
  87087. * @return the current instance of the {BABYLON.AssetsManager}
  87088. */
  87089. AssetsManager.prototype.load = function () {
  87090. if (this._isLoading) {
  87091. return this;
  87092. }
  87093. this._isLoading = true;
  87094. this._waitingTasksCount = this._tasks.length;
  87095. this._totalTasksCount = this._tasks.length;
  87096. if (this._waitingTasksCount === 0) {
  87097. this._isLoading = false;
  87098. if (this.onFinish) {
  87099. this.onFinish(this._tasks);
  87100. }
  87101. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87102. return this;
  87103. }
  87104. if (this.useDefaultLoadingScreen) {
  87105. this._scene.getEngine().displayLoadingUI();
  87106. }
  87107. for (var index = 0; index < this._tasks.length; index++) {
  87108. var task = this._tasks[index];
  87109. this._runTask(task);
  87110. }
  87111. return this;
  87112. };
  87113. return AssetsManager;
  87114. }());
  87115. BABYLON.AssetsManager = AssetsManager;
  87116. })(BABYLON || (BABYLON = {}));
  87117. //# sourceMappingURL=babylon.assetsManager.js.map
  87118. var BABYLON;
  87119. (function (BABYLON) {
  87120. var serializedGeometries = [];
  87121. var serializeGeometry = function (geometry, serializationGeometries) {
  87122. if (serializedGeometries[geometry.id]) {
  87123. return;
  87124. }
  87125. if (geometry.doNotSerialize) {
  87126. return;
  87127. }
  87128. if (geometry instanceof BABYLON.BoxGeometry) {
  87129. serializationGeometries.boxes.push(geometry.serialize());
  87130. }
  87131. else if (geometry instanceof BABYLON.SphereGeometry) {
  87132. serializationGeometries.spheres.push(geometry.serialize());
  87133. }
  87134. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87135. serializationGeometries.cylinders.push(geometry.serialize());
  87136. }
  87137. else if (geometry instanceof BABYLON.TorusGeometry) {
  87138. serializationGeometries.toruses.push(geometry.serialize());
  87139. }
  87140. else if (geometry instanceof BABYLON.GroundGeometry) {
  87141. serializationGeometries.grounds.push(geometry.serialize());
  87142. }
  87143. else if (geometry instanceof BABYLON.Plane) {
  87144. serializationGeometries.planes.push(geometry.serialize());
  87145. }
  87146. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87147. serializationGeometries.torusKnots.push(geometry.serialize());
  87148. }
  87149. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87150. throw new Error("Unknown primitive type");
  87151. }
  87152. else {
  87153. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87154. }
  87155. serializedGeometries[geometry.id] = true;
  87156. };
  87157. var serializeMesh = function (mesh, serializationScene) {
  87158. var serializationObject = {};
  87159. // Geometry
  87160. var geometry = mesh._geometry;
  87161. if (geometry) {
  87162. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87163. // 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
  87164. serializeGeometry(geometry, serializationScene.geometries);
  87165. }
  87166. }
  87167. // Custom
  87168. if (mesh.serialize) {
  87169. mesh.serialize(serializationObject);
  87170. }
  87171. return serializationObject;
  87172. };
  87173. var finalizeSingleMesh = function (mesh, serializationObject) {
  87174. //only works if the mesh is already loaded
  87175. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87176. //serialize material
  87177. if (mesh.material) {
  87178. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87179. serializationObject.materials = serializationObject.materials || [];
  87180. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87181. serializationObject.materials.push(mesh.material.serialize());
  87182. }
  87183. }
  87184. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87185. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87186. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87187. serializationObject.multiMaterials.push(mesh.material.serialize());
  87188. }
  87189. }
  87190. }
  87191. //serialize geometry
  87192. var geometry = mesh._geometry;
  87193. if (geometry) {
  87194. if (!serializationObject.geometries) {
  87195. serializationObject.geometries = {};
  87196. serializationObject.geometries.boxes = [];
  87197. serializationObject.geometries.spheres = [];
  87198. serializationObject.geometries.cylinders = [];
  87199. serializationObject.geometries.toruses = [];
  87200. serializationObject.geometries.grounds = [];
  87201. serializationObject.geometries.planes = [];
  87202. serializationObject.geometries.torusKnots = [];
  87203. serializationObject.geometries.vertexData = [];
  87204. }
  87205. serializeGeometry(geometry, serializationObject.geometries);
  87206. }
  87207. // Skeletons
  87208. if (mesh.skeleton) {
  87209. serializationObject.skeletons = serializationObject.skeletons || [];
  87210. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87211. }
  87212. //serialize the actual mesh
  87213. serializationObject.meshes = serializationObject.meshes || [];
  87214. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87215. }
  87216. };
  87217. var SceneSerializer = /** @class */ (function () {
  87218. function SceneSerializer() {
  87219. }
  87220. SceneSerializer.ClearCache = function () {
  87221. serializedGeometries = [];
  87222. };
  87223. SceneSerializer.Serialize = function (scene) {
  87224. var serializationObject = {};
  87225. SceneSerializer.ClearCache();
  87226. // Scene
  87227. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87228. serializationObject.autoClear = scene.autoClear;
  87229. serializationObject.clearColor = scene.clearColor.asArray();
  87230. serializationObject.ambientColor = scene.ambientColor.asArray();
  87231. serializationObject.gravity = scene.gravity.asArray();
  87232. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87233. serializationObject.workerCollisions = scene.workerCollisions;
  87234. // Fog
  87235. if (scene.fogMode && scene.fogMode !== 0) {
  87236. serializationObject.fogMode = scene.fogMode;
  87237. serializationObject.fogColor = scene.fogColor.asArray();
  87238. serializationObject.fogStart = scene.fogStart;
  87239. serializationObject.fogEnd = scene.fogEnd;
  87240. serializationObject.fogDensity = scene.fogDensity;
  87241. }
  87242. //Physics
  87243. if (scene.isPhysicsEnabled()) {
  87244. var physicEngine = scene.getPhysicsEngine();
  87245. if (physicEngine) {
  87246. serializationObject.physicsEnabled = true;
  87247. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87248. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87249. }
  87250. }
  87251. // Metadata
  87252. if (scene.metadata) {
  87253. serializationObject.metadata = scene.metadata;
  87254. }
  87255. // Morph targets
  87256. serializationObject.morphTargetManagers = [];
  87257. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87258. var abstractMesh = _a[_i];
  87259. var manager = abstractMesh.morphTargetManager;
  87260. if (manager) {
  87261. serializationObject.morphTargetManagers.push(manager.serialize());
  87262. }
  87263. }
  87264. // Lights
  87265. serializationObject.lights = [];
  87266. var index;
  87267. var light;
  87268. for (index = 0; index < scene.lights.length; index++) {
  87269. light = scene.lights[index];
  87270. if (!light.doNotSerialize) {
  87271. serializationObject.lights.push(light.serialize());
  87272. }
  87273. }
  87274. // Cameras
  87275. serializationObject.cameras = [];
  87276. for (index = 0; index < scene.cameras.length; index++) {
  87277. var camera = scene.cameras[index];
  87278. if (!camera.doNotSerialize) {
  87279. serializationObject.cameras.push(camera.serialize());
  87280. }
  87281. }
  87282. if (scene.activeCamera) {
  87283. serializationObject.activeCameraID = scene.activeCamera.id;
  87284. }
  87285. // Animations
  87286. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87287. // Materials
  87288. serializationObject.materials = [];
  87289. serializationObject.multiMaterials = [];
  87290. var material;
  87291. for (index = 0; index < scene.materials.length; index++) {
  87292. material = scene.materials[index];
  87293. if (!material.doNotSerialize) {
  87294. serializationObject.materials.push(material.serialize());
  87295. }
  87296. }
  87297. // MultiMaterials
  87298. serializationObject.multiMaterials = [];
  87299. for (index = 0; index < scene.multiMaterials.length; index++) {
  87300. var multiMaterial = scene.multiMaterials[index];
  87301. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87302. }
  87303. // Environment texture
  87304. if (scene.environmentTexture) {
  87305. serializationObject.environmentTexture = scene.environmentTexture.name;
  87306. }
  87307. // Skeletons
  87308. serializationObject.skeletons = [];
  87309. for (index = 0; index < scene.skeletons.length; index++) {
  87310. var skeleton = scene.skeletons[index];
  87311. if (!skeleton.doNotSerialize) {
  87312. serializationObject.skeletons.push(skeleton.serialize());
  87313. }
  87314. }
  87315. // Transform nodes
  87316. serializationObject.transformNodes = [];
  87317. for (index = 0; index < scene.transformNodes.length; index++) {
  87318. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87319. }
  87320. // Geometries
  87321. serializationObject.geometries = {};
  87322. serializationObject.geometries.boxes = [];
  87323. serializationObject.geometries.spheres = [];
  87324. serializationObject.geometries.cylinders = [];
  87325. serializationObject.geometries.toruses = [];
  87326. serializationObject.geometries.grounds = [];
  87327. serializationObject.geometries.planes = [];
  87328. serializationObject.geometries.torusKnots = [];
  87329. serializationObject.geometries.vertexData = [];
  87330. serializedGeometries = [];
  87331. var geometries = scene.getGeometries();
  87332. for (index = 0; index < geometries.length; index++) {
  87333. var geometry = geometries[index];
  87334. if (geometry.isReady()) {
  87335. serializeGeometry(geometry, serializationObject.geometries);
  87336. }
  87337. }
  87338. // Meshes
  87339. serializationObject.meshes = [];
  87340. for (index = 0; index < scene.meshes.length; index++) {
  87341. var abstractMesh = scene.meshes[index];
  87342. if (abstractMesh instanceof BABYLON.Mesh) {
  87343. var mesh = abstractMesh;
  87344. if (!mesh.doNotSerialize) {
  87345. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87346. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87347. }
  87348. }
  87349. }
  87350. }
  87351. // Particles Systems
  87352. serializationObject.particleSystems = [];
  87353. for (index = 0; index < scene.particleSystems.length; index++) {
  87354. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87355. }
  87356. // Lens flares
  87357. serializationObject.lensFlareSystems = [];
  87358. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87359. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87360. }
  87361. // Shadows
  87362. serializationObject.shadowGenerators = [];
  87363. for (index = 0; index < scene.lights.length; index++) {
  87364. light = scene.lights[index];
  87365. var shadowGenerator = light.getShadowGenerator();
  87366. if (shadowGenerator) {
  87367. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87368. }
  87369. }
  87370. // Action Manager
  87371. if (scene.actionManager) {
  87372. serializationObject.actions = scene.actionManager.serialize("scene");
  87373. }
  87374. // Audio
  87375. serializationObject.sounds = [];
  87376. for (index = 0; index < scene.soundTracks.length; index++) {
  87377. var soundtrack = scene.soundTracks[index];
  87378. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87379. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87380. }
  87381. }
  87382. return serializationObject;
  87383. };
  87384. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87385. if (withParents === void 0) { withParents = false; }
  87386. if (withChildren === void 0) { withChildren = false; }
  87387. var serializationObject = {};
  87388. SceneSerializer.ClearCache();
  87389. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87390. if (withParents || withChildren) {
  87391. //deliberate for loop! not for each, appended should be processed as well.
  87392. for (var i = 0; i < toSerialize.length; ++i) {
  87393. if (withChildren) {
  87394. toSerialize[i].getDescendants().forEach(function (node) {
  87395. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87396. toSerialize.push(node);
  87397. }
  87398. });
  87399. }
  87400. //make sure the array doesn't contain the object already
  87401. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87402. toSerialize.push(toSerialize[i].parent);
  87403. }
  87404. }
  87405. }
  87406. toSerialize.forEach(function (mesh) {
  87407. finalizeSingleMesh(mesh, serializationObject);
  87408. });
  87409. return serializationObject;
  87410. };
  87411. return SceneSerializer;
  87412. }());
  87413. BABYLON.SceneSerializer = SceneSerializer;
  87414. })(BABYLON || (BABYLON = {}));
  87415. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87416. var BABYLON;
  87417. (function (BABYLON) {
  87418. var ReflectionProbe = /** @class */ (function () {
  87419. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87420. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87421. var _this = this;
  87422. this.name = name;
  87423. this._viewMatrix = BABYLON.Matrix.Identity();
  87424. this._target = BABYLON.Vector3.Zero();
  87425. this._add = BABYLON.Vector3.Zero();
  87426. this._invertYAxis = false;
  87427. this.position = BABYLON.Vector3.Zero();
  87428. this._scene = scene;
  87429. this._scene.reflectionProbes.push(this);
  87430. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87431. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87432. switch (faceIndex) {
  87433. case 0:
  87434. _this._add.copyFromFloats(1, 0, 0);
  87435. break;
  87436. case 1:
  87437. _this._add.copyFromFloats(-1, 0, 0);
  87438. break;
  87439. case 2:
  87440. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87441. break;
  87442. case 3:
  87443. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87444. break;
  87445. case 4:
  87446. _this._add.copyFromFloats(0, 0, 1);
  87447. break;
  87448. case 5:
  87449. _this._add.copyFromFloats(0, 0, -1);
  87450. break;
  87451. }
  87452. if (_this._attachedMesh) {
  87453. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87454. }
  87455. _this.position.addToRef(_this._add, _this._target);
  87456. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87457. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87458. scene._forcedViewPosition = _this.position;
  87459. });
  87460. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87461. scene._forcedViewPosition = null;
  87462. scene.updateTransformMatrix(true);
  87463. });
  87464. if (scene.activeCamera) {
  87465. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87466. }
  87467. }
  87468. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87469. get: function () {
  87470. return this._renderTargetTexture.samples;
  87471. },
  87472. set: function (value) {
  87473. this._renderTargetTexture.samples = value;
  87474. },
  87475. enumerable: true,
  87476. configurable: true
  87477. });
  87478. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87479. get: function () {
  87480. return this._renderTargetTexture.refreshRate;
  87481. },
  87482. set: function (value) {
  87483. this._renderTargetTexture.refreshRate = value;
  87484. },
  87485. enumerable: true,
  87486. configurable: true
  87487. });
  87488. ReflectionProbe.prototype.getScene = function () {
  87489. return this._scene;
  87490. };
  87491. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87492. get: function () {
  87493. return this._renderTargetTexture;
  87494. },
  87495. enumerable: true,
  87496. configurable: true
  87497. });
  87498. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87499. get: function () {
  87500. return this._renderTargetTexture.renderList;
  87501. },
  87502. enumerable: true,
  87503. configurable: true
  87504. });
  87505. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87506. this._attachedMesh = mesh;
  87507. };
  87508. /**
  87509. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87510. *
  87511. * @param renderingGroupId The rendering group id corresponding to its index
  87512. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87513. */
  87514. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87515. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87516. };
  87517. ReflectionProbe.prototype.dispose = function () {
  87518. var index = this._scene.reflectionProbes.indexOf(this);
  87519. if (index !== -1) {
  87520. // Remove from the scene if found
  87521. this._scene.reflectionProbes.splice(index, 1);
  87522. }
  87523. if (this._renderTargetTexture) {
  87524. this._renderTargetTexture.dispose();
  87525. this._renderTargetTexture = null;
  87526. }
  87527. };
  87528. return ReflectionProbe;
  87529. }());
  87530. BABYLON.ReflectionProbe = ReflectionProbe;
  87531. })(BABYLON || (BABYLON = {}));
  87532. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87533. var BABYLON;
  87534. (function (BABYLON) {
  87535. var Layer = /** @class */ (function () {
  87536. function Layer(name, imgUrl, scene, isBackground, color) {
  87537. this.name = name;
  87538. this.scale = new BABYLON.Vector2(1, 1);
  87539. this.offset = new BABYLON.Vector2(0, 0);
  87540. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87541. this.layerMask = 0x0FFFFFFF;
  87542. this._vertexBuffers = {};
  87543. // Events
  87544. /**
  87545. * An event triggered when the layer is disposed.
  87546. * @type {BABYLON.Observable}
  87547. */
  87548. this.onDisposeObservable = new BABYLON.Observable();
  87549. /**
  87550. * An event triggered before rendering the scene
  87551. * @type {BABYLON.Observable}
  87552. */
  87553. this.onBeforeRenderObservable = new BABYLON.Observable();
  87554. /**
  87555. * An event triggered after rendering the scene
  87556. * @type {BABYLON.Observable}
  87557. */
  87558. this.onAfterRenderObservable = new BABYLON.Observable();
  87559. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87560. this.isBackground = isBackground === undefined ? true : isBackground;
  87561. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87562. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87563. this._scene.layers.push(this);
  87564. var engine = this._scene.getEngine();
  87565. // VBO
  87566. var vertices = [];
  87567. vertices.push(1, 1);
  87568. vertices.push(-1, 1);
  87569. vertices.push(-1, -1);
  87570. vertices.push(1, -1);
  87571. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87572. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87573. this._createIndexBuffer();
  87574. // Effects
  87575. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87576. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87577. }
  87578. Object.defineProperty(Layer.prototype, "onDispose", {
  87579. set: function (callback) {
  87580. if (this._onDisposeObserver) {
  87581. this.onDisposeObservable.remove(this._onDisposeObserver);
  87582. }
  87583. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87584. },
  87585. enumerable: true,
  87586. configurable: true
  87587. });
  87588. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87589. set: function (callback) {
  87590. if (this._onBeforeRenderObserver) {
  87591. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87592. }
  87593. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87594. },
  87595. enumerable: true,
  87596. configurable: true
  87597. });
  87598. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87599. set: function (callback) {
  87600. if (this._onAfterRenderObserver) {
  87601. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87602. }
  87603. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87604. },
  87605. enumerable: true,
  87606. configurable: true
  87607. });
  87608. Layer.prototype._createIndexBuffer = function () {
  87609. var engine = this._scene.getEngine();
  87610. // Indices
  87611. var indices = [];
  87612. indices.push(0);
  87613. indices.push(1);
  87614. indices.push(2);
  87615. indices.push(0);
  87616. indices.push(2);
  87617. indices.push(3);
  87618. this._indexBuffer = engine.createIndexBuffer(indices);
  87619. };
  87620. Layer.prototype._rebuild = function () {
  87621. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87622. if (vb) {
  87623. vb._rebuild();
  87624. }
  87625. this._createIndexBuffer();
  87626. };
  87627. Layer.prototype.render = function () {
  87628. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87629. // Check
  87630. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87631. return;
  87632. var engine = this._scene.getEngine();
  87633. this.onBeforeRenderObservable.notifyObservers(this);
  87634. // Render
  87635. engine.enableEffect(currentEffect);
  87636. engine.setState(false);
  87637. // Texture
  87638. currentEffect.setTexture("textureSampler", this.texture);
  87639. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87640. // Color
  87641. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87642. // Scale / offset
  87643. currentEffect.setVector2("offset", this.offset);
  87644. currentEffect.setVector2("scale", this.scale);
  87645. // VBOs
  87646. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87647. // Draw order
  87648. if (!this.alphaTest) {
  87649. engine.setAlphaMode(this.alphaBlendingMode);
  87650. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87651. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87652. }
  87653. else {
  87654. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87655. }
  87656. this.onAfterRenderObservable.notifyObservers(this);
  87657. };
  87658. Layer.prototype.dispose = function () {
  87659. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87660. if (vertexBuffer) {
  87661. vertexBuffer.dispose();
  87662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87663. }
  87664. if (this._indexBuffer) {
  87665. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87666. this._indexBuffer = null;
  87667. }
  87668. if (this.texture) {
  87669. this.texture.dispose();
  87670. this.texture = null;
  87671. }
  87672. // Remove from scene
  87673. var index = this._scene.layers.indexOf(this);
  87674. this._scene.layers.splice(index, 1);
  87675. // Callback
  87676. this.onDisposeObservable.notifyObservers(this);
  87677. this.onDisposeObservable.clear();
  87678. this.onAfterRenderObservable.clear();
  87679. this.onBeforeRenderObservable.clear();
  87680. };
  87681. return Layer;
  87682. }());
  87683. BABYLON.Layer = Layer;
  87684. })(BABYLON || (BABYLON = {}));
  87685. //# sourceMappingURL=babylon.layer.js.map
  87686. var BABYLON;
  87687. (function (BABYLON) {
  87688. var TextureTools = /** @class */ (function () {
  87689. function TextureTools() {
  87690. }
  87691. /**
  87692. * Uses the GPU to create a copy texture rescaled at a given size
  87693. * @param texture Texture to copy from
  87694. * @param width Desired width
  87695. * @param height Desired height
  87696. * @return Generated texture
  87697. */
  87698. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87699. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87700. var scene = texture.getScene();
  87701. var engine = scene.getEngine();
  87702. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87703. rtt.wrapU = texture.wrapU;
  87704. rtt.wrapV = texture.wrapV;
  87705. rtt.uOffset = texture.uOffset;
  87706. rtt.vOffset = texture.vOffset;
  87707. rtt.uScale = texture.uScale;
  87708. rtt.vScale = texture.vScale;
  87709. rtt.uAng = texture.uAng;
  87710. rtt.vAng = texture.vAng;
  87711. rtt.wAng = texture.wAng;
  87712. rtt.coordinatesIndex = texture.coordinatesIndex;
  87713. rtt.level = texture.level;
  87714. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87715. rtt._texture.isReady = false;
  87716. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87717. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87718. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87719. passPostProcess.getEffect().executeWhenCompiled(function () {
  87720. passPostProcess.onApply = function (effect) {
  87721. effect.setTexture("textureSampler", texture);
  87722. };
  87723. var internalTexture = rtt.getInternalTexture();
  87724. if (internalTexture) {
  87725. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87726. engine.unBindFramebuffer(internalTexture);
  87727. rtt.disposeFramebufferObjects();
  87728. passPostProcess.dispose();
  87729. internalTexture.isReady = true;
  87730. }
  87731. });
  87732. return rtt;
  87733. };
  87734. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87735. if (!scene._environmentBRDFTexture) {
  87736. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87737. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87738. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87739. scene._environmentBRDFTexture = texture;
  87740. }
  87741. return scene._environmentBRDFTexture;
  87742. };
  87743. 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=";
  87744. return TextureTools;
  87745. }());
  87746. BABYLON.TextureTools = TextureTools;
  87747. })(BABYLON || (BABYLON = {}));
  87748. //# sourceMappingURL=babylon.textureTools.js.map
  87749. var BABYLON;
  87750. (function (BABYLON) {
  87751. var FramingBehavior = /** @class */ (function () {
  87752. function FramingBehavior() {
  87753. this._mode = FramingBehavior.FitFrustumSidesMode;
  87754. this._radiusScale = 1.0;
  87755. this._positionScale = 0.5;
  87756. this._defaultElevation = 0.3;
  87757. this._elevationReturnTime = 1500;
  87758. this._elevationReturnWaitTime = 1000;
  87759. this._zoomStopsAnimation = false;
  87760. this._framingTime = 1500;
  87761. this._isPointerDown = false;
  87762. this._lastInteractionTime = -Infinity;
  87763. // Framing control
  87764. this._animatables = new Array();
  87765. this._betaIsAnimating = false;
  87766. }
  87767. Object.defineProperty(FramingBehavior.prototype, "name", {
  87768. get: function () {
  87769. return "Framing";
  87770. },
  87771. enumerable: true,
  87772. configurable: true
  87773. });
  87774. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87775. /**
  87776. * Gets current mode used by the behavior.
  87777. */
  87778. get: function () {
  87779. return this._mode;
  87780. },
  87781. /**
  87782. * Sets the current mode used by the behavior
  87783. */
  87784. set: function (mode) {
  87785. this._mode = mode;
  87786. },
  87787. enumerable: true,
  87788. configurable: true
  87789. });
  87790. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87791. /**
  87792. * Gets the scale applied to the radius
  87793. */
  87794. get: function () {
  87795. return this._radiusScale;
  87796. },
  87797. /**
  87798. * Sets the scale applied to the radius (1 by default)
  87799. */
  87800. set: function (radius) {
  87801. this._radiusScale = radius;
  87802. },
  87803. enumerable: true,
  87804. configurable: true
  87805. });
  87806. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87807. /**
  87808. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87809. */
  87810. get: function () {
  87811. return this._positionScale;
  87812. },
  87813. /**
  87814. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87815. */
  87816. set: function (scale) {
  87817. this._positionScale = scale;
  87818. },
  87819. enumerable: true,
  87820. configurable: true
  87821. });
  87822. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87823. /**
  87824. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87825. * behaviour is triggered, in radians.
  87826. */
  87827. get: function () {
  87828. return this._defaultElevation;
  87829. },
  87830. /**
  87831. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87832. * behaviour is triggered, in radians.
  87833. */
  87834. set: function (elevation) {
  87835. this._defaultElevation = elevation;
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87841. /**
  87842. * Gets the time (in milliseconds) taken to return to the default beta position.
  87843. * Negative value indicates camera should not return to default.
  87844. */
  87845. get: function () {
  87846. return this._elevationReturnTime;
  87847. },
  87848. /**
  87849. * Sets the time (in milliseconds) taken to return to the default beta position.
  87850. * Negative value indicates camera should not return to default.
  87851. */
  87852. set: function (speed) {
  87853. this._elevationReturnTime = speed;
  87854. },
  87855. enumerable: true,
  87856. configurable: true
  87857. });
  87858. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87859. /**
  87860. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87861. */
  87862. get: function () {
  87863. return this._elevationReturnWaitTime;
  87864. },
  87865. /**
  87866. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87867. */
  87868. set: function (time) {
  87869. this._elevationReturnWaitTime = time;
  87870. },
  87871. enumerable: true,
  87872. configurable: true
  87873. });
  87874. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87875. /**
  87876. * Gets the flag that indicates if user zooming should stop animation.
  87877. */
  87878. get: function () {
  87879. return this._zoomStopsAnimation;
  87880. },
  87881. /**
  87882. * Sets the flag that indicates if user zooming should stop animation.
  87883. */
  87884. set: function (flag) {
  87885. this._zoomStopsAnimation = flag;
  87886. },
  87887. enumerable: true,
  87888. configurable: true
  87889. });
  87890. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87891. /**
  87892. * Gets the transition time when framing the mesh, in milliseconds
  87893. */
  87894. get: function () {
  87895. return this._framingTime;
  87896. },
  87897. /**
  87898. * Sets the transition time when framing the mesh, in milliseconds
  87899. */
  87900. set: function (time) {
  87901. this._framingTime = time;
  87902. },
  87903. enumerable: true,
  87904. configurable: true
  87905. });
  87906. FramingBehavior.prototype.init = function () {
  87907. // Do notihng
  87908. };
  87909. FramingBehavior.prototype.attach = function (camera) {
  87910. var _this = this;
  87911. this._attachedCamera = camera;
  87912. var scene = this._attachedCamera.getScene();
  87913. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87914. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87915. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87916. _this._isPointerDown = true;
  87917. return;
  87918. }
  87919. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87920. _this._isPointerDown = false;
  87921. }
  87922. });
  87923. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87924. if (mesh) {
  87925. _this.zoomOnMesh(mesh);
  87926. }
  87927. });
  87928. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87929. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87930. _this._applyUserInteraction();
  87931. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87932. // back to the default position after a given timeout
  87933. _this._maintainCameraAboveGround();
  87934. });
  87935. };
  87936. FramingBehavior.prototype.detach = function () {
  87937. if (!this._attachedCamera) {
  87938. return;
  87939. }
  87940. var scene = this._attachedCamera.getScene();
  87941. if (this._onPrePointerObservableObserver) {
  87942. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87943. }
  87944. if (this._onAfterCheckInputsObserver) {
  87945. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87946. }
  87947. if (this._onMeshTargetChangedObserver) {
  87948. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87949. }
  87950. this._attachedCamera = null;
  87951. };
  87952. /**
  87953. * Targets the given mesh and updates zoom level accordingly.
  87954. * @param mesh The mesh to target.
  87955. * @param radius Optional. If a cached radius position already exists, overrides default.
  87956. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87957. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87958. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87959. */
  87960. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87961. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87962. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87963. mesh.computeWorldMatrix(true);
  87964. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87965. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87966. };
  87967. /**
  87968. * Targets the given mesh with its children and updates zoom level accordingly.
  87969. * @param mesh The mesh to target.
  87970. * @param radius Optional. If a cached radius position already exists, overrides default.
  87971. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87972. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87973. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87974. */
  87975. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87976. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87977. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87978. mesh.computeWorldMatrix(true);
  87979. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87980. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87981. };
  87982. /**
  87983. * Targets the given meshes with their children and updates zoom level accordingly.
  87984. * @param meshes The mesh to target.
  87985. * @param radius Optional. If a cached radius position already exists, overrides default.
  87986. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87987. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87988. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87989. */
  87990. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87991. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87992. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87993. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87994. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87995. for (var i = 0; i < meshes.length; i++) {
  87996. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87997. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87998. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87999. }
  88000. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88001. };
  88002. /**
  88003. * Targets the given mesh and updates zoom level accordingly.
  88004. * @param mesh The mesh to target.
  88005. * @param radius Optional. If a cached radius position already exists, overrides default.
  88006. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88007. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88008. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88009. */
  88010. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88011. var _this = this;
  88012. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88013. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88014. var zoomTarget;
  88015. if (!this._attachedCamera) {
  88016. return;
  88017. }
  88018. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88019. var bottom = minimumWorld.y;
  88020. var top = maximumWorld.y;
  88021. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88022. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88023. if (focusOnOriginXZ) {
  88024. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88025. }
  88026. else {
  88027. var centerWorld = minimumWorld.add(radiusWorld);
  88028. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88029. }
  88030. if (!this._vectorTransition) {
  88031. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88032. }
  88033. this._betaIsAnimating = true;
  88034. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88035. if (animatable) {
  88036. this._animatables.push(animatable);
  88037. }
  88038. // sets the radius and lower radius bounds
  88039. // Small delta ensures camera is not always at lower zoom limit.
  88040. var radius = 0;
  88041. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88042. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88043. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88044. radius = position;
  88045. }
  88046. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88047. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88048. if (this._attachedCamera.lowerRadiusLimit === null) {
  88049. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88050. }
  88051. }
  88052. // Set sensibilities
  88053. var extend = maximumWorld.subtract(minimumWorld).length();
  88054. this._attachedCamera.panningSensibility = 5000 / extend;
  88055. this._attachedCamera.wheelPrecision = 100 / radius;
  88056. // transition to new radius
  88057. if (!this._radiusTransition) {
  88058. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88059. }
  88060. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88061. _this.stopAllAnimations();
  88062. if (onAnimationEnd) {
  88063. onAnimationEnd();
  88064. }
  88065. if (_this._attachedCamera) {
  88066. _this._attachedCamera.storeState();
  88067. }
  88068. });
  88069. if (animatable) {
  88070. this._animatables.push(animatable);
  88071. }
  88072. };
  88073. /**
  88074. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88075. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88076. * frustum width.
  88077. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88078. * to fully enclose the mesh in the viewing frustum.
  88079. */
  88080. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88081. var size = maximumWorld.subtract(minimumWorld);
  88082. var boxVectorGlobalDiagonal = size.length();
  88083. var frustumSlope = this._getFrustumSlope();
  88084. // Formula for setting distance
  88085. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88086. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88087. // Horizon distance
  88088. var radius = radiusWithoutFraming * this._radiusScale;
  88089. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88090. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88091. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88092. var camera = this._attachedCamera;
  88093. if (!camera) {
  88094. return 0;
  88095. }
  88096. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88097. // Don't exceed the requested limit
  88098. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88099. }
  88100. // Don't exceed the upper radius limit
  88101. if (camera.upperRadiusLimit) {
  88102. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88103. }
  88104. return distance;
  88105. };
  88106. /**
  88107. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88108. * is automatically returned to its default position (expected to be above ground plane).
  88109. */
  88110. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88111. var _this = this;
  88112. if (this._elevationReturnTime < 0) {
  88113. return;
  88114. }
  88115. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88116. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88117. var limitBeta = Math.PI * 0.5;
  88118. // Bring the camera back up if below the ground plane
  88119. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88120. this._betaIsAnimating = true;
  88121. //Transition to new position
  88122. this.stopAllAnimations();
  88123. if (!this._betaTransition) {
  88124. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88125. }
  88126. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88127. _this._clearAnimationLocks();
  88128. _this.stopAllAnimations();
  88129. });
  88130. if (animatabe) {
  88131. this._animatables.push(animatabe);
  88132. }
  88133. }
  88134. };
  88135. /**
  88136. * Returns the frustum slope based on the canvas ratio and camera FOV
  88137. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88138. */
  88139. FramingBehavior.prototype._getFrustumSlope = function () {
  88140. // Calculate the viewport ratio
  88141. // Aspect Ratio is Height/Width.
  88142. var camera = this._attachedCamera;
  88143. if (!camera) {
  88144. return BABYLON.Vector2.Zero();
  88145. }
  88146. var engine = camera.getScene().getEngine();
  88147. var aspectRatio = engine.getAspectRatio(camera);
  88148. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88149. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88150. var frustumSlopeY = Math.tan(camera.fov / 2);
  88151. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88152. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88153. // along the forward vector.
  88154. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88155. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88156. };
  88157. /**
  88158. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88159. */
  88160. FramingBehavior.prototype._clearAnimationLocks = function () {
  88161. this._betaIsAnimating = false;
  88162. };
  88163. /**
  88164. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88165. */
  88166. FramingBehavior.prototype._applyUserInteraction = function () {
  88167. if (this.isUserIsMoving) {
  88168. this._lastInteractionTime = BABYLON.Tools.Now;
  88169. this.stopAllAnimations();
  88170. this._clearAnimationLocks();
  88171. }
  88172. };
  88173. /**
  88174. * Stops and removes all animations that have been applied to the camera
  88175. */
  88176. FramingBehavior.prototype.stopAllAnimations = function () {
  88177. if (this._attachedCamera) {
  88178. this._attachedCamera.animations = [];
  88179. }
  88180. while (this._animatables.length) {
  88181. if (this._animatables[0]) {
  88182. this._animatables[0].onAnimationEnd = null;
  88183. this._animatables[0].stop();
  88184. }
  88185. this._animatables.shift();
  88186. }
  88187. };
  88188. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88189. /**
  88190. * Gets a value indicating if the user is moving the camera
  88191. */
  88192. get: function () {
  88193. if (!this._attachedCamera) {
  88194. return false;
  88195. }
  88196. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88197. this._attachedCamera.inertialBetaOffset !== 0 ||
  88198. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88199. this._attachedCamera.inertialPanningX !== 0 ||
  88200. this._attachedCamera.inertialPanningY !== 0 ||
  88201. this._isPointerDown;
  88202. },
  88203. enumerable: true,
  88204. configurable: true
  88205. });
  88206. /**
  88207. * The easing function used by animations
  88208. */
  88209. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88210. /**
  88211. * The easing mode used by animations
  88212. */
  88213. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88214. // Statics
  88215. /**
  88216. * The camera can move all the way towards the mesh.
  88217. */
  88218. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88219. /**
  88220. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88221. */
  88222. FramingBehavior.FitFrustumSidesMode = 1;
  88223. return FramingBehavior;
  88224. }());
  88225. BABYLON.FramingBehavior = FramingBehavior;
  88226. })(BABYLON || (BABYLON = {}));
  88227. //# sourceMappingURL=babylon.framingBehavior.js.map
  88228. var BABYLON;
  88229. (function (BABYLON) {
  88230. /**
  88231. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88232. */
  88233. var BouncingBehavior = /** @class */ (function () {
  88234. function BouncingBehavior() {
  88235. /**
  88236. * The duration of the animation, in milliseconds
  88237. */
  88238. this.transitionDuration = 450;
  88239. /**
  88240. * Length of the distance animated by the transition when lower radius is reached
  88241. */
  88242. this.lowerRadiusTransitionRange = 2;
  88243. /**
  88244. * Length of the distance animated by the transition when upper radius is reached
  88245. */
  88246. this.upperRadiusTransitionRange = -2;
  88247. this._autoTransitionRange = false;
  88248. // Animations
  88249. this._radiusIsAnimating = false;
  88250. this._radiusBounceTransition = null;
  88251. this._animatables = new Array();
  88252. }
  88253. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88254. get: function () {
  88255. return "Bouncing";
  88256. },
  88257. enumerable: true,
  88258. configurable: true
  88259. });
  88260. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88261. /**
  88262. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88263. */
  88264. get: function () {
  88265. return this._autoTransitionRange;
  88266. },
  88267. /**
  88268. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88269. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88270. */
  88271. set: function (value) {
  88272. var _this = this;
  88273. if (this._autoTransitionRange === value) {
  88274. return;
  88275. }
  88276. this._autoTransitionRange = value;
  88277. var camera = this._attachedCamera;
  88278. if (!camera) {
  88279. return;
  88280. }
  88281. if (value) {
  88282. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88283. if (!mesh) {
  88284. return;
  88285. }
  88286. mesh.computeWorldMatrix(true);
  88287. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88288. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88289. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88290. });
  88291. }
  88292. else if (this._onMeshTargetChangedObserver) {
  88293. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88294. }
  88295. },
  88296. enumerable: true,
  88297. configurable: true
  88298. });
  88299. BouncingBehavior.prototype.init = function () {
  88300. // Do notihng
  88301. };
  88302. BouncingBehavior.prototype.attach = function (camera) {
  88303. var _this = this;
  88304. this._attachedCamera = camera;
  88305. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88306. if (!_this._attachedCamera) {
  88307. return;
  88308. }
  88309. // Add the bounce animation to the lower radius limit
  88310. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88311. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88312. }
  88313. // Add the bounce animation to the upper radius limit
  88314. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88315. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88316. }
  88317. });
  88318. };
  88319. BouncingBehavior.prototype.detach = function () {
  88320. if (!this._attachedCamera) {
  88321. return;
  88322. }
  88323. if (this._onAfterCheckInputsObserver) {
  88324. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88325. }
  88326. if (this._onMeshTargetChangedObserver) {
  88327. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88328. }
  88329. this._attachedCamera = null;
  88330. };
  88331. /**
  88332. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88333. * @param radiusLimit The limit to check against.
  88334. * @return Bool to indicate if at limit.
  88335. */
  88336. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88337. if (!this._attachedCamera) {
  88338. return false;
  88339. }
  88340. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88341. return true;
  88342. }
  88343. return false;
  88344. };
  88345. /**
  88346. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88347. * @param radiusDelta The delta by which to animate to. Can be negative.
  88348. */
  88349. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88350. var _this = this;
  88351. if (!this._attachedCamera) {
  88352. return;
  88353. }
  88354. if (!this._radiusBounceTransition) {
  88355. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88356. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88357. }
  88358. // Prevent zoom until bounce has completed
  88359. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88360. this._attachedCamera.wheelPrecision = Infinity;
  88361. this._attachedCamera.inertialRadiusOffset = 0;
  88362. // Animate to the radius limit
  88363. this.stopAllAnimations();
  88364. this._radiusIsAnimating = true;
  88365. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88366. if (animatable) {
  88367. this._animatables.push(animatable);
  88368. }
  88369. };
  88370. /**
  88371. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88372. */
  88373. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88374. this._radiusIsAnimating = false;
  88375. if (this._attachedCamera) {
  88376. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88377. }
  88378. };
  88379. /**
  88380. * Stops and removes all animations that have been applied to the camera
  88381. */
  88382. BouncingBehavior.prototype.stopAllAnimations = function () {
  88383. if (this._attachedCamera) {
  88384. this._attachedCamera.animations = [];
  88385. }
  88386. while (this._animatables.length) {
  88387. this._animatables[0].onAnimationEnd = null;
  88388. this._animatables[0].stop();
  88389. this._animatables.shift();
  88390. }
  88391. };
  88392. /**
  88393. * The easing function used by animations
  88394. */
  88395. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88396. /**
  88397. * The easing mode used by animations
  88398. */
  88399. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88400. return BouncingBehavior;
  88401. }());
  88402. BABYLON.BouncingBehavior = BouncingBehavior;
  88403. })(BABYLON || (BABYLON = {}));
  88404. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88405. var BABYLON;
  88406. (function (BABYLON) {
  88407. var AutoRotationBehavior = /** @class */ (function () {
  88408. function AutoRotationBehavior() {
  88409. this._zoomStopsAnimation = false;
  88410. this._idleRotationSpeed = 0.05;
  88411. this._idleRotationWaitTime = 2000;
  88412. this._idleRotationSpinupTime = 2000;
  88413. this._isPointerDown = false;
  88414. this._lastFrameTime = null;
  88415. this._lastInteractionTime = -Infinity;
  88416. this._cameraRotationSpeed = 0;
  88417. this._lastFrameRadius = 0;
  88418. }
  88419. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88420. get: function () {
  88421. return "AutoRotation";
  88422. },
  88423. enumerable: true,
  88424. configurable: true
  88425. });
  88426. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88427. /**
  88428. * Gets the flag that indicates if user zooming should stop animation.
  88429. */
  88430. get: function () {
  88431. return this._zoomStopsAnimation;
  88432. },
  88433. /**
  88434. * Sets the flag that indicates if user zooming should stop animation.
  88435. */
  88436. set: function (flag) {
  88437. this._zoomStopsAnimation = flag;
  88438. },
  88439. enumerable: true,
  88440. configurable: true
  88441. });
  88442. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88443. /**
  88444. * Gets the default speed at which the camera rotates around the model.
  88445. */
  88446. get: function () {
  88447. return this._idleRotationSpeed;
  88448. },
  88449. /**
  88450. * Sets the default speed at which the camera rotates around the model.
  88451. */
  88452. set: function (speed) {
  88453. this._idleRotationSpeed = speed;
  88454. },
  88455. enumerable: true,
  88456. configurable: true
  88457. });
  88458. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88459. /**
  88460. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88461. */
  88462. get: function () {
  88463. return this._idleRotationWaitTime;
  88464. },
  88465. /**
  88466. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88467. */
  88468. set: function (time) {
  88469. this._idleRotationWaitTime = time;
  88470. },
  88471. enumerable: true,
  88472. configurable: true
  88473. });
  88474. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88475. /**
  88476. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88477. */
  88478. get: function () {
  88479. return this._idleRotationSpinupTime;
  88480. },
  88481. /**
  88482. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88483. */
  88484. set: function (time) {
  88485. this._idleRotationSpinupTime = time;
  88486. },
  88487. enumerable: true,
  88488. configurable: true
  88489. });
  88490. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88491. /**
  88492. * Gets a value indicating if the camera is currently rotating because of this behavior
  88493. */
  88494. get: function () {
  88495. return Math.abs(this._cameraRotationSpeed) > 0;
  88496. },
  88497. enumerable: true,
  88498. configurable: true
  88499. });
  88500. AutoRotationBehavior.prototype.init = function () {
  88501. // Do notihng
  88502. };
  88503. AutoRotationBehavior.prototype.attach = function (camera) {
  88504. var _this = this;
  88505. this._attachedCamera = camera;
  88506. var scene = this._attachedCamera.getScene();
  88507. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88508. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88509. _this._isPointerDown = true;
  88510. return;
  88511. }
  88512. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88513. _this._isPointerDown = false;
  88514. }
  88515. });
  88516. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88517. var now = BABYLON.Tools.Now;
  88518. var dt = 0;
  88519. if (_this._lastFrameTime != null) {
  88520. dt = now - _this._lastFrameTime;
  88521. }
  88522. _this._lastFrameTime = now;
  88523. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88524. _this._applyUserInteraction();
  88525. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88526. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88527. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88528. // Step camera rotation by rotation speed
  88529. if (_this._attachedCamera) {
  88530. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88531. }
  88532. });
  88533. };
  88534. AutoRotationBehavior.prototype.detach = function () {
  88535. if (!this._attachedCamera) {
  88536. return;
  88537. }
  88538. var scene = this._attachedCamera.getScene();
  88539. if (this._onPrePointerObservableObserver) {
  88540. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88541. }
  88542. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88543. this._attachedCamera = null;
  88544. };
  88545. /**
  88546. * Returns true if user is scrolling.
  88547. * @return true if user is scrolling.
  88548. */
  88549. AutoRotationBehavior.prototype._userIsZooming = function () {
  88550. if (!this._attachedCamera) {
  88551. return false;
  88552. }
  88553. return this._attachedCamera.inertialRadiusOffset !== 0;
  88554. };
  88555. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88556. if (!this._attachedCamera) {
  88557. return false;
  88558. }
  88559. var zoomHasHitLimit = false;
  88560. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88561. zoomHasHitLimit = true;
  88562. }
  88563. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88564. this._lastFrameRadius = this._attachedCamera.radius;
  88565. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88566. };
  88567. /**
  88568. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88569. */
  88570. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88571. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88572. this._lastInteractionTime = BABYLON.Tools.Now;
  88573. }
  88574. };
  88575. // Tools
  88576. AutoRotationBehavior.prototype._userIsMoving = function () {
  88577. if (!this._attachedCamera) {
  88578. return false;
  88579. }
  88580. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88581. this._attachedCamera.inertialBetaOffset !== 0 ||
  88582. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88583. this._attachedCamera.inertialPanningX !== 0 ||
  88584. this._attachedCamera.inertialPanningY !== 0 ||
  88585. this._isPointerDown;
  88586. };
  88587. return AutoRotationBehavior;
  88588. }());
  88589. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88590. })(BABYLON || (BABYLON = {}));
  88591. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88592. var BABYLON;
  88593. (function (BABYLON) {
  88594. var NullEngineOptions = /** @class */ (function () {
  88595. function NullEngineOptions() {
  88596. this.renderWidth = 512;
  88597. this.renderHeight = 256;
  88598. this.textureSize = 512;
  88599. this.deterministicLockstep = false;
  88600. this.lockstepMaxSteps = 4;
  88601. }
  88602. return NullEngineOptions;
  88603. }());
  88604. BABYLON.NullEngineOptions = NullEngineOptions;
  88605. /**
  88606. * The null engine class provides support for headless version of babylon.js.
  88607. * This can be used in server side scenario or for testing purposes
  88608. */
  88609. var NullEngine = /** @class */ (function (_super) {
  88610. __extends(NullEngine, _super);
  88611. function NullEngine(options) {
  88612. if (options === void 0) { options = new NullEngineOptions(); }
  88613. var _this = _super.call(this, null) || this;
  88614. if (options.deterministicLockstep === undefined) {
  88615. options.deterministicLockstep = false;
  88616. }
  88617. if (options.lockstepMaxSteps === undefined) {
  88618. options.lockstepMaxSteps = 4;
  88619. }
  88620. _this._options = options;
  88621. // Init caps
  88622. // We consider we are on a webgl1 capable device
  88623. _this._caps = new BABYLON.EngineCapabilities();
  88624. _this._caps.maxTexturesImageUnits = 16;
  88625. _this._caps.maxVertexTextureImageUnits = 16;
  88626. _this._caps.maxTextureSize = 512;
  88627. _this._caps.maxCubemapTextureSize = 512;
  88628. _this._caps.maxRenderTextureSize = 512;
  88629. _this._caps.maxVertexAttribs = 16;
  88630. _this._caps.maxVaryingVectors = 16;
  88631. _this._caps.maxFragmentUniformVectors = 16;
  88632. _this._caps.maxVertexUniformVectors = 16;
  88633. // Extensions
  88634. _this._caps.standardDerivatives = false;
  88635. _this._caps.astc = null;
  88636. _this._caps.s3tc = null;
  88637. _this._caps.pvrtc = null;
  88638. _this._caps.etc1 = null;
  88639. _this._caps.etc2 = null;
  88640. _this._caps.textureAnisotropicFilterExtension = null;
  88641. _this._caps.maxAnisotropy = 0;
  88642. _this._caps.uintIndices = false;
  88643. _this._caps.fragmentDepthSupported = false;
  88644. _this._caps.highPrecisionShaderSupported = true;
  88645. _this._caps.colorBufferFloat = false;
  88646. _this._caps.textureFloat = false;
  88647. _this._caps.textureFloatLinearFiltering = false;
  88648. _this._caps.textureFloatRender = false;
  88649. _this._caps.textureHalfFloat = false;
  88650. _this._caps.textureHalfFloatLinearFiltering = false;
  88651. _this._caps.textureHalfFloatRender = false;
  88652. _this._caps.textureLOD = false;
  88653. _this._caps.drawBuffersExtension = false;
  88654. _this._caps.depthTextureExtension = false;
  88655. _this._caps.vertexArrayObject = false;
  88656. _this._caps.instancedArrays = false;
  88657. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88658. // Wrappers
  88659. if (typeof URL === "undefined") {
  88660. URL = {
  88661. createObjectURL: function () { },
  88662. revokeObjectURL: function () { }
  88663. };
  88664. }
  88665. if (typeof Blob === "undefined") {
  88666. Blob = function () { };
  88667. }
  88668. return _this;
  88669. }
  88670. NullEngine.prototype.isDeterministicLockStep = function () {
  88671. return this._options.deterministicLockstep;
  88672. };
  88673. NullEngine.prototype.getLockstepMaxSteps = function () {
  88674. return this._options.lockstepMaxSteps;
  88675. };
  88676. NullEngine.prototype.getHardwareScalingLevel = function () {
  88677. return 1.0;
  88678. };
  88679. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88680. return {
  88681. capacity: 0,
  88682. references: 1,
  88683. is32Bits: false
  88684. };
  88685. };
  88686. NullEngine.prototype.createIndexBuffer = function (indices) {
  88687. return {
  88688. capacity: 0,
  88689. references: 1,
  88690. is32Bits: false
  88691. };
  88692. };
  88693. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88694. if (stencil === void 0) { stencil = false; }
  88695. };
  88696. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88697. if (useScreen === void 0) { useScreen = false; }
  88698. if (!useScreen && this._currentRenderTarget) {
  88699. return this._currentRenderTarget.width;
  88700. }
  88701. return this._options.renderWidth;
  88702. };
  88703. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88704. if (useScreen === void 0) { useScreen = false; }
  88705. if (!useScreen && this._currentRenderTarget) {
  88706. return this._currentRenderTarget.height;
  88707. }
  88708. return this._options.renderHeight;
  88709. };
  88710. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88711. this._cachedViewport = viewport;
  88712. };
  88713. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88714. return {
  88715. transformFeedback: null,
  88716. __SPECTOR_rebuildProgram: null
  88717. };
  88718. };
  88719. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88720. return [];
  88721. };
  88722. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88723. return [];
  88724. };
  88725. NullEngine.prototype.bindSamplers = function (effect) {
  88726. this._currentEffect = null;
  88727. };
  88728. NullEngine.prototype.enableEffect = function (effect) {
  88729. this._currentEffect = effect;
  88730. if (effect.onBind) {
  88731. effect.onBind(effect);
  88732. }
  88733. effect.onBindObservable.notifyObservers(effect);
  88734. };
  88735. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88736. if (zOffset === void 0) { zOffset = 0; }
  88737. if (reverseSide === void 0) { reverseSide = false; }
  88738. };
  88739. NullEngine.prototype.setIntArray = function (uniform, array) {
  88740. };
  88741. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88742. };
  88743. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88744. };
  88745. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88746. };
  88747. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88748. };
  88749. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88750. };
  88751. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88752. };
  88753. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88754. };
  88755. NullEngine.prototype.setArray = function (uniform, array) {
  88756. };
  88757. NullEngine.prototype.setArray2 = function (uniform, array) {
  88758. };
  88759. NullEngine.prototype.setArray3 = function (uniform, array) {
  88760. };
  88761. NullEngine.prototype.setArray4 = function (uniform, array) {
  88762. };
  88763. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88764. };
  88765. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88766. };
  88767. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88768. };
  88769. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88770. };
  88771. NullEngine.prototype.setFloat = function (uniform, value) {
  88772. };
  88773. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88774. };
  88775. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88776. };
  88777. NullEngine.prototype.setBool = function (uniform, bool) {
  88778. };
  88779. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88780. };
  88781. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88782. };
  88783. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88784. };
  88785. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88786. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88787. if (this._alphaMode === mode) {
  88788. return;
  88789. }
  88790. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88791. if (!noDepthWriteChange) {
  88792. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88793. }
  88794. this._alphaMode = mode;
  88795. };
  88796. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88797. };
  88798. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88799. if (this.preventCacheWipeBetweenFrames) {
  88800. return;
  88801. }
  88802. this.resetTextureCache();
  88803. this._currentEffect = null;
  88804. if (bruteForce) {
  88805. this._currentProgram = null;
  88806. this._stencilState.reset();
  88807. this._depthCullingState.reset();
  88808. this._alphaState.reset();
  88809. }
  88810. this._cachedVertexBuffers = null;
  88811. this._cachedIndexBuffer = null;
  88812. this._cachedEffectForVertexBuffers = null;
  88813. };
  88814. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88815. };
  88816. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88817. };
  88818. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88819. };
  88820. NullEngine.prototype._createTexture = function () {
  88821. return {};
  88822. };
  88823. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88825. if (onLoad === void 0) { onLoad = null; }
  88826. if (onError === void 0) { onError = null; }
  88827. if (buffer === void 0) { buffer = null; }
  88828. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88829. var url = String(urlArg);
  88830. texture.url = url;
  88831. texture.generateMipMaps = !noMipmap;
  88832. texture.samplingMode = samplingMode;
  88833. texture.invertY = invertY;
  88834. texture.baseWidth = this._options.textureSize;
  88835. texture.baseHeight = this._options.textureSize;
  88836. texture.width = this._options.textureSize;
  88837. texture.height = this._options.textureSize;
  88838. if (format) {
  88839. texture.format = format;
  88840. }
  88841. texture.isReady = true;
  88842. if (onLoad) {
  88843. onLoad();
  88844. }
  88845. return texture;
  88846. };
  88847. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88848. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88849. if (options !== undefined && typeof options === "object") {
  88850. fullOptions.generateMipMaps = options.generateMipMaps;
  88851. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88852. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88853. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88854. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88855. }
  88856. else {
  88857. fullOptions.generateMipMaps = options;
  88858. fullOptions.generateDepthBuffer = true;
  88859. fullOptions.generateStencilBuffer = false;
  88860. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88861. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88862. }
  88863. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88864. var width = size.width || size;
  88865. var height = size.height || size;
  88866. texture._depthStencilBuffer = {};
  88867. texture._framebuffer = {};
  88868. texture.baseWidth = width;
  88869. texture.baseHeight = height;
  88870. texture.width = width;
  88871. texture.height = height;
  88872. texture.isReady = true;
  88873. texture.samples = 1;
  88874. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88875. texture.samplingMode = fullOptions.samplingMode;
  88876. texture.type = fullOptions.type;
  88877. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88878. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88879. return texture;
  88880. };
  88881. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88882. texture.samplingMode = samplingMode;
  88883. };
  88884. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88885. if (this._currentRenderTarget) {
  88886. this.unBindFramebuffer(this._currentRenderTarget);
  88887. }
  88888. this._currentRenderTarget = texture;
  88889. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88890. if (this._cachedViewport && !forceFullscreenViewport) {
  88891. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88892. }
  88893. };
  88894. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88895. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88896. this._currentRenderTarget = null;
  88897. if (onBeforeUnbind) {
  88898. if (texture._MSAAFramebuffer) {
  88899. this._currentFramebuffer = texture._framebuffer;
  88900. }
  88901. onBeforeUnbind();
  88902. }
  88903. this._currentFramebuffer = null;
  88904. };
  88905. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88906. var vbo = {
  88907. capacity: 1,
  88908. references: 1,
  88909. is32Bits: false
  88910. };
  88911. return vbo;
  88912. };
  88913. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88914. if (offset === void 0) { offset = 0; }
  88915. };
  88916. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88917. };
  88918. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88919. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88920. this._boundTexturesCache[this._activeChannel] = texture;
  88921. }
  88922. };
  88923. NullEngine.prototype._bindTexture = function (channel, texture) {
  88924. if (channel < 0) {
  88925. return;
  88926. }
  88927. this._bindTextureDirectly(0, texture);
  88928. };
  88929. NullEngine.prototype._releaseBuffer = function (buffer) {
  88930. buffer.references--;
  88931. if (buffer.references === 0) {
  88932. return true;
  88933. }
  88934. return false;
  88935. };
  88936. return NullEngine;
  88937. }(BABYLON.Engine));
  88938. BABYLON.NullEngine = NullEngine;
  88939. })(BABYLON || (BABYLON = {}));
  88940. //# sourceMappingURL=babylon.nullEngine.js.map
  88941. var BABYLON;
  88942. (function (BABYLON) {
  88943. /**
  88944. * This class can be used to get instrumentation data from a Babylon engine
  88945. */
  88946. var EngineInstrumentation = /** @class */ (function () {
  88947. function EngineInstrumentation(engine) {
  88948. this.engine = engine;
  88949. this._captureGPUFrameTime = false;
  88950. this._gpuFrameTime = new BABYLON.PerfCounter();
  88951. this._captureShaderCompilationTime = false;
  88952. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88953. // Observers
  88954. this._onBeginFrameObserver = null;
  88955. this._onEndFrameObserver = null;
  88956. this._onBeforeShaderCompilationObserver = null;
  88957. this._onAfterShaderCompilationObserver = null;
  88958. }
  88959. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88960. // Properties
  88961. /**
  88962. * Gets the perf counter used for GPU frame time
  88963. */
  88964. get: function () {
  88965. return this._gpuFrameTime;
  88966. },
  88967. enumerable: true,
  88968. configurable: true
  88969. });
  88970. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88971. /**
  88972. * Gets the GPU frame time capture status
  88973. */
  88974. get: function () {
  88975. return this._captureGPUFrameTime;
  88976. },
  88977. /**
  88978. * Enable or disable the GPU frame time capture
  88979. */
  88980. set: function (value) {
  88981. var _this = this;
  88982. if (value === this._captureGPUFrameTime) {
  88983. return;
  88984. }
  88985. this._captureGPUFrameTime = value;
  88986. if (value) {
  88987. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88988. if (!_this._gpuFrameTimeToken) {
  88989. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88990. }
  88991. });
  88992. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88993. if (!_this._gpuFrameTimeToken) {
  88994. return;
  88995. }
  88996. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88997. if (time > -1) {
  88998. _this._gpuFrameTimeToken = null;
  88999. _this._gpuFrameTime.fetchNewFrame();
  89000. _this._gpuFrameTime.addCount(time, true);
  89001. }
  89002. });
  89003. }
  89004. else {
  89005. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89006. this._onBeginFrameObserver = null;
  89007. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89008. this._onEndFrameObserver = null;
  89009. }
  89010. },
  89011. enumerable: true,
  89012. configurable: true
  89013. });
  89014. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89015. /**
  89016. * Gets the perf counter used for shader compilation time
  89017. */
  89018. get: function () {
  89019. return this._shaderCompilationTime;
  89020. },
  89021. enumerable: true,
  89022. configurable: true
  89023. });
  89024. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89025. /**
  89026. * Gets the shader compilation time capture status
  89027. */
  89028. get: function () {
  89029. return this._captureShaderCompilationTime;
  89030. },
  89031. /**
  89032. * Enable or disable the shader compilation time capture
  89033. */
  89034. set: function (value) {
  89035. var _this = this;
  89036. if (value === this._captureShaderCompilationTime) {
  89037. return;
  89038. }
  89039. this._captureShaderCompilationTime = value;
  89040. if (value) {
  89041. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89042. _this._shaderCompilationTime.fetchNewFrame();
  89043. _this._shaderCompilationTime.beginMonitoring();
  89044. });
  89045. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89046. _this._shaderCompilationTime.endMonitoring();
  89047. });
  89048. }
  89049. else {
  89050. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89051. this._onBeforeShaderCompilationObserver = null;
  89052. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89053. this._onAfterShaderCompilationObserver = null;
  89054. }
  89055. },
  89056. enumerable: true,
  89057. configurable: true
  89058. });
  89059. EngineInstrumentation.prototype.dispose = function () {
  89060. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89061. this._onBeginFrameObserver = null;
  89062. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89063. this._onEndFrameObserver = null;
  89064. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89065. this._onBeforeShaderCompilationObserver = null;
  89066. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89067. this._onAfterShaderCompilationObserver = null;
  89068. this.engine = null;
  89069. };
  89070. return EngineInstrumentation;
  89071. }());
  89072. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89073. })(BABYLON || (BABYLON = {}));
  89074. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89075. var BABYLON;
  89076. (function (BABYLON) {
  89077. /**
  89078. * This class can be used to get instrumentation data from a Babylon engine
  89079. */
  89080. var SceneInstrumentation = /** @class */ (function () {
  89081. function SceneInstrumentation(scene) {
  89082. var _this = this;
  89083. this.scene = scene;
  89084. this._captureActiveMeshesEvaluationTime = false;
  89085. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89086. this._captureRenderTargetsRenderTime = false;
  89087. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89088. this._captureFrameTime = false;
  89089. this._frameTime = new BABYLON.PerfCounter();
  89090. this._captureRenderTime = false;
  89091. this._renderTime = new BABYLON.PerfCounter();
  89092. this._captureInterFrameTime = false;
  89093. this._interFrameTime = new BABYLON.PerfCounter();
  89094. this._captureParticlesRenderTime = false;
  89095. this._particlesRenderTime = new BABYLON.PerfCounter();
  89096. this._captureSpritesRenderTime = false;
  89097. this._spritesRenderTime = new BABYLON.PerfCounter();
  89098. this._capturePhysicsTime = false;
  89099. this._physicsTime = new BABYLON.PerfCounter();
  89100. this._captureAnimationsTime = false;
  89101. this._animationsTime = new BABYLON.PerfCounter();
  89102. // Observers
  89103. this._onBeforeActiveMeshesEvaluationObserver = null;
  89104. this._onAfterActiveMeshesEvaluationObserver = null;
  89105. this._onBeforeRenderTargetsRenderObserver = null;
  89106. this._onAfterRenderTargetsRenderObserver = null;
  89107. this._onAfterRenderObserver = null;
  89108. this._onBeforeDrawPhaseObserver = null;
  89109. this._onAfterDrawPhaseObserver = null;
  89110. this._onBeforeAnimationsObserver = null;
  89111. this._onBeforeParticlesRenderingObserver = null;
  89112. this._onAfterParticlesRenderingObserver = null;
  89113. this._onBeforeSpritesRenderingObserver = null;
  89114. this._onAfterSpritesRenderingObserver = null;
  89115. this._onBeforePhysicsObserver = null;
  89116. this._onAfterPhysicsObserver = null;
  89117. this._onAfterAnimationsObserver = null;
  89118. // Before render
  89119. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89120. if (_this._captureActiveMeshesEvaluationTime) {
  89121. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89122. }
  89123. if (_this._captureRenderTargetsRenderTime) {
  89124. _this._renderTargetsRenderTime.fetchNewFrame();
  89125. }
  89126. if (_this._captureFrameTime) {
  89127. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89128. _this._frameTime.beginMonitoring();
  89129. }
  89130. if (_this._captureInterFrameTime) {
  89131. _this._interFrameTime.endMonitoring();
  89132. }
  89133. if (_this._captureParticlesRenderTime) {
  89134. _this._particlesRenderTime.fetchNewFrame();
  89135. }
  89136. if (_this._captureSpritesRenderTime) {
  89137. _this._spritesRenderTime.fetchNewFrame();
  89138. }
  89139. if (_this._captureAnimationsTime) {
  89140. _this._animationsTime.beginMonitoring();
  89141. }
  89142. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89143. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89144. });
  89145. // After render
  89146. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89147. if (_this._captureFrameTime) {
  89148. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89149. _this._frameTime.endMonitoring();
  89150. }
  89151. if (_this._captureRenderTime) {
  89152. _this._renderTime.endMonitoring(false);
  89153. }
  89154. if (_this._captureInterFrameTime) {
  89155. _this._interFrameTime.beginMonitoring();
  89156. }
  89157. });
  89158. }
  89159. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89160. // Properties
  89161. /**
  89162. * Gets the perf counter used for active meshes evaluation time
  89163. */
  89164. get: function () {
  89165. return this._activeMeshesEvaluationTime;
  89166. },
  89167. enumerable: true,
  89168. configurable: true
  89169. });
  89170. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89171. /**
  89172. * Gets the active meshes evaluation time capture status
  89173. */
  89174. get: function () {
  89175. return this._captureActiveMeshesEvaluationTime;
  89176. },
  89177. /**
  89178. * Enable or disable the active meshes evaluation time capture
  89179. */
  89180. set: function (value) {
  89181. var _this = this;
  89182. if (value === this._captureActiveMeshesEvaluationTime) {
  89183. return;
  89184. }
  89185. this._captureActiveMeshesEvaluationTime = value;
  89186. if (value) {
  89187. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89188. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89189. _this._activeMeshesEvaluationTime.beginMonitoring();
  89190. });
  89191. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89192. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89193. _this._activeMeshesEvaluationTime.endMonitoring();
  89194. });
  89195. }
  89196. else {
  89197. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89198. this._onBeforeActiveMeshesEvaluationObserver = null;
  89199. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89200. this._onAfterActiveMeshesEvaluationObserver = null;
  89201. }
  89202. },
  89203. enumerable: true,
  89204. configurable: true
  89205. });
  89206. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89207. /**
  89208. * Gets the perf counter used for render targets render time
  89209. */
  89210. get: function () {
  89211. return this._renderTargetsRenderTime;
  89212. },
  89213. enumerable: true,
  89214. configurable: true
  89215. });
  89216. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89217. /**
  89218. * Gets the render targets render time capture status
  89219. */
  89220. get: function () {
  89221. return this._captureRenderTargetsRenderTime;
  89222. },
  89223. /**
  89224. * Enable or disable the render targets render time capture
  89225. */
  89226. set: function (value) {
  89227. var _this = this;
  89228. if (value === this._captureRenderTargetsRenderTime) {
  89229. return;
  89230. }
  89231. this._captureRenderTargetsRenderTime = value;
  89232. if (value) {
  89233. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89234. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89235. _this._renderTargetsRenderTime.beginMonitoring();
  89236. });
  89237. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89238. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89239. _this._renderTargetsRenderTime.endMonitoring(false);
  89240. });
  89241. }
  89242. else {
  89243. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89244. this._onBeforeRenderTargetsRenderObserver = null;
  89245. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89246. this._onAfterRenderTargetsRenderObserver = null;
  89247. }
  89248. },
  89249. enumerable: true,
  89250. configurable: true
  89251. });
  89252. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89253. /**
  89254. * Gets the perf counter used for particles render time
  89255. */
  89256. get: function () {
  89257. return this._particlesRenderTime;
  89258. },
  89259. enumerable: true,
  89260. configurable: true
  89261. });
  89262. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89263. /**
  89264. * Gets the particles render time capture status
  89265. */
  89266. get: function () {
  89267. return this._captureParticlesRenderTime;
  89268. },
  89269. /**
  89270. * Enable or disable the particles render time capture
  89271. */
  89272. set: function (value) {
  89273. var _this = this;
  89274. if (value === this._captureParticlesRenderTime) {
  89275. return;
  89276. }
  89277. this._captureParticlesRenderTime = value;
  89278. if (value) {
  89279. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89280. BABYLON.Tools.StartPerformanceCounter("Particles");
  89281. _this._particlesRenderTime.beginMonitoring();
  89282. });
  89283. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89284. BABYLON.Tools.EndPerformanceCounter("Particles");
  89285. _this._particlesRenderTime.endMonitoring(false);
  89286. });
  89287. }
  89288. else {
  89289. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89290. this._onBeforeParticlesRenderingObserver = null;
  89291. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89292. this._onAfterParticlesRenderingObserver = null;
  89293. }
  89294. },
  89295. enumerable: true,
  89296. configurable: true
  89297. });
  89298. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89299. /**
  89300. * Gets the perf counter used for sprites render time
  89301. */
  89302. get: function () {
  89303. return this._spritesRenderTime;
  89304. },
  89305. enumerable: true,
  89306. configurable: true
  89307. });
  89308. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89309. /**
  89310. * Gets the sprites render time capture status
  89311. */
  89312. get: function () {
  89313. return this._captureSpritesRenderTime;
  89314. },
  89315. /**
  89316. * Enable or disable the sprites render time capture
  89317. */
  89318. set: function (value) {
  89319. var _this = this;
  89320. if (value === this._captureSpritesRenderTime) {
  89321. return;
  89322. }
  89323. this._captureSpritesRenderTime = value;
  89324. if (value) {
  89325. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89326. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89327. _this._spritesRenderTime.beginMonitoring();
  89328. });
  89329. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89330. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89331. _this._spritesRenderTime.endMonitoring(false);
  89332. });
  89333. }
  89334. else {
  89335. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89336. this._onBeforeSpritesRenderingObserver = null;
  89337. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89338. this._onAfterSpritesRenderingObserver = null;
  89339. }
  89340. },
  89341. enumerable: true,
  89342. configurable: true
  89343. });
  89344. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89345. /**
  89346. * Gets the perf counter used for physics time
  89347. */
  89348. get: function () {
  89349. return this._physicsTime;
  89350. },
  89351. enumerable: true,
  89352. configurable: true
  89353. });
  89354. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89355. /**
  89356. * Gets the physics time capture status
  89357. */
  89358. get: function () {
  89359. return this._capturePhysicsTime;
  89360. },
  89361. /**
  89362. * Enable or disable the physics time capture
  89363. */
  89364. set: function (value) {
  89365. var _this = this;
  89366. if (value === this._capturePhysicsTime) {
  89367. return;
  89368. }
  89369. this._capturePhysicsTime = value;
  89370. if (value) {
  89371. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89372. BABYLON.Tools.StartPerformanceCounter("Physics");
  89373. _this._physicsTime.beginMonitoring();
  89374. });
  89375. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89376. BABYLON.Tools.EndPerformanceCounter("Physics");
  89377. _this._physicsTime.endMonitoring();
  89378. });
  89379. }
  89380. else {
  89381. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89382. this._onBeforePhysicsObserver = null;
  89383. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89384. this._onAfterPhysicsObserver = null;
  89385. }
  89386. },
  89387. enumerable: true,
  89388. configurable: true
  89389. });
  89390. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89391. /**
  89392. * Gets the perf counter used for animations time
  89393. */
  89394. get: function () {
  89395. return this._animationsTime;
  89396. },
  89397. enumerable: true,
  89398. configurable: true
  89399. });
  89400. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89401. /**
  89402. * Gets the animations time capture status
  89403. */
  89404. get: function () {
  89405. return this._captureAnimationsTime;
  89406. },
  89407. /**
  89408. * Enable or disable the animations time capture
  89409. */
  89410. set: function (value) {
  89411. var _this = this;
  89412. if (value === this._captureAnimationsTime) {
  89413. return;
  89414. }
  89415. this._captureAnimationsTime = value;
  89416. if (value) {
  89417. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89418. _this._animationsTime.endMonitoring();
  89419. });
  89420. }
  89421. else {
  89422. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89423. this._onAfterAnimationsObserver = null;
  89424. }
  89425. },
  89426. enumerable: true,
  89427. configurable: true
  89428. });
  89429. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89430. /**
  89431. * Gets the perf counter used for frame time capture
  89432. */
  89433. get: function () {
  89434. return this._frameTime;
  89435. },
  89436. enumerable: true,
  89437. configurable: true
  89438. });
  89439. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89440. /**
  89441. * Gets the frame time capture status
  89442. */
  89443. get: function () {
  89444. return this._captureFrameTime;
  89445. },
  89446. /**
  89447. * Enable or disable the frame time capture
  89448. */
  89449. set: function (value) {
  89450. this._captureFrameTime = value;
  89451. },
  89452. enumerable: true,
  89453. configurable: true
  89454. });
  89455. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89456. /**
  89457. * Gets the perf counter used for inter-frames time capture
  89458. */
  89459. get: function () {
  89460. return this._interFrameTime;
  89461. },
  89462. enumerable: true,
  89463. configurable: true
  89464. });
  89465. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89466. /**
  89467. * Gets the inter-frames time capture status
  89468. */
  89469. get: function () {
  89470. return this._captureInterFrameTime;
  89471. },
  89472. /**
  89473. * Enable or disable the inter-frames time capture
  89474. */
  89475. set: function (value) {
  89476. this._captureInterFrameTime = value;
  89477. },
  89478. enumerable: true,
  89479. configurable: true
  89480. });
  89481. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89482. /**
  89483. * Gets the perf counter used for render time capture
  89484. */
  89485. get: function () {
  89486. return this._renderTime;
  89487. },
  89488. enumerable: true,
  89489. configurable: true
  89490. });
  89491. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89492. /**
  89493. * Gets the render time capture status
  89494. */
  89495. get: function () {
  89496. return this._captureRenderTime;
  89497. },
  89498. /**
  89499. * Enable or disable the render time capture
  89500. */
  89501. set: function (value) {
  89502. var _this = this;
  89503. if (value === this._captureRenderTime) {
  89504. return;
  89505. }
  89506. this._captureRenderTime = value;
  89507. if (value) {
  89508. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89509. _this._renderTime.beginMonitoring();
  89510. BABYLON.Tools.StartPerformanceCounter("Main render");
  89511. });
  89512. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89513. _this._renderTime.endMonitoring(false);
  89514. BABYLON.Tools.EndPerformanceCounter("Main render");
  89515. });
  89516. }
  89517. else {
  89518. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89519. this._onBeforeDrawPhaseObserver = null;
  89520. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89521. this._onAfterDrawPhaseObserver = null;
  89522. }
  89523. },
  89524. enumerable: true,
  89525. configurable: true
  89526. });
  89527. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89528. /**
  89529. * Gets the perf counter used for draw calls
  89530. */
  89531. get: function () {
  89532. return this.scene.getEngine()._drawCalls;
  89533. },
  89534. enumerable: true,
  89535. configurable: true
  89536. });
  89537. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89538. /**
  89539. * Gets the perf counter used for texture collisions
  89540. */
  89541. get: function () {
  89542. return this.scene.getEngine()._textureCollisions;
  89543. },
  89544. enumerable: true,
  89545. configurable: true
  89546. });
  89547. SceneInstrumentation.prototype.dispose = function () {
  89548. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89549. this._onAfterRenderObserver = null;
  89550. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89551. this._onBeforeActiveMeshesEvaluationObserver = null;
  89552. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89553. this._onAfterActiveMeshesEvaluationObserver = null;
  89554. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89555. this._onBeforeRenderTargetsRenderObserver = null;
  89556. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89557. this._onAfterRenderTargetsRenderObserver = null;
  89558. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89559. this._onBeforeAnimationsObserver = null;
  89560. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89561. this._onBeforeParticlesRenderingObserver = null;
  89562. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89563. this._onAfterParticlesRenderingObserver = null;
  89564. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89565. this._onBeforeSpritesRenderingObserver = null;
  89566. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89567. this._onAfterSpritesRenderingObserver = null;
  89568. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89569. this._onBeforeDrawPhaseObserver = null;
  89570. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89571. this._onAfterDrawPhaseObserver = null;
  89572. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89573. this._onBeforePhysicsObserver = null;
  89574. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89575. this._onAfterPhysicsObserver = null;
  89576. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89577. this._onAfterAnimationsObserver = null;
  89578. this.scene = null;
  89579. };
  89580. return SceneInstrumentation;
  89581. }());
  89582. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89583. })(BABYLON || (BABYLON = {}));
  89584. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89585. var BABYLON;
  89586. (function (BABYLON) {
  89587. var _TimeToken = /** @class */ (function () {
  89588. function _TimeToken() {
  89589. this._timeElapsedQueryEnded = false;
  89590. }
  89591. return _TimeToken;
  89592. }());
  89593. BABYLON._TimeToken = _TimeToken;
  89594. })(BABYLON || (BABYLON = {}));
  89595. //# sourceMappingURL=babylon.timeToken.js.map
  89596. var BABYLON;
  89597. (function (BABYLON) {
  89598. /**
  89599. * Background material defines definition.
  89600. * @ignore Mainly internal Use
  89601. */
  89602. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89603. __extends(BackgroundMaterialDefines, _super);
  89604. /**
  89605. * Constructor of the defines.
  89606. */
  89607. function BackgroundMaterialDefines() {
  89608. var _this = _super.call(this) || this;
  89609. /**
  89610. * True if the diffuse texture is in use.
  89611. */
  89612. _this.DIFFUSE = false;
  89613. /**
  89614. * The direct UV channel to use.
  89615. */
  89616. _this.DIFFUSEDIRECTUV = 0;
  89617. /**
  89618. * True if the diffuse texture is in gamma space.
  89619. */
  89620. _this.GAMMADIFFUSE = false;
  89621. /**
  89622. * True if the diffuse texture has opacity in the alpha channel.
  89623. */
  89624. _this.DIFFUSEHASALPHA = false;
  89625. /**
  89626. * True if you want the material to fade to transparent at grazing angle.
  89627. */
  89628. _this.OPACITYFRESNEL = false;
  89629. /**
  89630. * True if an extra blur needs to be added in the reflection.
  89631. */
  89632. _this.REFLECTIONBLUR = false;
  89633. /**
  89634. * True if you want the material to fade to reflection at grazing angle.
  89635. */
  89636. _this.REFLECTIONFRESNEL = false;
  89637. /**
  89638. * True if you want the material to falloff as far as you move away from the scene center.
  89639. */
  89640. _this.REFLECTIONFALLOFF = false;
  89641. /**
  89642. * False if the current Webgl implementation does not support the texture lod extension.
  89643. */
  89644. _this.TEXTURELODSUPPORT = false;
  89645. /**
  89646. * True to ensure the data are premultiplied.
  89647. */
  89648. _this.PREMULTIPLYALPHA = false;
  89649. /**
  89650. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89651. */
  89652. _this.USERGBCOLOR = false;
  89653. /**
  89654. * True to add noise in order to reduce the banding effect.
  89655. */
  89656. _this.NOISE = false;
  89657. /**
  89658. * is the reflection texture in BGR color scheme?
  89659. * Mainly used to solve a bug in ios10 video tag
  89660. */
  89661. _this.REFLECTIONBGR = false;
  89662. _this.IMAGEPROCESSING = false;
  89663. _this.VIGNETTE = false;
  89664. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89665. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89666. _this.TONEMAPPING = false;
  89667. _this.CONTRAST = false;
  89668. _this.COLORCURVES = false;
  89669. _this.COLORGRADING = false;
  89670. _this.COLORGRADING3D = false;
  89671. _this.SAMPLER3DGREENDEPTH = false;
  89672. _this.SAMPLER3DBGRMAP = false;
  89673. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89674. _this.EXPOSURE = false;
  89675. _this.GRAIN = false;
  89676. // Reflection.
  89677. _this.REFLECTION = false;
  89678. _this.REFLECTIONMAP_3D = false;
  89679. _this.REFLECTIONMAP_SPHERICAL = false;
  89680. _this.REFLECTIONMAP_PLANAR = false;
  89681. _this.REFLECTIONMAP_CUBIC = false;
  89682. _this.REFLECTIONMAP_PROJECTION = false;
  89683. _this.REFLECTIONMAP_SKYBOX = false;
  89684. _this.REFLECTIONMAP_EXPLICIT = false;
  89685. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89686. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89687. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89688. _this.INVERTCUBICMAP = false;
  89689. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89690. _this.LODINREFLECTIONALPHA = false;
  89691. _this.GAMMAREFLECTION = false;
  89692. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89693. // Default BJS.
  89694. _this.MAINUV1 = false;
  89695. _this.MAINUV2 = false;
  89696. _this.UV1 = false;
  89697. _this.UV2 = false;
  89698. _this.CLIPPLANE = false;
  89699. _this.POINTSIZE = false;
  89700. _this.FOG = false;
  89701. _this.NORMAL = false;
  89702. _this.NUM_BONE_INFLUENCERS = 0;
  89703. _this.BonesPerMesh = 0;
  89704. _this.INSTANCES = false;
  89705. _this.SHADOWFLOAT = false;
  89706. _this.rebuild();
  89707. return _this;
  89708. }
  89709. return BackgroundMaterialDefines;
  89710. }(BABYLON.MaterialDefines));
  89711. /**
  89712. * Background material used to create an efficient environement around your scene.
  89713. */
  89714. var BackgroundMaterial = /** @class */ (function (_super) {
  89715. __extends(BackgroundMaterial, _super);
  89716. /**
  89717. * Instantiates a Background Material in the given scene
  89718. * @param name The friendly name of the material
  89719. * @param scene The scene to add the material to
  89720. */
  89721. function BackgroundMaterial(name, scene) {
  89722. var _this = _super.call(this, name, scene) || this;
  89723. /**
  89724. * Key light Color (multiply against the R channel of the environement texture)
  89725. */
  89726. _this.primaryColor = BABYLON.Color3.White();
  89727. /**
  89728. * Key light Level (allowing HDR output of the background)
  89729. */
  89730. _this.primaryLevel = 1;
  89731. /**
  89732. * Secondary light Color (multiply against the G channel of the environement texture)
  89733. */
  89734. _this.secondaryColor = BABYLON.Color3.Gray();
  89735. /**
  89736. * Secondary light Level (allowing HDR output of the background)
  89737. */
  89738. _this.secondaryLevel = 1;
  89739. /**
  89740. * Tertiary light Color (multiply against the B channel of the environement texture)
  89741. */
  89742. _this.tertiaryColor = BABYLON.Color3.Black();
  89743. /**
  89744. * Tertiary light Level (allowing HDR output of the background)
  89745. */
  89746. _this.tertiaryLevel = 1;
  89747. /**
  89748. * Reflection Texture used in the material.
  89749. * Should be author in a specific way for the best result (refer to the documentation).
  89750. */
  89751. _this.reflectionTexture = null;
  89752. /**
  89753. * Reflection Texture level of blur.
  89754. *
  89755. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89756. * texture twice.
  89757. */
  89758. _this.reflectionBlur = 0;
  89759. /**
  89760. * Diffuse Texture used in the material.
  89761. * Should be author in a specific way for the best result (refer to the documentation).
  89762. */
  89763. _this.diffuseTexture = null;
  89764. _this._shadowLights = null;
  89765. /**
  89766. * Specify the list of lights casting shadow on the material.
  89767. * All scene shadow lights will be included if null.
  89768. */
  89769. _this.shadowLights = null;
  89770. /**
  89771. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89772. * soft lighting on the background.
  89773. */
  89774. _this.shadowBlurScale = 1;
  89775. /**
  89776. * Helps adjusting the shadow to a softer level if required.
  89777. * 0 means black shadows and 1 means no shadows.
  89778. */
  89779. _this.shadowLevel = 0;
  89780. /**
  89781. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89782. * It is usually zero but might be interesting to modify according to your setup.
  89783. */
  89784. _this.sceneCenter = BABYLON.Vector3.Zero();
  89785. /**
  89786. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89787. * This helps ensuring a nice transition when the camera goes under the ground.
  89788. */
  89789. _this.opacityFresnel = true;
  89790. /**
  89791. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89792. * This helps adding a mirror texture on the ground.
  89793. */
  89794. _this.reflectionFresnel = false;
  89795. /**
  89796. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89797. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89798. */
  89799. _this.reflectionFalloffDistance = 0.0;
  89800. /**
  89801. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89802. */
  89803. _this.reflectionAmount = 1.0;
  89804. /**
  89805. * This specifies the weight of the reflection at grazing angle.
  89806. */
  89807. _this.reflectionReflectance0 = 0.05;
  89808. /**
  89809. * This specifies the weight of the reflection at a perpendicular point of view.
  89810. */
  89811. _this.reflectionReflectance90 = 0.5;
  89812. /**
  89813. * Helps to directly use the maps channels instead of their level.
  89814. */
  89815. _this.useRGBColor = true;
  89816. /**
  89817. * This helps reducing the banding effect that could occur on the background.
  89818. */
  89819. _this.enableNoise = false;
  89820. _this._fovMultiplier = 1.0;
  89821. /**
  89822. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89823. * @type {boolean}
  89824. */
  89825. _this.useEquirectangularFOV = false;
  89826. _this._maxSimultaneousLights = 4;
  89827. /**
  89828. * Number of Simultaneous lights allowed on the material.
  89829. */
  89830. _this.maxSimultaneousLights = 4;
  89831. /**
  89832. * Keep track of the image processing observer to allow dispose and replace.
  89833. */
  89834. _this._imageProcessingObserver = null;
  89835. /**
  89836. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89837. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89838. */
  89839. _this.switchToBGR = false;
  89840. // Temp values kept as cache in the material.
  89841. _this._renderTargets = new BABYLON.SmartArray(16);
  89842. _this._reflectionControls = BABYLON.Vector4.Zero();
  89843. // Setup the default processing configuration to the scene.
  89844. _this._attachImageProcessingConfiguration(null);
  89845. _this.getRenderTargetTextures = function () {
  89846. _this._renderTargets.reset();
  89847. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89848. _this._renderTargets.push(_this._diffuseTexture);
  89849. }
  89850. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89851. _this._renderTargets.push(_this._reflectionTexture);
  89852. }
  89853. return _this._renderTargets;
  89854. };
  89855. return _this;
  89856. }
  89857. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89858. /**
  89859. * Sets the reflection reflectance fresnel values according to the default standard
  89860. * empirically know to work well :-)
  89861. */
  89862. set: function (value) {
  89863. var reflectionWeight = value;
  89864. if (reflectionWeight < 0.5) {
  89865. reflectionWeight = reflectionWeight * 2.0;
  89866. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89867. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89868. }
  89869. else {
  89870. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89871. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89872. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89873. }
  89874. },
  89875. enumerable: true,
  89876. configurable: true
  89877. });
  89878. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89879. /**
  89880. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89881. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89882. * Recommended to be keep at 1.0 except for special cases.
  89883. */
  89884. get: function () {
  89885. return this._fovMultiplier;
  89886. },
  89887. set: function (value) {
  89888. if (isNaN(value)) {
  89889. value = 1.0;
  89890. }
  89891. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89892. },
  89893. enumerable: true,
  89894. configurable: true
  89895. });
  89896. /**
  89897. * Attaches a new image processing configuration to the PBR Material.
  89898. * @param configuration (if null the scene configuration will be use)
  89899. */
  89900. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89901. var _this = this;
  89902. if (configuration === this._imageProcessingConfiguration) {
  89903. return;
  89904. }
  89905. // Detaches observer.
  89906. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89907. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89908. }
  89909. // Pick the scene configuration if needed.
  89910. if (!configuration) {
  89911. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89912. }
  89913. else {
  89914. this._imageProcessingConfiguration = configuration;
  89915. }
  89916. // Attaches observer.
  89917. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89918. _this._markAllSubMeshesAsImageProcessingDirty();
  89919. });
  89920. };
  89921. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89922. /**
  89923. * Gets the image processing configuration used either in this material.
  89924. */
  89925. get: function () {
  89926. return this._imageProcessingConfiguration;
  89927. },
  89928. /**
  89929. * Sets the Default image processing configuration used either in the this material.
  89930. *
  89931. * If sets to null, the scene one is in use.
  89932. */
  89933. set: function (value) {
  89934. this._attachImageProcessingConfiguration(value);
  89935. // Ensure the effect will be rebuilt.
  89936. this._markAllSubMeshesAsTexturesDirty();
  89937. },
  89938. enumerable: true,
  89939. configurable: true
  89940. });
  89941. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89942. /**
  89943. * Gets wether the color curves effect is enabled.
  89944. */
  89945. get: function () {
  89946. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89947. },
  89948. /**
  89949. * Sets wether the color curves effect is enabled.
  89950. */
  89951. set: function (value) {
  89952. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89953. },
  89954. enumerable: true,
  89955. configurable: true
  89956. });
  89957. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89958. /**
  89959. * Gets wether the color grading effect is enabled.
  89960. */
  89961. get: function () {
  89962. return this.imageProcessingConfiguration.colorGradingEnabled;
  89963. },
  89964. /**
  89965. * Gets wether the color grading effect is enabled.
  89966. */
  89967. set: function (value) {
  89968. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89969. },
  89970. enumerable: true,
  89971. configurable: true
  89972. });
  89973. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89974. /**
  89975. * Gets wether tonemapping is enabled or not.
  89976. */
  89977. get: function () {
  89978. return this._imageProcessingConfiguration.toneMappingEnabled;
  89979. },
  89980. /**
  89981. * Sets wether tonemapping is enabled or not
  89982. */
  89983. set: function (value) {
  89984. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89985. },
  89986. enumerable: true,
  89987. configurable: true
  89988. });
  89989. ;
  89990. ;
  89991. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89992. /**
  89993. * The camera exposure used on this material.
  89994. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89995. * This corresponds to a photographic exposure.
  89996. */
  89997. get: function () {
  89998. return this._imageProcessingConfiguration.exposure;
  89999. },
  90000. /**
  90001. * The camera exposure used on this material.
  90002. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90003. * This corresponds to a photographic exposure.
  90004. */
  90005. set: function (value) {
  90006. this._imageProcessingConfiguration.exposure = value;
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. ;
  90012. ;
  90013. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90014. /**
  90015. * Gets The camera contrast used on this material.
  90016. */
  90017. get: function () {
  90018. return this._imageProcessingConfiguration.contrast;
  90019. },
  90020. /**
  90021. * Sets The camera contrast used on this material.
  90022. */
  90023. set: function (value) {
  90024. this._imageProcessingConfiguration.contrast = value;
  90025. },
  90026. enumerable: true,
  90027. configurable: true
  90028. });
  90029. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90030. /**
  90031. * Gets the Color Grading 2D Lookup Texture.
  90032. */
  90033. get: function () {
  90034. return this._imageProcessingConfiguration.colorGradingTexture;
  90035. },
  90036. /**
  90037. * Sets the Color Grading 2D Lookup Texture.
  90038. */
  90039. set: function (value) {
  90040. this.imageProcessingConfiguration.colorGradingTexture = value;
  90041. },
  90042. enumerable: true,
  90043. configurable: true
  90044. });
  90045. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90046. /**
  90047. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90048. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90049. * 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;
  90050. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90051. */
  90052. get: function () {
  90053. return this.imageProcessingConfiguration.colorCurves;
  90054. },
  90055. /**
  90056. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90057. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90058. * 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;
  90059. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90060. */
  90061. set: function (value) {
  90062. this.imageProcessingConfiguration.colorCurves = value;
  90063. },
  90064. enumerable: true,
  90065. configurable: true
  90066. });
  90067. /**
  90068. * The entire material has been created in order to prevent overdraw.
  90069. * @returns false
  90070. */
  90071. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90072. return true;
  90073. };
  90074. /**
  90075. * The entire material has been created in order to prevent overdraw.
  90076. * @returns true if blending is enable
  90077. */
  90078. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90079. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90080. };
  90081. /**
  90082. * Checks wether the material is ready to be rendered for a given mesh.
  90083. * @param mesh The mesh to render
  90084. * @param subMesh The submesh to check against
  90085. * @param useInstances Specify wether or not the material is used with instances
  90086. * @returns true if all the dependencies are ready (Textures, Effects...)
  90087. */
  90088. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90089. var _this = this;
  90090. if (useInstances === void 0) { useInstances = false; }
  90091. if (subMesh.effect && this.isFrozen) {
  90092. if (this._wasPreviouslyReady) {
  90093. return true;
  90094. }
  90095. }
  90096. if (!subMesh._materialDefines) {
  90097. subMesh._materialDefines = new BackgroundMaterialDefines();
  90098. }
  90099. var scene = this.getScene();
  90100. var defines = subMesh._materialDefines;
  90101. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90102. if (defines._renderId === scene.getRenderId()) {
  90103. return true;
  90104. }
  90105. }
  90106. var engine = scene.getEngine();
  90107. // Lights
  90108. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90109. defines._needNormals = true;
  90110. // Textures
  90111. if (defines._areTexturesDirty) {
  90112. defines._needUVs = false;
  90113. if (scene.texturesEnabled) {
  90114. if (scene.getEngine().getCaps().textureLOD) {
  90115. defines.TEXTURELODSUPPORT = true;
  90116. }
  90117. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90118. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90119. return false;
  90120. }
  90121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90122. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90123. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90124. defines.OPACITYFRESNEL = this._opacityFresnel;
  90125. }
  90126. else {
  90127. defines.DIFFUSE = false;
  90128. defines.DIFFUSEHASALPHA = false;
  90129. defines.GAMMADIFFUSE = false;
  90130. defines.OPACITYFRESNEL = false;
  90131. }
  90132. var reflectionTexture = this._reflectionTexture;
  90133. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90134. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90135. return false;
  90136. }
  90137. defines.REFLECTION = true;
  90138. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90139. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90140. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90141. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90142. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90143. defines.REFLECTIONBGR = this.switchToBGR;
  90144. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90145. defines.INVERTCUBICMAP = true;
  90146. }
  90147. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90148. switch (reflectionTexture.coordinatesMode) {
  90149. case BABYLON.Texture.CUBIC_MODE:
  90150. case BABYLON.Texture.INVCUBIC_MODE:
  90151. defines.REFLECTIONMAP_CUBIC = true;
  90152. break;
  90153. case BABYLON.Texture.EXPLICIT_MODE:
  90154. defines.REFLECTIONMAP_EXPLICIT = true;
  90155. break;
  90156. case BABYLON.Texture.PLANAR_MODE:
  90157. defines.REFLECTIONMAP_PLANAR = true;
  90158. break;
  90159. case BABYLON.Texture.PROJECTION_MODE:
  90160. defines.REFLECTIONMAP_PROJECTION = true;
  90161. break;
  90162. case BABYLON.Texture.SKYBOX_MODE:
  90163. defines.REFLECTIONMAP_SKYBOX = true;
  90164. break;
  90165. case BABYLON.Texture.SPHERICAL_MODE:
  90166. defines.REFLECTIONMAP_SPHERICAL = true;
  90167. break;
  90168. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90169. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90170. break;
  90171. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90172. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90173. break;
  90174. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90175. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90176. break;
  90177. }
  90178. if (this.reflectionFresnel) {
  90179. defines.REFLECTIONFRESNEL = true;
  90180. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90181. this._reflectionControls.x = this.reflectionAmount;
  90182. this._reflectionControls.y = this.reflectionReflectance0;
  90183. this._reflectionControls.z = this.reflectionReflectance90;
  90184. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90185. }
  90186. else {
  90187. defines.REFLECTIONFRESNEL = false;
  90188. defines.REFLECTIONFALLOFF = false;
  90189. }
  90190. }
  90191. else {
  90192. defines.REFLECTION = false;
  90193. defines.REFLECTIONFALLOFF = false;
  90194. defines.REFLECTIONBLUR = false;
  90195. defines.REFLECTIONMAP_3D = false;
  90196. defines.REFLECTIONMAP_SPHERICAL = false;
  90197. defines.REFLECTIONMAP_PLANAR = false;
  90198. defines.REFLECTIONMAP_CUBIC = false;
  90199. defines.REFLECTIONMAP_PROJECTION = false;
  90200. defines.REFLECTIONMAP_SKYBOX = false;
  90201. defines.REFLECTIONMAP_EXPLICIT = false;
  90202. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90203. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90204. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90205. defines.INVERTCUBICMAP = false;
  90206. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90207. defines.LODINREFLECTIONALPHA = false;
  90208. defines.GAMMAREFLECTION = false;
  90209. }
  90210. }
  90211. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90212. defines.USERGBCOLOR = this._useRGBColor;
  90213. defines.NOISE = this._enableNoise;
  90214. }
  90215. if (defines._areImageProcessingDirty) {
  90216. if (!this._imageProcessingConfiguration.isReady()) {
  90217. return false;
  90218. }
  90219. this._imageProcessingConfiguration.prepareDefines(defines);
  90220. }
  90221. // Misc.
  90222. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90223. // Values that need to be evaluated on every frame
  90224. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90225. // Attribs
  90226. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90227. if (mesh) {
  90228. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90229. mesh.createNormals(true);
  90230. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90231. }
  90232. }
  90233. }
  90234. // Get correct effect
  90235. if (defines.isDirty) {
  90236. defines.markAsProcessed();
  90237. scene.resetCachedMaterial();
  90238. // Fallbacks
  90239. var fallbacks = new BABYLON.EffectFallbacks();
  90240. if (defines.FOG) {
  90241. fallbacks.addFallback(0, "FOG");
  90242. }
  90243. if (defines.POINTSIZE) {
  90244. fallbacks.addFallback(1, "POINTSIZE");
  90245. }
  90246. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90247. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90248. fallbacks.addCPUSkinningFallback(0, mesh);
  90249. }
  90250. //Attributes
  90251. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90252. if (defines.NORMAL) {
  90253. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90254. }
  90255. if (defines.UV1) {
  90256. attribs.push(BABYLON.VertexBuffer.UVKind);
  90257. }
  90258. if (defines.UV2) {
  90259. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90260. }
  90261. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90262. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90263. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90264. "vFogInfos", "vFogColor", "pointSize",
  90265. "vClipPlane", "mBones",
  90266. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90267. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90268. "shadowLevel", "alpha",
  90269. "vBackgroundCenter", "vReflectionControl",
  90270. "vDiffuseInfos", "diffuseMatrix",
  90271. ];
  90272. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90273. var uniformBuffers = ["Material", "Scene"];
  90274. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90275. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90276. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90277. uniformsNames: uniforms,
  90278. uniformBuffersNames: uniformBuffers,
  90279. samplers: samplers,
  90280. defines: defines,
  90281. maxSimultaneousLights: this._maxSimultaneousLights
  90282. });
  90283. var onCompiled = function (effect) {
  90284. if (_this.onCompiled) {
  90285. _this.onCompiled(effect);
  90286. }
  90287. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90288. };
  90289. var join = defines.toString();
  90290. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90291. attributes: attribs,
  90292. uniformsNames: uniforms,
  90293. uniformBuffersNames: uniformBuffers,
  90294. samplers: samplers,
  90295. defines: join,
  90296. fallbacks: fallbacks,
  90297. onCompiled: onCompiled,
  90298. onError: this.onError,
  90299. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90300. }, engine), defines);
  90301. this.buildUniformLayout();
  90302. }
  90303. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90304. return false;
  90305. }
  90306. defines._renderId = scene.getRenderId();
  90307. this._wasPreviouslyReady = true;
  90308. return true;
  90309. };
  90310. /**
  90311. * Build the uniform buffer used in the material.
  90312. */
  90313. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90314. // Order is important !
  90315. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90316. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90317. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90318. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90319. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90320. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90321. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90322. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90323. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90324. this._uniformBuffer.addUniform("pointSize", 1);
  90325. this._uniformBuffer.addUniform("shadowLevel", 1);
  90326. this._uniformBuffer.addUniform("alpha", 1);
  90327. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90328. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90329. this._uniformBuffer.create();
  90330. };
  90331. /**
  90332. * Unbind the material.
  90333. */
  90334. BackgroundMaterial.prototype.unbind = function () {
  90335. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90336. this._uniformBuffer.setTexture("diffuseSampler", null);
  90337. }
  90338. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90339. this._uniformBuffer.setTexture("reflectionSampler", null);
  90340. }
  90341. _super.prototype.unbind.call(this);
  90342. };
  90343. /**
  90344. * Bind only the world matrix to the material.
  90345. * @param world The world matrix to bind.
  90346. */
  90347. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90348. this._activeEffect.setMatrix("world", world);
  90349. };
  90350. /**
  90351. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90352. * @param world The world matrix to bind.
  90353. * @param subMesh The submesh to bind for.
  90354. */
  90355. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90356. var scene = this.getScene();
  90357. var defines = subMesh._materialDefines;
  90358. if (!defines) {
  90359. return;
  90360. }
  90361. var effect = subMesh.effect;
  90362. if (!effect) {
  90363. return;
  90364. }
  90365. this._activeEffect = effect;
  90366. // Matrices
  90367. this.bindOnlyWorldMatrix(world);
  90368. // Bones
  90369. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90370. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90371. if (mustRebind) {
  90372. this._uniformBuffer.bindToEffect(effect, "Material");
  90373. this.bindViewProjection(effect);
  90374. var reflectionTexture = this._reflectionTexture;
  90375. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90376. // Texture uniforms
  90377. if (scene.texturesEnabled) {
  90378. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90379. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90380. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90381. }
  90382. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90383. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90384. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90385. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90386. }
  90387. }
  90388. if (this.shadowLevel > 0) {
  90389. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90390. }
  90391. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90392. // Point size
  90393. if (this.pointsCloud) {
  90394. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90395. }
  90396. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90397. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90398. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90399. }
  90400. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90401. // Textures
  90402. if (scene.texturesEnabled) {
  90403. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90404. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90405. }
  90406. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90407. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90408. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90409. }
  90410. else if (!defines.REFLECTIONBLUR) {
  90411. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90412. }
  90413. else {
  90414. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90415. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90416. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90417. }
  90418. if (defines.REFLECTIONFRESNEL) {
  90419. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90420. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90421. }
  90422. }
  90423. }
  90424. // Clip plane
  90425. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90426. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90427. }
  90428. if (mustRebind || !this.isFrozen) {
  90429. if (scene.lightsEnabled) {
  90430. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90431. }
  90432. // View
  90433. this.bindView(effect);
  90434. // Fog
  90435. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90436. // image processing
  90437. this._imageProcessingConfiguration.bind(this._activeEffect);
  90438. }
  90439. this._uniformBuffer.update();
  90440. this._afterBind(mesh);
  90441. };
  90442. /**
  90443. * Dispose the material.
  90444. * @param forceDisposeEffect Force disposal of the associated effect.
  90445. * @param forceDisposeTextures Force disposal of the associated textures.
  90446. */
  90447. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90448. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90449. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90450. if (forceDisposeTextures) {
  90451. if (this.diffuseTexture) {
  90452. this.diffuseTexture.dispose();
  90453. }
  90454. if (this.reflectionTexture) {
  90455. this.reflectionTexture.dispose();
  90456. }
  90457. }
  90458. this._renderTargets.dispose();
  90459. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90460. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90461. }
  90462. _super.prototype.dispose.call(this, forceDisposeEffect);
  90463. };
  90464. /**
  90465. * Clones the material.
  90466. * @param name The cloned name.
  90467. * @returns The cloned material.
  90468. */
  90469. BackgroundMaterial.prototype.clone = function (name) {
  90470. var _this = this;
  90471. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90472. };
  90473. /**
  90474. * Serializes the current material to its JSON representation.
  90475. * @returns The JSON representation.
  90476. */
  90477. BackgroundMaterial.prototype.serialize = function () {
  90478. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90479. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90480. return serializationObject;
  90481. };
  90482. /**
  90483. * Gets the class name of the material
  90484. * @returns "BackgroundMaterial"
  90485. */
  90486. BackgroundMaterial.prototype.getClassName = function () {
  90487. return "BackgroundMaterial";
  90488. };
  90489. /**
  90490. * Parse a JSON input to create back a background material.
  90491. * @param source The JSON data to parse
  90492. * @param scene The scene to create the parsed material in
  90493. * @param rootUrl The root url of the assets the material depends upon
  90494. * @returns the instantiated BackgroundMaterial.
  90495. */
  90496. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90497. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90498. };
  90499. /**
  90500. * Standard reflectance value at parallel view angle.
  90501. */
  90502. BackgroundMaterial.StandardReflectance0 = 0.05;
  90503. /**
  90504. * Standard reflectance value at grazing angle.
  90505. */
  90506. BackgroundMaterial.StandardReflectance90 = 0.5;
  90507. __decorate([
  90508. BABYLON.serializeAsColor3()
  90509. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90510. __decorate([
  90511. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90512. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90513. __decorate([
  90514. BABYLON.serialize()
  90515. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90516. __decorate([
  90517. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90518. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90519. __decorate([
  90520. BABYLON.serializeAsColor3()
  90521. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90522. __decorate([
  90523. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90524. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90525. __decorate([
  90526. BABYLON.serialize()
  90527. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90528. __decorate([
  90529. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90530. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90531. __decorate([
  90532. BABYLON.serializeAsColor3()
  90533. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90534. __decorate([
  90535. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90536. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90537. __decorate([
  90538. BABYLON.serialize()
  90539. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90540. __decorate([
  90541. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90542. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90543. __decorate([
  90544. BABYLON.serializeAsTexture()
  90545. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90546. __decorate([
  90547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90548. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90549. __decorate([
  90550. BABYLON.serialize()
  90551. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90552. __decorate([
  90553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90554. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90555. __decorate([
  90556. BABYLON.serializeAsTexture()
  90557. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90558. __decorate([
  90559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90560. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90561. __decorate([
  90562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90563. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90564. __decorate([
  90565. BABYLON.serialize()
  90566. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90567. __decorate([
  90568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90569. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90570. __decorate([
  90571. BABYLON.serialize()
  90572. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90573. __decorate([
  90574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90575. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90576. __decorate([
  90577. BABYLON.serializeAsVector3()
  90578. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90579. __decorate([
  90580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90581. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90582. __decorate([
  90583. BABYLON.serialize()
  90584. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90585. __decorate([
  90586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90587. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90588. __decorate([
  90589. BABYLON.serialize()
  90590. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90591. __decorate([
  90592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90593. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90594. __decorate([
  90595. BABYLON.serialize()
  90596. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90597. __decorate([
  90598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90599. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90600. __decorate([
  90601. BABYLON.serialize()
  90602. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90603. __decorate([
  90604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90605. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90606. __decorate([
  90607. BABYLON.serialize()
  90608. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90609. __decorate([
  90610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90611. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90612. __decorate([
  90613. BABYLON.serialize()
  90614. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90615. __decorate([
  90616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90617. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90618. __decorate([
  90619. BABYLON.serialize()
  90620. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90621. __decorate([
  90622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90623. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90624. __decorate([
  90625. BABYLON.serialize()
  90626. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90627. __decorate([
  90628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90629. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90630. __decorate([
  90631. BABYLON.serialize()
  90632. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90633. __decorate([
  90634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90635. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90636. __decorate([
  90637. BABYLON.serializeAsImageProcessingConfiguration()
  90638. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90639. return BackgroundMaterial;
  90640. }(BABYLON.PushMaterial));
  90641. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90642. })(BABYLON || (BABYLON = {}));
  90643. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90644. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90645. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90646. s = arguments[i];
  90647. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90648. t[p] = s[p];
  90649. }
  90650. return t;
  90651. };
  90652. var BABYLON;
  90653. (function (BABYLON) {
  90654. /**
  90655. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90656. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90657. * It also helps with the default setup of your imageProcessing configuration.
  90658. */
  90659. var EnvironmentHelper = /** @class */ (function () {
  90660. /**
  90661. * constructor
  90662. * @param options
  90663. * @param scene The scene to add the material to
  90664. */
  90665. function EnvironmentHelper(options, scene) {
  90666. var _this = this;
  90667. this._errorHandler = function (message, exception) {
  90668. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90669. };
  90670. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90671. this._scene = scene;
  90672. this.onErrorObservable = new BABYLON.Observable();
  90673. this._setupBackground();
  90674. this._setupImageProcessing();
  90675. }
  90676. /**
  90677. * Creates the default options for the helper.
  90678. */
  90679. EnvironmentHelper._getDefaultOptions = function () {
  90680. return {
  90681. createGround: true,
  90682. groundSize: 15,
  90683. groundTexture: this._groundTextureCDNUrl,
  90684. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90685. groundOpacity: 0.9,
  90686. enableGroundShadow: true,
  90687. groundShadowLevel: 0.5,
  90688. enableGroundMirror: false,
  90689. groundMirrorSizeRatio: 0.3,
  90690. groundMirrorBlurKernel: 64,
  90691. groundMirrorAmount: 1,
  90692. groundMirrorFresnelWeight: 1,
  90693. groundMirrorFallOffDistance: 0,
  90694. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90695. groundYBias: 0.00001,
  90696. createSkybox: true,
  90697. skyboxSize: 20,
  90698. skyboxTexture: this._skyboxTextureCDNUrl,
  90699. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90700. backgroundYRotation: 0,
  90701. sizeAuto: true,
  90702. rootPosition: BABYLON.Vector3.Zero(),
  90703. setupImageProcessing: true,
  90704. environmentTexture: this._environmentTextureCDNUrl,
  90705. cameraExposure: 0.8,
  90706. cameraContrast: 1.2,
  90707. toneMappingEnabled: true,
  90708. };
  90709. };
  90710. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90711. /**
  90712. * Gets the root mesh created by the helper.
  90713. */
  90714. get: function () {
  90715. return this._rootMesh;
  90716. },
  90717. enumerable: true,
  90718. configurable: true
  90719. });
  90720. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90721. /**
  90722. * Gets the skybox created by the helper.
  90723. */
  90724. get: function () {
  90725. return this._skybox;
  90726. },
  90727. enumerable: true,
  90728. configurable: true
  90729. });
  90730. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90731. /**
  90732. * Gets the skybox texture created by the helper.
  90733. */
  90734. get: function () {
  90735. return this._skyboxTexture;
  90736. },
  90737. enumerable: true,
  90738. configurable: true
  90739. });
  90740. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90741. /**
  90742. * Gets the skybox material created by the helper.
  90743. */
  90744. get: function () {
  90745. return this._skyboxMaterial;
  90746. },
  90747. enumerable: true,
  90748. configurable: true
  90749. });
  90750. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90751. /**
  90752. * Gets the ground mesh created by the helper.
  90753. */
  90754. get: function () {
  90755. return this._ground;
  90756. },
  90757. enumerable: true,
  90758. configurable: true
  90759. });
  90760. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90761. /**
  90762. * Gets the ground texture created by the helper.
  90763. */
  90764. get: function () {
  90765. return this._groundTexture;
  90766. },
  90767. enumerable: true,
  90768. configurable: true
  90769. });
  90770. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90771. /**
  90772. * Gets the ground mirror created by the helper.
  90773. */
  90774. get: function () {
  90775. return this._groundMirror;
  90776. },
  90777. enumerable: true,
  90778. configurable: true
  90779. });
  90780. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90781. /**
  90782. * Gets the ground mirror render list to helps pushing the meshes
  90783. * you wish in the ground reflection.
  90784. */
  90785. get: function () {
  90786. if (this._groundMirror) {
  90787. return this._groundMirror.renderList;
  90788. }
  90789. return null;
  90790. },
  90791. enumerable: true,
  90792. configurable: true
  90793. });
  90794. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90795. /**
  90796. * Gets the ground material created by the helper.
  90797. */
  90798. get: function () {
  90799. return this._groundMaterial;
  90800. },
  90801. enumerable: true,
  90802. configurable: true
  90803. });
  90804. /**
  90805. * Updates the background according to the new options
  90806. * @param options
  90807. */
  90808. EnvironmentHelper.prototype.updateOptions = function (options) {
  90809. var newOptions = __assign({}, this._options, options);
  90810. if (this._ground && !newOptions.createGround) {
  90811. this._ground.dispose();
  90812. this._ground = null;
  90813. }
  90814. if (this._groundMaterial && !newOptions.createGround) {
  90815. this._groundMaterial.dispose();
  90816. this._groundMaterial = null;
  90817. }
  90818. if (this._groundTexture) {
  90819. if (this._options.groundTexture != newOptions.groundTexture) {
  90820. this._groundTexture.dispose();
  90821. this._groundTexture = null;
  90822. }
  90823. }
  90824. if (this._skybox && !newOptions.createSkybox) {
  90825. this._skybox.dispose();
  90826. this._skybox = null;
  90827. }
  90828. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90829. this._skyboxMaterial.dispose();
  90830. this._skyboxMaterial = null;
  90831. }
  90832. if (this._skyboxTexture) {
  90833. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90834. this._skyboxTexture.dispose();
  90835. this._skyboxTexture = null;
  90836. }
  90837. }
  90838. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90839. this._groundMirror.dispose();
  90840. this._groundMirror = null;
  90841. }
  90842. if (this._scene.environmentTexture) {
  90843. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90844. this._scene.environmentTexture.dispose();
  90845. }
  90846. }
  90847. this._options = newOptions;
  90848. this._setupBackground();
  90849. this._setupImageProcessing();
  90850. };
  90851. /**
  90852. * Sets the primary color of all the available elements.
  90853. * @param color
  90854. */
  90855. EnvironmentHelper.prototype.setMainColor = function (color) {
  90856. if (this.groundMaterial) {
  90857. this.groundMaterial.primaryColor = color;
  90858. }
  90859. if (this.skyboxMaterial) {
  90860. this.skyboxMaterial.primaryColor = color;
  90861. }
  90862. if (this.groundMirror) {
  90863. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90864. }
  90865. };
  90866. /**
  90867. * Setup the image processing according to the specified options.
  90868. */
  90869. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90870. if (this._options.setupImageProcessing) {
  90871. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90872. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90873. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90874. this._setupEnvironmentTexture();
  90875. }
  90876. };
  90877. /**
  90878. * Setup the environment texture according to the specified options.
  90879. */
  90880. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90881. if (this._scene.environmentTexture) {
  90882. return;
  90883. }
  90884. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90885. this._scene.environmentTexture = this._options.environmentTexture;
  90886. return;
  90887. }
  90888. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90889. this._scene.environmentTexture = environmentTexture;
  90890. };
  90891. /**
  90892. * Setup the background according to the specified options.
  90893. */
  90894. EnvironmentHelper.prototype._setupBackground = function () {
  90895. if (!this._rootMesh) {
  90896. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90897. }
  90898. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90899. var sceneSize = this._getSceneSize();
  90900. if (this._options.createGround) {
  90901. this._setupGround(sceneSize);
  90902. this._setupGroundMaterial();
  90903. this._setupGroundDiffuseTexture();
  90904. if (this._options.enableGroundMirror) {
  90905. this._setupGroundMirrorTexture(sceneSize);
  90906. }
  90907. this._setupMirrorInGroundMaterial();
  90908. }
  90909. if (this._options.createSkybox) {
  90910. this._setupSkybox(sceneSize);
  90911. this._setupSkyboxMaterial();
  90912. this._setupSkyboxReflectionTexture();
  90913. }
  90914. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90915. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90916. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90917. };
  90918. /**
  90919. * Get the scene sizes according to the setup.
  90920. */
  90921. EnvironmentHelper.prototype._getSceneSize = function () {
  90922. var _this = this;
  90923. var groundSize = this._options.groundSize;
  90924. var skyboxSize = this._options.skyboxSize;
  90925. var rootPosition = this._options.rootPosition;
  90926. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90927. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90928. }
  90929. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90930. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90931. });
  90932. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90933. if (this._options.sizeAuto) {
  90934. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90935. this._scene.activeCamera.upperRadiusLimit) {
  90936. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90937. skyboxSize = groundSize;
  90938. }
  90939. var sceneDiagonalLenght = sceneDiagonal.length();
  90940. if (sceneDiagonalLenght > groundSize) {
  90941. groundSize = sceneDiagonalLenght * 2;
  90942. skyboxSize = groundSize;
  90943. }
  90944. // 10 % bigger.
  90945. groundSize *= 1.1;
  90946. skyboxSize *= 1.5;
  90947. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90948. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90949. }
  90950. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90951. };
  90952. /**
  90953. * Setup the ground according to the specified options.
  90954. */
  90955. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90956. var _this = this;
  90957. if (!this._ground) {
  90958. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90959. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90960. this._ground.parent = this._rootMesh;
  90961. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90962. }
  90963. this._ground.receiveShadows = this._options.enableGroundShadow;
  90964. };
  90965. /**
  90966. * Setup the ground material according to the specified options.
  90967. */
  90968. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90969. if (!this._groundMaterial) {
  90970. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90971. }
  90972. this._groundMaterial.alpha = this._options.groundOpacity;
  90973. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90974. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90975. this._groundMaterial.primaryLevel = 1;
  90976. this._groundMaterial.primaryColor = this._options.groundColor;
  90977. this._groundMaterial.secondaryLevel = 0;
  90978. this._groundMaterial.tertiaryLevel = 0;
  90979. this._groundMaterial.useRGBColor = false;
  90980. this._groundMaterial.enableNoise = true;
  90981. if (this._ground) {
  90982. this._ground.material = this._groundMaterial;
  90983. }
  90984. };
  90985. /**
  90986. * Setup the ground diffuse texture according to the specified options.
  90987. */
  90988. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90989. if (!this._groundMaterial) {
  90990. return;
  90991. }
  90992. if (this._groundTexture) {
  90993. return;
  90994. }
  90995. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90996. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90997. return;
  90998. }
  90999. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91000. diffuseTexture.gammaSpace = false;
  91001. diffuseTexture.hasAlpha = true;
  91002. this._groundMaterial.diffuseTexture = diffuseTexture;
  91003. };
  91004. /**
  91005. * Setup the ground mirror texture according to the specified options.
  91006. */
  91007. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91008. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91009. if (!this._groundMirror) {
  91010. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91011. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91012. this._groundMirror.anisotropicFilteringLevel = 1;
  91013. this._groundMirror.wrapU = wrapping;
  91014. this._groundMirror.wrapV = wrapping;
  91015. this._groundMirror.gammaSpace = false;
  91016. if (this._groundMirror.renderList) {
  91017. for (var i = 0; i < this._scene.meshes.length; i++) {
  91018. var mesh = this._scene.meshes[i];
  91019. if (mesh !== this._ground &&
  91020. mesh !== this._skybox &&
  91021. mesh !== this._rootMesh) {
  91022. this._groundMirror.renderList.push(mesh);
  91023. }
  91024. }
  91025. }
  91026. }
  91027. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91028. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91029. };
  91030. /**
  91031. * Setup the ground to receive the mirror texture.
  91032. */
  91033. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91034. if (this._groundMaterial) {
  91035. this._groundMaterial.reflectionTexture = this._groundMirror;
  91036. this._groundMaterial.reflectionFresnel = true;
  91037. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91038. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91039. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91040. }
  91041. };
  91042. /**
  91043. * Setup the skybox according to the specified options.
  91044. */
  91045. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91046. var _this = this;
  91047. if (!this._skybox) {
  91048. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91049. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91050. }
  91051. this._skybox.parent = this._rootMesh;
  91052. };
  91053. /**
  91054. * Setup the skybox material according to the specified options.
  91055. */
  91056. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91057. if (!this._skybox) {
  91058. return;
  91059. }
  91060. if (!this._skyboxMaterial) {
  91061. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91062. }
  91063. this._skyboxMaterial.useRGBColor = false;
  91064. this._skyboxMaterial.primaryLevel = 1;
  91065. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91066. this._skyboxMaterial.secondaryLevel = 0;
  91067. this._skyboxMaterial.tertiaryLevel = 0;
  91068. this._skyboxMaterial.enableNoise = true;
  91069. this._skybox.material = this._skyboxMaterial;
  91070. };
  91071. /**
  91072. * Setup the skybox reflection texture according to the specified options.
  91073. */
  91074. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91075. if (!this._skyboxMaterial) {
  91076. return;
  91077. }
  91078. if (this._skyboxTexture) {
  91079. return;
  91080. }
  91081. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91082. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91083. return;
  91084. }
  91085. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91086. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91087. this._skyboxTexture.gammaSpace = false;
  91088. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91089. };
  91090. /**
  91091. * Dispose all the elements created by the Helper.
  91092. */
  91093. EnvironmentHelper.prototype.dispose = function () {
  91094. if (this._groundMaterial) {
  91095. this._groundMaterial.dispose(true, true);
  91096. }
  91097. if (this._skyboxMaterial) {
  91098. this._skyboxMaterial.dispose(true, true);
  91099. }
  91100. this._rootMesh.dispose(false);
  91101. };
  91102. /**
  91103. * Default ground texture URL.
  91104. */
  91105. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91106. /**
  91107. * Default skybox texture URL.
  91108. */
  91109. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91110. /**
  91111. * Default environment texture URL.
  91112. */
  91113. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91114. return EnvironmentHelper;
  91115. }());
  91116. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91117. })(BABYLON || (BABYLON = {}));
  91118. //# sourceMappingURL=babylon.environmentHelper.js.map
  91119. var BABYLON;
  91120. (function (BABYLON) {
  91121. /**
  91122. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91123. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91124. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91125. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91126. */
  91127. var VideoDome = /** @class */ (function (_super) {
  91128. __extends(VideoDome, _super);
  91129. /**
  91130. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91131. * @param name Element's name, child elements will append suffixes for their own names.
  91132. * @param urlsOrVideo
  91133. * @param options An object containing optional or exposed sub element properties:
  91134. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91135. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91136. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91137. * @param options **loop=true** Automatically loop video on end.
  91138. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91139. */
  91140. function VideoDome(name, urlsOrVideo, options, scene) {
  91141. var _this = _super.call(this, name, scene) || this;
  91142. // set defaults and manage values
  91143. name = name || "videoDome";
  91144. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91145. options.clickToPlay = Boolean(options.clickToPlay);
  91146. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91147. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91148. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91149. // create
  91150. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91151. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91152. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91153. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91154. flat: false,
  91155. radius: options.size,
  91156. subdivisions: options.resolution,
  91157. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91158. }, scene);
  91159. // configure material
  91160. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91161. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91162. material.reflectionTexture = _this._videoTexture;
  91163. material.useEquirectangularFOV = true;
  91164. material.fovMultiplier = 1.0;
  91165. // configure mesh
  91166. _this._mesh.material = material;
  91167. _this._mesh.parent = _this;
  91168. // optional configuration
  91169. if (options.clickToPlay) {
  91170. scene.onPointerUp = function () {
  91171. _this._videoTexture.video.play();
  91172. };
  91173. }
  91174. return _this;
  91175. }
  91176. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91177. /**
  91178. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91179. * Also see the options.resolution property.
  91180. */
  91181. get: function () {
  91182. return this._material.fovMultiplier;
  91183. },
  91184. set: function (value) {
  91185. this._material.fovMultiplier = value;
  91186. },
  91187. enumerable: true,
  91188. configurable: true
  91189. });
  91190. /**
  91191. * Releases resources associated with this node.
  91192. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91193. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91194. */
  91195. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91196. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91197. this._videoTexture.dispose();
  91198. this._mesh.dispose();
  91199. this._material.dispose();
  91200. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91201. };
  91202. return VideoDome;
  91203. }(BABYLON.Node));
  91204. BABYLON.VideoDome = VideoDome;
  91205. })(BABYLON || (BABYLON = {}));
  91206. //# sourceMappingURL=babylon.videoDome.js.map
  91207. 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 float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=size;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#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"};
  91208. 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};"};
  91209. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91210. globalObject["BABYLON"] = BABYLON
  91211. return BABYLON;
  91212. });
  91213. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91214. /***/ }),
  91215. /* 1 */
  91216. /***/ (function(module, exports, __webpack_require__) {
  91217. "use strict";
  91218. Object.defineProperty(exports, "__esModule", { value: true });
  91219. var babylonjs_1 = __webpack_require__(0);
  91220. var helper_1 = __webpack_require__(2);
  91221. var HTMLMapper = (function () {
  91222. function HTMLMapper() {
  91223. }
  91224. HTMLMapper.prototype.map = function (element) {
  91225. var config = {};
  91226. var _loop_1 = function (attrIdx) {
  91227. var attr = element.attributes.item(attrIdx);
  91228. var split = attr.nodeName.split('.');
  91229. split.reduce(function (currentConfig, key, idx) {
  91230. var camelKey = helper_1.kebabToCamel(key);
  91231. if (idx === split.length - 1) {
  91232. var val = attr.nodeValue;
  91233. if (val === "true") {
  91234. val = true;
  91235. }
  91236. else if (val === "false") {
  91237. val = false;
  91238. }
  91239. else {
  91240. var isnum = /^\d+$/.test(val);
  91241. if (isnum) {
  91242. var number = parseFloat(val);
  91243. if (!isNaN(number)) {
  91244. val = number;
  91245. }
  91246. }
  91247. }
  91248. currentConfig[camelKey] = val;
  91249. }
  91250. else {
  91251. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91252. }
  91253. return currentConfig[camelKey];
  91254. }, config);
  91255. };
  91256. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91257. _loop_1(attrIdx);
  91258. }
  91259. return config;
  91260. };
  91261. return HTMLMapper;
  91262. }());
  91263. var JSONMapper = (function () {
  91264. function JSONMapper() {
  91265. }
  91266. JSONMapper.prototype.map = function (rawSource) {
  91267. return JSON.parse(rawSource);
  91268. };
  91269. return JSONMapper;
  91270. }());
  91271. var DOMMapper = (function () {
  91272. function DOMMapper() {
  91273. }
  91274. DOMMapper.prototype.map = function (baseElement) {
  91275. var htmlMapper = new HTMLMapper();
  91276. var config = htmlMapper.map(baseElement);
  91277. var traverseChildren = function (element, partConfig) {
  91278. var children = element.children;
  91279. if (children.length) {
  91280. for (var i = 0; i < children.length; ++i) {
  91281. var item = children.item(i);
  91282. var configMapped = htmlMapper.map(item);
  91283. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91284. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91285. partConfig[key] = [];
  91286. }
  91287. else {
  91288. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91289. partConfig.push(configMapped);
  91290. }
  91291. else if (partConfig[key]) {
  91292. element.setAttribute('array', 'true');
  91293. var oldItem = partConfig[key];
  91294. partConfig = [oldItem, configMapped];
  91295. }
  91296. else {
  91297. partConfig[key] = configMapped;
  91298. }
  91299. }
  91300. traverseChildren(item, partConfig[key] || configMapped);
  91301. }
  91302. }
  91303. return partConfig;
  91304. };
  91305. traverseChildren(baseElement, config);
  91306. return config;
  91307. };
  91308. return DOMMapper;
  91309. }());
  91310. var MapperManager = (function () {
  91311. function MapperManager() {
  91312. this.mappers = {
  91313. "html": new HTMLMapper(),
  91314. "json": new JSONMapper(),
  91315. "dom": new DOMMapper()
  91316. };
  91317. }
  91318. MapperManager.prototype.getMapper = function (type) {
  91319. if (!this.mappers[type]) {
  91320. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91321. }
  91322. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91323. };
  91324. MapperManager.prototype.registerMapper = function (type, mapper) {
  91325. this.mappers[type] = mapper;
  91326. };
  91327. MapperManager.DefaultMapper = 'json';
  91328. return MapperManager;
  91329. }());
  91330. exports.MapperManager = MapperManager;
  91331. exports.mapperManager = new MapperManager();
  91332. /***/ }),
  91333. /* 2 */
  91334. /***/ (function(module, exports, __webpack_require__) {
  91335. "use strict";
  91336. Object.defineProperty(exports, "__esModule", { value: true });
  91337. function isUrl(urlToCheck) {
  91338. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91339. return true;
  91340. }
  91341. return false;
  91342. }
  91343. exports.isUrl = isUrl;
  91344. function kebabToCamel(s) {
  91345. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91346. }
  91347. exports.kebabToCamel = kebabToCamel;
  91348. function camelToKebab(str) {
  91349. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91350. }
  91351. exports.camelToKebab = camelToKebab;
  91352. /***/ }),
  91353. /* 3 */
  91354. /***/ (function(module, exports, __webpack_require__) {
  91355. "use strict";
  91356. Object.defineProperty(exports, "__esModule", { value: true });
  91357. var babylonjs_1 = __webpack_require__(0);
  91358. var ViewerManager = (function () {
  91359. function ViewerManager() {
  91360. this.viewers = {};
  91361. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91362. }
  91363. ViewerManager.prototype.addViewer = function (viewer) {
  91364. this.viewers[viewer.getBaseId()] = viewer;
  91365. this._onViewerAdded(viewer);
  91366. };
  91367. ViewerManager.prototype.getViewerById = function (id) {
  91368. return this.viewers[id];
  91369. };
  91370. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91371. for (var id in this.viewers) {
  91372. if (this.viewers[id].containerElement === element) {
  91373. return this.getViewerById(id);
  91374. }
  91375. }
  91376. };
  91377. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91378. var _this = this;
  91379. return new Promise(function (resolve, reject) {
  91380. var localViewer = _this.getViewerById(id);
  91381. if (localViewer) {
  91382. return resolve(localViewer);
  91383. }
  91384. var viewerFunction = function (viewer) {
  91385. if (viewer.getBaseId() === id) {
  91386. resolve(viewer);
  91387. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91388. }
  91389. };
  91390. _this.onViewerAddedObservable.add(viewerFunction);
  91391. });
  91392. };
  91393. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91394. this.onViewerAdded && this.onViewerAdded(viewer);
  91395. this.onViewerAddedObservable.notifyObservers(viewer);
  91396. };
  91397. return ViewerManager;
  91398. }());
  91399. exports.ViewerManager = ViewerManager;
  91400. exports.viewerManager = new ViewerManager();
  91401. /***/ }),
  91402. /* 4 */
  91403. /***/ (function(module, exports, __webpack_require__) {
  91404. "use strict";
  91405. var __extends = (this && this.__extends) || (function () {
  91406. var extendStatics = Object.setPrototypeOf ||
  91407. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91408. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91409. return function (d, b) {
  91410. extendStatics(d, b);
  91411. function __() { this.constructor = d; }
  91412. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91413. };
  91414. })();
  91415. Object.defineProperty(exports, "__esModule", { value: true });
  91416. var viewer_1 = __webpack_require__(5);
  91417. var babylonjs_1 = __webpack_require__(0);
  91418. var DefaultViewer = (function (_super) {
  91419. __extends(DefaultViewer, _super);
  91420. function DefaultViewer(containerElement, initialConfiguration) {
  91421. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91422. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91423. _this.containerElement = containerElement;
  91424. _this.onModelLoaded = function (model) {
  91425. var hideLoadingDelay = 500;
  91426. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91427. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91428. }
  91429. setTimeout(function () {
  91430. _this.hideLoadingScreen();
  91431. }, hideLoadingDelay);
  91432. return;
  91433. };
  91434. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91435. return _this;
  91436. }
  91437. DefaultViewer.prototype.initScene = function () {
  91438. var _this = this;
  91439. return _super.prototype.initScene.call(this).then(function () {
  91440. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91441. return _this.scene;
  91442. });
  91443. };
  91444. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91445. var _this = this;
  91446. this.showLoadingScreen();
  91447. this.initNavbar();
  91448. var closeButton = document.getElementById('close-button');
  91449. if (closeButton) {
  91450. closeButton.addEventListener('pointerdown', function () {
  91451. _this.hideOverlayScreen();
  91452. });
  91453. }
  91454. return _super.prototype.onTemplatesLoaded.call(this);
  91455. };
  91456. DefaultViewer.prototype.initNavbar = function () {
  91457. var navbar = this.templateManager.getTemplate('navBar');
  91458. if (navbar) {
  91459. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91460. var navbarShown_1 = true;
  91461. var timeoutCancel_1;
  91462. var triggerNavbar = function (show, evt) {
  91463. if (show === void 0) { show = false; }
  91464. if (!navbar || evt.button > 0)
  91465. return;
  91466. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91467. if (show === navbarShown_1)
  91468. return;
  91469. if (show) {
  91470. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91471. navbarShown_1 = show;
  91472. }
  91473. else {
  91474. var visibilityTimeout = 2000;
  91475. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91476. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91477. }
  91478. timeoutCancel_1 = setTimeout(function () {
  91479. if (navbar) {
  91480. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91481. }
  91482. navbarShown_1 = show;
  91483. }, visibilityTimeout);
  91484. }
  91485. };
  91486. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91487. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91488. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91489. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91490. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91491. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91492. var triggerFullscren = function (eventData) {
  91493. if (viewerElement_1) {
  91494. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91495. if (!fullscreenElement) {
  91496. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91497. requestFullScreen.call(viewerElement_1);
  91498. }
  91499. else {
  91500. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91501. exitFullscreen.call(document);
  91502. }
  91503. }
  91504. };
  91505. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91506. }
  91507. };
  91508. DefaultViewer.prototype.prepareContainerElement = function () {
  91509. this.containerElement.style.position = 'relative';
  91510. this.containerElement.style.display = 'flex';
  91511. };
  91512. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91513. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91514. var navbar = this.templateManager.getTemplate('navBar');
  91515. if (!navbar)
  91516. return;
  91517. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91518. if (metadataContainer) {
  91519. if (modelConfiguration.title !== undefined) {
  91520. var element = metadataContainer.querySelector('span.model-title');
  91521. if (element) {
  91522. element.innerHTML = modelConfiguration.title;
  91523. }
  91524. }
  91525. if (modelConfiguration.subtitle !== undefined) {
  91526. var element = metadataContainer.querySelector('span.model-subtitle');
  91527. if (element) {
  91528. element.innerHTML = modelConfiguration.subtitle;
  91529. }
  91530. }
  91531. if (modelConfiguration.thumbnail !== undefined) {
  91532. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91533. }
  91534. }
  91535. };
  91536. DefaultViewer.prototype.loadModel = function (model) {
  91537. var _this = this;
  91538. if (model === void 0) { model = this.configuration.model; }
  91539. this.showLoadingScreen();
  91540. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91541. console.log(error);
  91542. _this.hideLoadingScreen();
  91543. _this.showOverlayScreen('error');
  91544. return Promise.reject(error);
  91545. });
  91546. };
  91547. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91548. var _this = this;
  91549. var template = this.templateManager.getTemplate('overlay');
  91550. if (!template)
  91551. return Promise.resolve('Overlay template not found');
  91552. return template.show((function (template) {
  91553. var canvasRect = _this.containerElement.getBoundingClientRect();
  91554. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91555. template.parent.style.display = 'flex';
  91556. template.parent.style.width = canvasRect.width + "px";
  91557. template.parent.style.height = canvasRect.height + "px";
  91558. template.parent.style.opacity = "1";
  91559. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91560. if (!subTemplate) {
  91561. return Promise.reject(subScreen + ' template not found');
  91562. }
  91563. return subTemplate.show((function (template) {
  91564. template.parent.style.display = 'flex';
  91565. return Promise.resolve(template);
  91566. }));
  91567. }));
  91568. };
  91569. DefaultViewer.prototype.hideOverlayScreen = function () {
  91570. var template = this.templateManager.getTemplate('overlay');
  91571. if (!template)
  91572. return Promise.resolve('Overlay template not found');
  91573. return template.hide((function (template) {
  91574. template.parent.style.opacity = "0";
  91575. var onTransitionEnd = function () {
  91576. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91577. template.parent.style.display = 'none';
  91578. };
  91579. template.parent.addEventListener("transitionend", onTransitionEnd);
  91580. var overlays = template.parent.querySelectorAll('.overlay');
  91581. if (overlays) {
  91582. for (var i = 0; i < overlays.length; ++i) {
  91583. var htmlElement = overlays.item(i);
  91584. htmlElement.style.display = 'none';
  91585. }
  91586. }
  91587. return Promise.resolve(template);
  91588. }));
  91589. };
  91590. DefaultViewer.prototype.showLoadingScreen = function () {
  91591. var _this = this;
  91592. var template = this.templateManager.getTemplate('loadingScreen');
  91593. if (!template)
  91594. return Promise.resolve('Loading Screen template not found');
  91595. return template.show((function (template) {
  91596. var canvasRect = _this.containerElement.getBoundingClientRect();
  91597. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91598. template.parent.style.display = 'flex';
  91599. template.parent.style.width = canvasRect.width + "px";
  91600. template.parent.style.height = canvasRect.height + "px";
  91601. template.parent.style.opacity = "1";
  91602. template.parent.style.backgroundColor = "black";
  91603. return Promise.resolve(template);
  91604. }));
  91605. };
  91606. DefaultViewer.prototype.hideLoadingScreen = function () {
  91607. var template = this.templateManager.getTemplate('loadingScreen');
  91608. if (!template)
  91609. return Promise.resolve('Loading Screen template not found');
  91610. return template.hide((function (template) {
  91611. template.parent.style.opacity = "0";
  91612. var onTransitionEnd = function () {
  91613. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91614. template.parent.style.display = 'none';
  91615. };
  91616. template.parent.addEventListener("transitionend", onTransitionEnd);
  91617. return Promise.resolve(template);
  91618. }));
  91619. };
  91620. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91621. var _this = this;
  91622. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91623. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  91624. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91625. var pointerPosition = BABYLON.Vector3.Zero();
  91626. var lightTarget_1;
  91627. var angle = 0.5;
  91628. var exponent = Math.PI / 2;
  91629. if (typeof this.configuration.lab.flashlight === "object") {
  91630. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91631. angle = this.configuration.lab.flashlight.angle || angle;
  91632. }
  91633. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91634. if (typeof this.configuration.lab.flashlight === "object") {
  91635. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91636. if (this.configuration.lab.flashlight.diffuse) {
  91637. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91638. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91639. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91640. }
  91641. if (this.configuration.lab.flashlight.specular) {
  91642. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91643. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91644. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91645. }
  91646. }
  91647. this.scene.constantlyUpdateMeshUnderPointer = true;
  91648. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91649. if (eventData.type === 4 && eventData.pickInfo) {
  91650. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91651. }
  91652. else {
  91653. lightTarget_1 = undefined;
  91654. }
  91655. });
  91656. var updateFlashlightFunction = function () {
  91657. if (_this.camera && flashlight) {
  91658. flashlight.position.copyFrom(_this.camera.position);
  91659. if (lightTarget_1) {
  91660. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91661. }
  91662. }
  91663. };
  91664. this.scene.registerBeforeRender(updateFlashlightFunction);
  91665. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91666. }
  91667. };
  91668. return DefaultViewer;
  91669. }(viewer_1.AbstractViewer));
  91670. exports.DefaultViewer = DefaultViewer;
  91671. /***/ }),
  91672. /* 5 */
  91673. /***/ (function(module, exports, __webpack_require__) {
  91674. "use strict";
  91675. Object.defineProperty(exports, "__esModule", { value: true });
  91676. var viewerManager_1 = __webpack_require__(3);
  91677. var templateManager_1 = __webpack_require__(19);
  91678. var loader_1 = __webpack_require__(22);
  91679. var babylonjs_1 = __webpack_require__(0);
  91680. var deepmerge = __webpack_require__(13);
  91681. var viewerModel_1 = __webpack_require__(30);
  91682. var AbstractViewer = (function () {
  91683. function AbstractViewer(containerElement, initialConfiguration) {
  91684. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91685. var _this = this;
  91686. this.containerElement = containerElement;
  91687. this.resize = function () {
  91688. if (!_this.isCanvasInDOM()) {
  91689. return;
  91690. }
  91691. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91692. return;
  91693. }
  91694. _this.engine.resize();
  91695. };
  91696. this.render = function () {
  91697. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91698. };
  91699. if (containerElement.id) {
  91700. this.baseId = containerElement.id;
  91701. }
  91702. else {
  91703. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91704. }
  91705. this.onSceneInitObservable = new babylonjs_1.Observable();
  91706. this.onEngineInitObservable = new babylonjs_1.Observable();
  91707. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91708. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91709. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91710. this.onInitDoneObservable = new babylonjs_1.Observable();
  91711. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91712. this.registeredOnBeforerenderFunctions = [];
  91713. this.models = [];
  91714. viewerManager_1.viewerManager.addViewer(this);
  91715. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91716. this.prepareContainerElement();
  91717. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91718. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91719. if (_this.configuration.observers) {
  91720. _this.configureObservers(_this.configuration.observers);
  91721. }
  91722. var templateConfiguration = _this.configuration.templates || {};
  91723. _this.templateManager.initTemplate(templateConfiguration);
  91724. _this.templateManager.onAllLoaded.add(function () {
  91725. var canvas = _this.templateManager.getCanvas();
  91726. if (canvas) {
  91727. _this.canvas = canvas;
  91728. }
  91729. _this._onTemplateLoaded();
  91730. });
  91731. });
  91732. }
  91733. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91734. get: function () {
  91735. return this._hdrSupport;
  91736. },
  91737. enumerable: true,
  91738. configurable: true
  91739. });
  91740. AbstractViewer.prototype.getBaseId = function () {
  91741. return this.baseId;
  91742. };
  91743. AbstractViewer.prototype.isCanvasInDOM = function () {
  91744. return !!this.canvas && !!this.canvas.parentElement;
  91745. };
  91746. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91747. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91748. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91749. if (newConfiguration.scene) {
  91750. this.configureScene(newConfiguration.scene);
  91751. }
  91752. if (newConfiguration.optimizer) {
  91753. this.configureOptimizer(newConfiguration.optimizer);
  91754. }
  91755. if (newConfiguration.observers) {
  91756. this.configureObservers(newConfiguration.observers);
  91757. }
  91758. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91759. this.configureModel(newConfiguration.model);
  91760. }
  91761. if (newConfiguration.lights) {
  91762. this.configureLights(newConfiguration.lights);
  91763. }
  91764. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91765. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91766. }
  91767. if (newConfiguration.camera) {
  91768. this.configureCamera(newConfiguration.camera);
  91769. }
  91770. };
  91771. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91772. if (!skyboxConifguration && !groundConfiguration) {
  91773. if (this.environmentHelper) {
  91774. this.environmentHelper.dispose();
  91775. delete this.environmentHelper;
  91776. }
  91777. ;
  91778. return Promise.resolve(this.scene);
  91779. }
  91780. var options = {
  91781. createGround: !!groundConfiguration,
  91782. createSkybox: !!skyboxConifguration,
  91783. setupImageProcessing: false
  91784. };
  91785. if (groundConfiguration) {
  91786. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91787. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91788. if (groundSize) {
  91789. options.groundSize = groundSize;
  91790. }
  91791. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91792. if (groundConfig.shadowLevel !== undefined) {
  91793. options.groundShadowLevel = groundConfig.shadowLevel;
  91794. }
  91795. options.enableGroundMirror = !!groundConfig.mirror;
  91796. if (groundConfig.texture) {
  91797. options.groundTexture = groundConfig.texture;
  91798. }
  91799. if (groundConfig.color) {
  91800. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91801. }
  91802. if (groundConfig.opacity !== undefined) {
  91803. options.groundOpacity = groundConfig.opacity;
  91804. }
  91805. if (groundConfig.mirror) {
  91806. options.enableGroundMirror = true;
  91807. if (typeof groundConfig.mirror === "object") {
  91808. if (groundConfig.mirror.amount !== undefined)
  91809. options.groundMirrorAmount = groundConfig.mirror.amount;
  91810. if (groundConfig.mirror.sizeRatio !== undefined)
  91811. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91812. if (groundConfig.mirror.blurKernel !== undefined)
  91813. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91814. if (groundConfig.mirror.fresnelWeight !== undefined)
  91815. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91816. if (groundConfig.mirror.fallOffDistance !== undefined)
  91817. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91818. if (this.defaultPipelineTextureType !== undefined)
  91819. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91820. }
  91821. }
  91822. }
  91823. var postInitSkyboxMaterial = false;
  91824. if (skyboxConifguration) {
  91825. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91826. if (conf.material && conf.material.imageProcessingConfiguration) {
  91827. options.setupImageProcessing = false;
  91828. }
  91829. var skyboxSize = conf.scale;
  91830. if (skyboxSize) {
  91831. options.skyboxSize = skyboxSize;
  91832. }
  91833. options.sizeAuto = !options.skyboxSize;
  91834. if (conf.color) {
  91835. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91836. }
  91837. if (conf.cubeTexture && conf.cubeTexture.url) {
  91838. if (typeof conf.cubeTexture.url === "string") {
  91839. options.skyboxTexture = conf.cubeTexture.url;
  91840. }
  91841. else {
  91842. postInitSkyboxMaterial = true;
  91843. }
  91844. }
  91845. if (conf.material && conf.material.imageProcessingConfiguration) {
  91846. postInitSkyboxMaterial = true;
  91847. }
  91848. }
  91849. options.setupImageProcessing = false;
  91850. if (!this.environmentHelper) {
  91851. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91852. }
  91853. else {
  91854. var scene = this.environmentHelper.rootMesh.getScene();
  91855. if (scene !== this.scene) {
  91856. this.environmentHelper.dispose();
  91857. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91858. }
  91859. else {
  91860. this.environmentHelper.updateOptions(options);
  91861. }
  91862. }
  91863. if (postInitSkyboxMaterial) {
  91864. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  91865. if (skyboxMaterial) {
  91866. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  91867. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  91868. }
  91869. }
  91870. }
  91871. };
  91872. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  91873. if (!this.scene) {
  91874. return;
  91875. }
  91876. if (sceneConfig.debug) {
  91877. this.scene.debugLayer.show();
  91878. }
  91879. else {
  91880. if (this.scene.debugLayer.isVisible()) {
  91881. this.scene.debugLayer.hide();
  91882. }
  91883. }
  91884. if (sceneConfig.clearColor) {
  91885. var cc = sceneConfig.clearColor;
  91886. var oldcc = this.scene.clearColor;
  91887. if (cc.r !== undefined) {
  91888. oldcc.r = cc.r;
  91889. }
  91890. if (cc.g !== undefined) {
  91891. oldcc.g = cc.g;
  91892. }
  91893. if (cc.b !== undefined) {
  91894. oldcc.b = cc.b;
  91895. }
  91896. if (cc.a !== undefined) {
  91897. oldcc.a = cc.a;
  91898. }
  91899. }
  91900. if (sceneConfig.imageProcessingConfiguration) {
  91901. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  91902. }
  91903. if (sceneConfig.environmentTexture) {
  91904. if (this.scene.environmentTexture) {
  91905. this.scene.environmentTexture.dispose();
  91906. }
  91907. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  91908. this.scene.environmentTexture = environmentTexture;
  91909. }
  91910. if (sceneConfig.autoRotate) {
  91911. this.camera.useAutoRotationBehavior = true;
  91912. }
  91913. };
  91914. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  91915. if (typeof optimizerConfig === 'boolean') {
  91916. if (this.sceneOptimizer) {
  91917. this.sceneOptimizer.stop();
  91918. this.sceneOptimizer.dispose();
  91919. delete this.sceneOptimizer;
  91920. }
  91921. if (optimizerConfig) {
  91922. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  91923. this.sceneOptimizer.start();
  91924. }
  91925. }
  91926. else {
  91927. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  91928. if (optimizerConfig.degradation) {
  91929. switch (optimizerConfig.degradation) {
  91930. case "low":
  91931. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  91932. break;
  91933. case "moderate":
  91934. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  91935. break;
  91936. case "hight":
  91937. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  91938. break;
  91939. }
  91940. }
  91941. if (this.sceneOptimizer) {
  91942. this.sceneOptimizer.stop();
  91943. this.sceneOptimizer.dispose();
  91944. }
  91945. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  91946. this.sceneOptimizer.start();
  91947. }
  91948. };
  91949. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  91950. if (observersConfiguration.onEngineInit) {
  91951. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  91952. }
  91953. else {
  91954. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  91955. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  91956. }
  91957. }
  91958. if (observersConfiguration.onSceneInit) {
  91959. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  91960. }
  91961. else {
  91962. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  91963. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  91964. }
  91965. }
  91966. if (observersConfiguration.onModelLoaded) {
  91967. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  91968. }
  91969. else {
  91970. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  91971. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  91972. }
  91973. }
  91974. };
  91975. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  91976. var _this = this;
  91977. var focusMeshes = model ? model.meshes : this.scene.meshes;
  91978. if (!this.scene.activeCamera) {
  91979. this.scene.createDefaultCamera(true, true, true);
  91980. this.camera = this.scene.activeCamera;
  91981. }
  91982. if (cameraConfig.position) {
  91983. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  91984. }
  91985. if (cameraConfig.rotation) {
  91986. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  91987. }
  91988. this.extendClassWithConfig(this.camera, cameraConfig);
  91989. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  91990. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  91991. if (cameraConfig.behaviors) {
  91992. for (var name_1 in cameraConfig.behaviors) {
  91993. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  91994. }
  91995. }
  91996. ;
  91997. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  91998. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  91999. });
  92000. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92001. var sceneDiagonalLenght = sceneDiagonal.length();
  92002. if (isFinite(sceneDiagonalLenght))
  92003. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92004. };
  92005. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92006. var _this = this;
  92007. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92008. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92009. if (!Object.keys(lightsConfiguration).length)
  92010. return;
  92011. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92012. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92013. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92014. lightsAvailable.forEach(function (lName) {
  92015. if (lightsToConfigure.indexOf(lName) === -1) {
  92016. _this.scene.getLightByName(lName).dispose();
  92017. }
  92018. });
  92019. }
  92020. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92021. var lightConfig = { type: 0 };
  92022. if (typeof lightsConfiguration[name] === 'object') {
  92023. lightConfig = lightsConfiguration[name];
  92024. }
  92025. lightConfig.name = name;
  92026. var light;
  92027. if (lightsAvailable.indexOf(name) === -1) {
  92028. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92029. if (!constructor)
  92030. return;
  92031. light = constructor();
  92032. }
  92033. else {
  92034. light = _this.scene.getLightByName(name);
  92035. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92036. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92037. light.dispose();
  92038. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92039. if (!constructor)
  92040. return;
  92041. light = constructor();
  92042. }
  92043. }
  92044. if (lightsConfiguration[name] === false) {
  92045. light.dispose();
  92046. return;
  92047. }
  92048. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92049. light.setEnabled(enabled);
  92050. _this.extendClassWithConfig(light, lightConfig);
  92051. if (light instanceof babylonjs_1.ShadowLight) {
  92052. if (lightConfig.target) {
  92053. if (light.setDirectionToTarget) {
  92054. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92055. light.setDirectionToTarget(target);
  92056. }
  92057. }
  92058. else if (lightConfig.direction) {
  92059. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92060. light.direction = direction;
  92061. }
  92062. var shadowGenerator = light.getShadowGenerator();
  92063. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92064. if (!shadowGenerator) {
  92065. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92066. }
  92067. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92068. var shadownMap = shadowGenerator.getShadowMap();
  92069. if (!shadownMap)
  92070. return;
  92071. var renderList = shadownMap.renderList;
  92072. for (var index = 0; index < focusMeshes.length; index++) {
  92073. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92074. renderList && renderList.push(focusMeshes[index]);
  92075. }
  92076. }
  92077. }
  92078. else if (shadowGenerator) {
  92079. shadowGenerator.dispose();
  92080. }
  92081. }
  92082. });
  92083. };
  92084. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92085. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92086. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92087. var updateMeshesWithNoParent = function (variable, value, param) {
  92088. meshesWithNoParent.forEach(function (mesh) {
  92089. if (param) {
  92090. mesh[variable][param] = value;
  92091. }
  92092. else {
  92093. mesh[variable] = value;
  92094. }
  92095. });
  92096. };
  92097. var updateXYZ = function (variable, configValues) {
  92098. if (configValues.x !== undefined) {
  92099. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92100. }
  92101. if (configValues.y !== undefined) {
  92102. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92103. }
  92104. if (configValues.z !== undefined) {
  92105. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92106. }
  92107. if (configValues.w !== undefined) {
  92108. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92109. }
  92110. };
  92111. if (modelConfiguration.position) {
  92112. updateXYZ('position', modelConfiguration.position);
  92113. }
  92114. if (modelConfiguration.rotation) {
  92115. if (modelConfiguration.rotation.w) {
  92116. meshesWithNoParent.forEach(function (mesh) {
  92117. if (!mesh.rotationQuaternion) {
  92118. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92119. }
  92120. });
  92121. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92122. }
  92123. else {
  92124. updateXYZ('rotation', modelConfiguration.rotation);
  92125. }
  92126. }
  92127. if (modelConfiguration.scaling) {
  92128. updateXYZ('scaling', modelConfiguration.scaling);
  92129. }
  92130. if (modelConfiguration.castShadow) {
  92131. focusMeshes.forEach(function (mesh) {
  92132. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92133. });
  92134. }
  92135. if (modelConfiguration.normalize) {
  92136. var center = false;
  92137. var unitSize = false;
  92138. var parentIndex = void 0;
  92139. if (modelConfiguration.normalize === true) {
  92140. center = true;
  92141. unitSize = true;
  92142. parentIndex = 0;
  92143. }
  92144. else {
  92145. center = !!modelConfiguration.normalize.center;
  92146. unitSize = !!modelConfiguration.normalize.unitSize;
  92147. parentIndex = modelConfiguration.normalize.parentIndex;
  92148. }
  92149. var meshesToNormalize = [];
  92150. if (parentIndex !== undefined) {
  92151. meshesToNormalize.push(focusMeshes[parentIndex]);
  92152. }
  92153. else {
  92154. meshesToNormalize = meshesWithNoParent;
  92155. }
  92156. if (unitSize) {
  92157. meshesToNormalize.forEach(function (mesh) {
  92158. mesh.normalizeToUnitCube(true);
  92159. mesh.computeWorldMatrix(true);
  92160. });
  92161. }
  92162. if (center) {
  92163. meshesToNormalize.forEach(function (mesh) {
  92164. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92165. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92166. var halfSizeVec = sizeVec.scale(0.5);
  92167. var center = boundingInfo.min.add(halfSizeVec);
  92168. mesh.position = center.scale(-1);
  92169. mesh.position.y += halfSizeVec.y;
  92170. mesh.computeWorldMatrix(true);
  92171. });
  92172. }
  92173. }
  92174. };
  92175. AbstractViewer.prototype.dispose = function () {
  92176. window.removeEventListener('resize', this.resize);
  92177. if (this.sceneOptimizer) {
  92178. this.sceneOptimizer.stop();
  92179. this.sceneOptimizer.dispose();
  92180. }
  92181. if (this.scene.activeCamera) {
  92182. this.scene.activeCamera.detachControl(this.canvas);
  92183. }
  92184. this.scene.dispose();
  92185. this.engine.dispose();
  92186. this.templateManager.dispose();
  92187. };
  92188. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92189. return Promise.resolve(this);
  92190. };
  92191. AbstractViewer.prototype._onTemplateLoaded = function () {
  92192. var _this = this;
  92193. return this.onTemplatesLoaded().then(function () {
  92194. var autoLoadModel = !!_this.configuration.model;
  92195. return _this.initEngine().then(function (engine) {
  92196. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92197. }).then(function () {
  92198. if (autoLoadModel) {
  92199. return _this.loadModel().then(function () { return _this.scene; });
  92200. }
  92201. else {
  92202. return _this.scene || _this.initScene();
  92203. }
  92204. }).then(function (scene) {
  92205. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92206. }).then(function () {
  92207. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92208. });
  92209. });
  92210. };
  92211. AbstractViewer.prototype.initEngine = function () {
  92212. this.injectCustomShaders();
  92213. var canvasElement = this.templateManager.getCanvas();
  92214. if (!canvasElement) {
  92215. return Promise.reject('Canvas element not found!');
  92216. }
  92217. var config = this.configuration.engine || {};
  92218. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92219. babylonjs_1.Database.IDBStorageEnabled = false;
  92220. if (!config.disableResize) {
  92221. window.addEventListener('resize', this.resize);
  92222. }
  92223. this.engine.runRenderLoop(this.render);
  92224. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92225. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92226. this.engine.setHardwareScalingLevel(scale);
  92227. }
  92228. this.handleHardwareLimitations();
  92229. return Promise.resolve(this.engine);
  92230. };
  92231. AbstractViewer.prototype.initScene = function () {
  92232. if (this.scene) {
  92233. this.scene.dispose();
  92234. }
  92235. this.scene = new babylonjs_1.Scene(this.engine);
  92236. this.scene.createDefaultLight(true);
  92237. if (this.configuration.scene) {
  92238. this.configureScene(this.configuration.scene);
  92239. if (this.configuration.optimizer) {
  92240. this.configureOptimizer(this.configuration.optimizer);
  92241. }
  92242. }
  92243. return Promise.resolve(this.scene);
  92244. };
  92245. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92246. var _this = this;
  92247. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92248. if (clearScene === void 0) { clearScene = true; }
  92249. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92250. if (!modelUrl) {
  92251. return Promise.reject("no model configuration found");
  92252. }
  92253. if (this.isLoading) {
  92254. return Promise.reject("sanother model is curently being loaded.");
  92255. }
  92256. this.isLoading = true;
  92257. if ((typeof modelConfig === 'string')) {
  92258. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92259. this.configuration.model.url = modelConfig;
  92260. }
  92261. }
  92262. else {
  92263. if (this.configuration.model) {
  92264. deepmerge(this.configuration.model, modelConfig);
  92265. }
  92266. else {
  92267. this.configuration.model = modelConfig;
  92268. }
  92269. }
  92270. return Promise.resolve(this.scene).then(function (scene) {
  92271. if (!scene)
  92272. return _this.initScene();
  92273. if (clearScene) {
  92274. _this.models.forEach(function (m) { return m.dispose(); });
  92275. _this.models.length = 0;
  92276. }
  92277. return scene;
  92278. }).then(function () {
  92279. return new Promise(function (resolve, reject) {
  92280. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92281. _this.models.push(model);
  92282. _this.lastUsedLoader = model.loader;
  92283. model.onLoadedObservable.add(function (model) {
  92284. resolve(model);
  92285. });
  92286. model.onLoadErrorObservable.add(function (errorObject) {
  92287. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92288. reject(errorObject.exception);
  92289. });
  92290. });
  92291. model.onLoadProgressObservable.add(function (progressEvent) {
  92292. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92293. });
  92294. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92295. });
  92296. }).then(function (model) {
  92297. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92298. .then(function () {
  92299. _this.configureModel(_this.configuration.model || modelConfig, model);
  92300. _this.configureLights(_this.configuration.lights);
  92301. if (_this.configuration.camera) {
  92302. _this.configureCamera(_this.configuration.camera, model);
  92303. }
  92304. return _this.initEnvironment(model);
  92305. }).then(function () {
  92306. _this.isLoading = false;
  92307. return model;
  92308. });
  92309. });
  92310. };
  92311. AbstractViewer.prototype.initEnvironment = function (model) {
  92312. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92313. return Promise.resolve(this.scene);
  92314. };
  92315. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92316. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92317. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92318. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92319. this.maxShadows = 0;
  92320. }
  92321. else {
  92322. this.maxShadows = 3;
  92323. }
  92324. var caps = this.engine.getCaps();
  92325. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92326. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92327. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92328. if (linearHalfFloatTargets) {
  92329. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92330. this.shadowGeneratorBias = 0.002;
  92331. }
  92332. else if (linearFloatTargets) {
  92333. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92334. this.shadowGeneratorBias = 0.001;
  92335. }
  92336. else {
  92337. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92338. this.shadowGeneratorBias = 0.001;
  92339. }
  92340. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92341. };
  92342. AbstractViewer.prototype.injectCustomShaders = function () {
  92343. var customShaders = this.configuration.customShaders;
  92344. if (!customShaders) {
  92345. return;
  92346. }
  92347. if (customShaders.shaders) {
  92348. Object.keys(customShaders.shaders).forEach(function (key) {
  92349. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92350. });
  92351. }
  92352. if (customShaders.includes) {
  92353. Object.keys(customShaders.includes).forEach(function (key) {
  92354. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92355. });
  92356. }
  92357. };
  92358. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92359. var _this = this;
  92360. if (!config)
  92361. return;
  92362. Object.keys(config).forEach(function (key) {
  92363. if (key in object && typeof object[key] !== 'function') {
  92364. if (typeof object[key] === 'object') {
  92365. _this.extendClassWithConfig(object[key], config[key]);
  92366. }
  92367. else {
  92368. if (config[key] !== undefined) {
  92369. object[key] = config[key];
  92370. }
  92371. }
  92372. }
  92373. });
  92374. };
  92375. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92376. var behavior;
  92377. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92378. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92379. switch (type) {
  92380. case 0:
  92381. this.camera.useAutoRotationBehavior = true;
  92382. behavior = this.camera.autoRotationBehavior;
  92383. break;
  92384. case 1:
  92385. this.camera.useBouncingBehavior = true;
  92386. behavior = this.camera.bouncingBehavior;
  92387. break;
  92388. case 2:
  92389. this.camera.useFramingBehavior = true;
  92390. behavior = this.camera.framingBehavior;
  92391. break;
  92392. default:
  92393. behavior = null;
  92394. break;
  92395. }
  92396. if (behavior) {
  92397. if (typeof behaviorConfig === "object") {
  92398. this.extendClassWithConfig(behavior, behaviorConfig);
  92399. }
  92400. }
  92401. switch (type) {
  92402. case 0:
  92403. break;
  92404. case 1:
  92405. break;
  92406. case 2:
  92407. if (config.zoomOnBoundingInfo) {
  92408. var meshes = payload;
  92409. var bounding = meshes[0].getHierarchyBoundingVectors();
  92410. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92411. }
  92412. break;
  92413. }
  92414. };
  92415. return AbstractViewer;
  92416. }());
  92417. exports.AbstractViewer = AbstractViewer;
  92418. /***/ }),
  92419. /* 6 */
  92420. /***/ (function(module, exports) {
  92421. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92422. /***/ }),
  92423. /* 7 */
  92424. /***/ (function(module, exports) {
  92425. 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}}>";
  92426. /***/ }),
  92427. /* 8 */
  92428. /***/ (function(module, exports) {
  92429. 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=="
  92430. /***/ }),
  92431. /* 9 */
  92432. /***/ (function(module, exports) {
  92433. 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>";
  92434. /***/ }),
  92435. /* 10 */
  92436. /***/ (function(module, exports) {
  92437. 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>";
  92438. /***/ }),
  92439. /* 11 */
  92440. /***/ (function(module, exports) {
  92441. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92442. /***/ }),
  92443. /* 12 */
  92444. /***/ (function(module, exports) {
  92445. module.exports = "Error loading the model";
  92446. /***/ }),
  92447. /* 13 */
  92448. /***/ (function(module, exports, __webpack_require__) {
  92449. (function (global, factory) {
  92450. true ? module.exports = factory() :
  92451. typeof define === 'function' && define.amd ? define(factory) :
  92452. (global.deepmerge = factory());
  92453. }(this, (function () { 'use strict';
  92454. var isMergeableObject = function isMergeableObject(value) {
  92455. return isNonNullObject(value)
  92456. && !isSpecial(value)
  92457. };
  92458. function isNonNullObject(value) {
  92459. return !!value && typeof value === 'object'
  92460. }
  92461. function isSpecial(value) {
  92462. var stringValue = Object.prototype.toString.call(value);
  92463. return stringValue === '[object RegExp]'
  92464. || stringValue === '[object Date]'
  92465. || isReactElement(value)
  92466. }
  92467. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92468. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92469. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92470. function isReactElement(value) {
  92471. return value.$$typeof === REACT_ELEMENT_TYPE
  92472. }
  92473. function emptyTarget(val) {
  92474. return Array.isArray(val) ? [] : {}
  92475. }
  92476. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92477. var clone = !optionsArgument || optionsArgument.clone !== false;
  92478. return (clone && isMergeableObject(value))
  92479. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92480. : value
  92481. }
  92482. function defaultArrayMerge(target, source, optionsArgument) {
  92483. return target.concat(source).map(function(element) {
  92484. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92485. })
  92486. }
  92487. function mergeObject(target, source, optionsArgument) {
  92488. var destination = {};
  92489. if (isMergeableObject(target)) {
  92490. Object.keys(target).forEach(function(key) {
  92491. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92492. });
  92493. }
  92494. Object.keys(source).forEach(function(key) {
  92495. if (!isMergeableObject(source[key]) || !target[key]) {
  92496. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92497. } else {
  92498. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92499. }
  92500. });
  92501. return destination
  92502. }
  92503. function deepmerge(target, source, optionsArgument) {
  92504. var sourceIsArray = Array.isArray(source);
  92505. var targetIsArray = Array.isArray(target);
  92506. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92507. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92508. if (!sourceAndTargetTypesMatch) {
  92509. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92510. } else if (sourceIsArray) {
  92511. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92512. return arrayMerge(target, source, optionsArgument)
  92513. } else {
  92514. return mergeObject(target, source, optionsArgument)
  92515. }
  92516. }
  92517. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92518. if (!Array.isArray(array)) {
  92519. throw new Error('first argument should be an array')
  92520. }
  92521. return array.reduce(function(prev, next) {
  92522. return deepmerge(prev, next, optionsArgument)
  92523. }, {})
  92524. };
  92525. var deepmerge_1 = deepmerge;
  92526. return deepmerge_1;
  92527. })));
  92528. /***/ }),
  92529. /* 14 */
  92530. /***/ (function(module, exports, __webpack_require__) {
  92531. module.exports = __webpack_require__(15);
  92532. /***/ }),
  92533. /* 15 */
  92534. /***/ (function(module, exports, __webpack_require__) {
  92535. "use strict";
  92536. Object.defineProperty(exports, "__esModule", { value: true });
  92537. var mappers_1 = __webpack_require__(1);
  92538. exports.mapperManager = mappers_1.mapperManager;
  92539. var viewerManager_1 = __webpack_require__(3);
  92540. exports.viewerManager = viewerManager_1.viewerManager;
  92541. var defaultViewer_1 = __webpack_require__(4);
  92542. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92543. var viewer_1 = __webpack_require__(5);
  92544. exports.AbstractViewer = viewer_1.AbstractViewer;
  92545. var babylonjs_1 = __webpack_require__(0);
  92546. __webpack_require__(32);
  92547. __webpack_require__(33);
  92548. var initializer_1 = __webpack_require__(34);
  92549. exports.InitTags = initializer_1.InitTags;
  92550. babylonjs_1.PromisePolyfill.Apply();
  92551. exports.disableInit = false;
  92552. document.addEventListener("DOMContentLoaded", function (event) {
  92553. if (exports.disableInit)
  92554. return;
  92555. initializer_1.InitTags();
  92556. });
  92557. /***/ }),
  92558. /* 16 */
  92559. /***/ (function(module, exports) {
  92560. var g;
  92561. // This works in non-strict mode
  92562. g = (function() {
  92563. return this;
  92564. })();
  92565. try {
  92566. // This works if eval is allowed (see CSP)
  92567. g = g || Function("return this")() || (1,eval)("this");
  92568. } catch(e) {
  92569. // This works if the window reference is available
  92570. if(typeof window === "object")
  92571. g = window;
  92572. }
  92573. // g can still be undefined, but nothing to do about it...
  92574. // We return undefined, instead of nothing here, so it's
  92575. // easier to handle this case. if(!global) { ...}
  92576. module.exports = g;
  92577. /***/ }),
  92578. /* 17 */
  92579. /***/ (function(module, exports) {
  92580. module.exports = cannon;
  92581. /***/ }),
  92582. /* 18 */
  92583. /***/ (function(module, exports, __webpack_require__) {
  92584. /**
  92585. * from OimoPhysics DEV 1.1.0a AS3
  92586. * @author Saharan / http://el-ement.com/
  92587. *
  92588. * to Oimo.js 2015 JAVASCRIPT
  92589. * @author LoTh / http://lo-th.github.io/labs/
  92590. */
  92591. var OIMO = {
  92592. REVISION: "1.2",
  92593. // Global identification of next shape.
  92594. // This will be incremented every time a shape is created.
  92595. nextID: 0,
  92596. proxyID: 0,
  92597. // BroadPhase
  92598. BR_NULL: 0,
  92599. BR_BRUTE_FORCE: 1,
  92600. BR_SWEEP_AND_PRUNE: 2,
  92601. BR_BOUNDING_VOLUME_TREE: 3,
  92602. // body type
  92603. BODY_NULL: 0,
  92604. BODY_DYNAMIC: 1,
  92605. BODY_STATIC: 2,
  92606. // shape type
  92607. SHAPE_NULL: 0,
  92608. SHAPE_SPHERE: 1,
  92609. SHAPE_BOX: 2,
  92610. SHAPE_CYLINDER: 3,
  92611. SHAPE_TETRA: 4,
  92612. // joint type
  92613. JOINT_NULL: 0,
  92614. JOINT_DISTANCE: 1,
  92615. JOINT_BALL_AND_SOCKET: 2,
  92616. JOINT_HINGE: 3,
  92617. JOINT_WHEEL: 4,
  92618. JOINT_SLIDER: 5,
  92619. JOINT_PRISMATIC: 6,
  92620. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92621. // scale all by 100 so object is between 10 to 10000 three unit.
  92622. WORLD_SCALE: 100,
  92623. INV_SCALE: 0.01,
  92624. // AABB aproximation
  92625. AABB_PROX: 0.005,
  92626. // Math function
  92627. sqrt: Math.sqrt,
  92628. abs: Math.abs,
  92629. floor: Math.floor,
  92630. cos: Math.cos,
  92631. sin: Math.sin,
  92632. acos: Math.acos,
  92633. asin: Math.asin,
  92634. atan2: Math.atan2,
  92635. round: Math.round,
  92636. pow: Math.pow,
  92637. max: Math.max,
  92638. min: Math.min,
  92639. random: Math.random,
  92640. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92641. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92642. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92643. int: function (x) { return ~~x; },
  92644. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92645. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92646. degtorad: 0.0174532925199432957,
  92647. radtodeg: 57.295779513082320876,
  92648. PI: 3.141592653589793,
  92649. TwoPI: 6.283185307179586,
  92650. PI90: 1.570796326794896,
  92651. PI270: 4.712388980384689,
  92652. CustomError: null,
  92653. Error: function (Class, Msg) {
  92654. if (OIMO.CustomError == null) console.error(Class, Msg);
  92655. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92656. }
  92657. };
  92658. var OIMO_ARRAY_TYPE;
  92659. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92660. try {
  92661. (function (w) {
  92662. var perfNow;
  92663. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92664. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92665. var n = perfNowNames[i];
  92666. if (!!w['performance'][n]) {
  92667. perfNow = function () { return w['performance'][n]() };
  92668. break;
  92669. }
  92670. }
  92671. if (!perfNow) perfNow = Date.now;
  92672. //w.perfNow = perfNow;
  92673. OIMO.now = perfNow;
  92674. })(window);
  92675. } catch (e) { OIMO.now = function () { return 0; }; }
  92676. /**
  92677. * The class of physical computing world.
  92678. * You must be added to the world physical all computing objects
  92679. * @author saharan
  92680. * @author lo-th
  92681. */
  92682. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92683. // The time between each step
  92684. this.timeStep = TimeStep || 0.01666; // 1/60;
  92685. // The number of iterations for constraint solvers.
  92686. this.numIterations = Iterations || 8;
  92687. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92688. switch (BroadPhaseType || 2) {
  92689. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92690. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92691. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92692. }
  92693. // This is the detailed information of the performance.
  92694. this.performance = null;
  92695. this.isNoStat = NoStat || false;
  92696. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92697. // Whether the constraints randomizer is enabled or not.
  92698. this.enableRandomizer = true;
  92699. // The rigid body list
  92700. this.rigidBodies = null;
  92701. // number of rigid body
  92702. this.numRigidBodies = 0;
  92703. // The contact list
  92704. this.contacts = null;
  92705. this.unusedContacts = null;
  92706. // The number of contact
  92707. this.numContacts = 0;
  92708. // The number of contact points
  92709. this.numContactPoints = 0;
  92710. // The joint list
  92711. this.joints = null;
  92712. // The number of joints.
  92713. this.numJoints = 0;
  92714. // The number of simulation islands.
  92715. this.numIslands = 0;
  92716. // The gravity in the world.
  92717. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92718. var numShapeTypes = 5;//4;//3;
  92719. this.detectors = [];
  92720. this.detectors.length = numShapeTypes;
  92721. var i = numShapeTypes;
  92722. while (i--) {
  92723. this.detectors[i] = [];
  92724. this.detectors[i].length = numShapeTypes;
  92725. }
  92726. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92727. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92728. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92729. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92730. // CYLINDER add
  92731. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92732. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92733. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92734. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92735. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92736. // TETRA add
  92737. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92738. this.randX = 65535;
  92739. this.randA = 98765;
  92740. this.randB = 123456789;
  92741. //this.maxIslandRigidBodies = 64;
  92742. this.islandRigidBodies = [];
  92743. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92744. this.islandStack = [];
  92745. //this.islandStack.length = this.maxIslandRigidBodies;
  92746. //this.maxIslandConstraints = 128;
  92747. this.islandConstraints = [];
  92748. //this.islandConstraints.length = this.maxIslandConstraints;
  92749. };
  92750. OIMO.World.prototype = {
  92751. constructor: OIMO.World,
  92752. /**
  92753. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92754. */
  92755. clear: function () {
  92756. this.randX = 65535;
  92757. while (this.joints !== null) {
  92758. this.removeJoint(this.joints);
  92759. }
  92760. while (this.contacts !== null) {
  92761. this.removeContact(this.contacts);
  92762. }
  92763. while (this.rigidBodies !== null) {
  92764. this.removeRigidBody(this.rigidBodies);
  92765. }
  92766. OIMO.nextID = 0;
  92767. OIMO.proxyID = 0;
  92768. },
  92769. /**
  92770. * I'll add a rigid body to the world.
  92771. * Rigid body that has been added will be the operands of each step.
  92772. * @param rigidBody Rigid body that you want to add
  92773. */
  92774. addRigidBody: function (rigidBody) {
  92775. if (rigidBody.parent) {
  92776. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92777. }
  92778. rigidBody.parent = this;
  92779. rigidBody.awake();
  92780. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92781. this.addShape(shape);
  92782. }
  92783. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92784. this.rigidBodies = rigidBody;
  92785. this.numRigidBodies++;
  92786. },
  92787. /**
  92788. * I will remove the rigid body from the world.
  92789. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92790. * @param rigidBody Rigid body to be removed
  92791. */
  92792. removeRigidBody: function (rigidBody) {
  92793. var remove = rigidBody;
  92794. if (remove.parent !== this) return;
  92795. remove.awake();
  92796. var js = remove.jointLink;
  92797. while (js != null) {
  92798. var joint = js.joint;
  92799. js = js.next;
  92800. this.removeJoint(joint);
  92801. }
  92802. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92803. this.removeShape(shape);
  92804. }
  92805. var prev = remove.prev;
  92806. var next = remove.next;
  92807. if (prev !== null) prev.next = next;
  92808. if (next !== null) next.prev = prev;
  92809. if (this.rigidBodies == remove) this.rigidBodies = next;
  92810. remove.prev = null;
  92811. remove.next = null;
  92812. remove.parent = null;
  92813. this.numRigidBodies--;
  92814. },
  92815. getByName: function (name) {
  92816. var result = null;
  92817. var body = this.rigidBodies;
  92818. while (body !== null) {
  92819. if (body.name !== " " && body.name === name) result = body;
  92820. body = body.next;
  92821. }
  92822. var joint = this.joints;
  92823. while (joint !== null) {
  92824. if (joint.name !== "" && joint.name === name) result = joint;
  92825. joint = joint.next;
  92826. }
  92827. return result;
  92828. },
  92829. /**
  92830. * I'll add a shape to the world..
  92831. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92832. * Shape will be added to the world automatically, please do not call from outside this method.
  92833. * @param shape Shape you want to add
  92834. */
  92835. addShape: function (shape) {
  92836. if (!shape.parent || !shape.parent.parent) {
  92837. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92838. }
  92839. shape.proxy = this.broadPhase.createProxy(shape);
  92840. shape.updateProxy();
  92841. this.broadPhase.addProxy(shape.proxy);
  92842. },
  92843. /**
  92844. * I will remove the shape from the world.
  92845. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92846. * Shape will be added to the world automatically, please do not call from outside this method.
  92847. * @param shape Shape you want to delete
  92848. */
  92849. removeShape: function (shape) {
  92850. this.broadPhase.removeProxy(shape.proxy);
  92851. shape.proxy = null;
  92852. },
  92853. /**
  92854. * I'll add a joint to the world.
  92855. * Joint that has been added will be the operands of each step.
  92856. * @param shape Joint to be added
  92857. */
  92858. addJoint: function (joint) {
  92859. if (joint.parent) {
  92860. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92861. }
  92862. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  92863. this.joints = joint;
  92864. joint.parent = this;
  92865. this.numJoints++;
  92866. joint.awake();
  92867. joint.attach();
  92868. },
  92869. /**
  92870. * I will remove the joint from the world.
  92871. * Joint that has been added will be the operands of each step.
  92872. * @param shape Joint to be deleted
  92873. */
  92874. removeJoint: function (joint) {
  92875. var remove = joint;
  92876. var prev = remove.prev;
  92877. var next = remove.next;
  92878. if (prev !== null) prev.next = next;
  92879. if (next !== null) next.prev = prev;
  92880. if (this.joints == remove) this.joints = next;
  92881. remove.prev = null;
  92882. remove.next = null;
  92883. this.numJoints--;
  92884. remove.awake();
  92885. remove.detach();
  92886. remove.parent = null;
  92887. },
  92888. worldscale: function (scale) {
  92889. OIMO.WORLD_SCALE = scale || 100;
  92890. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  92891. },
  92892. addContact: function (s1, s2) {
  92893. var newContact;
  92894. if (this.unusedContacts !== null) {
  92895. newContact = this.unusedContacts;
  92896. this.unusedContacts = this.unusedContacts.next;
  92897. } else {
  92898. newContact = new OIMO.Contact();
  92899. }
  92900. newContact.attach(s1, s2);
  92901. newContact.detector = this.detectors[s1.type][s2.type];
  92902. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  92903. this.contacts = newContact;
  92904. this.numContacts++;
  92905. },
  92906. removeContact: function (contact) {
  92907. var prev = contact.prev;
  92908. var next = contact.next;
  92909. if (next) next.prev = prev;
  92910. if (prev) prev.next = next;
  92911. if (this.contacts == contact) this.contacts = next;
  92912. contact.prev = null;
  92913. contact.next = null;
  92914. contact.detach();
  92915. contact.next = this.unusedContacts;
  92916. this.unusedContacts = contact;
  92917. this.numContacts--;
  92918. },
  92919. checkContact: function (name1, name2) {
  92920. var n1, n2;
  92921. var contact = this.contacts;
  92922. while (contact !== null) {
  92923. n1 = contact.body1.name || ' ';
  92924. n2 = contact.body2.name || ' ';
  92925. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  92926. else contact = contact.next;
  92927. }
  92928. return false;
  92929. },
  92930. callSleep: function (body) {
  92931. if (!body.allowSleep) return false;
  92932. if (body.linearVelocity.lengthSq() > 0.04) return false;
  92933. if (body.angularVelocity.lengthSq() > 0.25) return false;
  92934. return true;
  92935. },
  92936. /**
  92937. * I will proceed only time step seconds time of World.
  92938. */
  92939. step: function () {
  92940. var time0, time1, time2, time3;
  92941. var stat = !this.isNoStat ? true : false;
  92942. if (stat) time0 = OIMO.now();
  92943. var body = this.rigidBodies;
  92944. while (body !== null) {
  92945. body.addedToIsland = false;
  92946. if (body.sleeping) {
  92947. if (
  92948. body.linearVelocity.testZero() ||
  92949. body.angularVelocity.testZero() ||
  92950. body.position.testDiff(body.sleepPosition) ||
  92951. body.orientation.testDiff(body.sleepOrientation)
  92952. ) body.awake(); // awake the body
  92953. }
  92954. body = body.next;
  92955. }
  92956. //------------------------------------------------------
  92957. // UPDATE CONTACT
  92958. //------------------------------------------------------
  92959. // broad phase
  92960. if (stat) time1 = OIMO.now();
  92961. this.broadPhase.detectPairs();
  92962. var pairs = this.broadPhase.pairs;
  92963. var i = this.broadPhase.numPairs;
  92964. //do{
  92965. while (i--) {
  92966. //for(var i=0, l=numPairs; i<l; i++){
  92967. var pair = pairs[i];
  92968. var s1;
  92969. var s2;
  92970. if (pair.shape1.id < pair.shape2.id) {
  92971. s1 = pair.shape1;
  92972. s2 = pair.shape2;
  92973. } else {
  92974. s1 = pair.shape2;
  92975. s2 = pair.shape1;
  92976. }
  92977. var link;
  92978. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  92979. else link = s2.contactLink;
  92980. var exists = false;
  92981. while (link) {
  92982. var contact = link.contact;
  92983. if (contact.shape1 == s1 && contact.shape2 == s2) {
  92984. contact.persisting = true;
  92985. exists = true;// contact already exists
  92986. break;
  92987. }
  92988. link = link.next;
  92989. }
  92990. if (!exists) {
  92991. this.addContact(s1, s2);
  92992. }
  92993. }// while(i-- >0);
  92994. if (stat) {
  92995. time2 = OIMO.now();
  92996. this.performance.broadPhaseTime = time2 - time1;
  92997. }
  92998. // update & narrow phase
  92999. this.numContactPoints = 0;
  93000. contact = this.contacts;
  93001. while (contact !== null) {
  93002. if (!contact.persisting) {
  93003. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93004. /*var aabb1=contact.shape1.aabb;
  93005. var aabb2=contact.shape2.aabb;
  93006. if(
  93007. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93008. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93009. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93010. ){*/
  93011. var next = contact.next;
  93012. this.removeContact(contact);
  93013. contact = next;
  93014. continue;
  93015. }
  93016. }
  93017. var b1 = contact.body1;
  93018. var b2 = contact.body2;
  93019. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93020. contact.updateManifold();
  93021. }
  93022. this.numContactPoints += contact.manifold.numPoints;
  93023. contact.persisting = false;
  93024. contact.constraint.addedToIsland = false;
  93025. contact = contact.next;
  93026. }
  93027. if (stat) {
  93028. time3 = OIMO.now();
  93029. this.performance.narrowPhaseTime = time3 - time2;
  93030. }
  93031. //------------------------------------------------------
  93032. // SOLVE ISLANDS
  93033. //------------------------------------------------------
  93034. var invTimeStep = 1 / this.timeStep;
  93035. //var body;
  93036. var joint;
  93037. var constraint;
  93038. //var num;
  93039. for (joint = this.joints; joint !== null; joint = joint.next) {
  93040. joint.addedToIsland = false;
  93041. }
  93042. // clear old island array
  93043. this.islandRigidBodies = [];
  93044. this.islandConstraints = [];
  93045. this.islandStack = [];
  93046. // expand island buffers
  93047. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93048. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93049. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93050. this.islandRigidBodies=[];
  93051. this.islandStack=[];
  93052. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93053. this.islandStack.length = this.maxIslandRigidBodies;
  93054. }
  93055. var numConstraints=this.numJoints+this.numContacts;
  93056. if(this.maxIslandConstraints<numConstraints){
  93057. this.maxIslandConstraints=numConstraints<<1;
  93058. //this.maxIslandConstraints=numConstraints*2;
  93059. this.islandConstraints=[];
  93060. this.islandConstraints.length = this.maxIslandConstraints;
  93061. }*/
  93062. time1 = OIMO.now();
  93063. this.numIslands = 0;
  93064. // build and solve simulation islands
  93065. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93066. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93067. if (base.isLonely()) {// update single body
  93068. if (base.isDynamic) {
  93069. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93070. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93071. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93072. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93073. }
  93074. if (this.callSleep(base)) {
  93075. base.sleepTime += this.timeStep;
  93076. if (base.sleepTime > 0.5) base.sleep();
  93077. else base.updatePosition(this.timeStep);
  93078. } else {
  93079. base.sleepTime = 0;
  93080. base.updatePosition(this.timeStep);
  93081. }
  93082. this.numIslands++;
  93083. continue;
  93084. }
  93085. var islandNumRigidBodies = 0;
  93086. var islandNumConstraints = 0;
  93087. var stackCount = 1;
  93088. // add rigid body to stack
  93089. this.islandStack[0] = base;
  93090. base.addedToIsland = true;
  93091. // build an island
  93092. do {
  93093. // get rigid body from stack
  93094. body = this.islandStack[--stackCount];
  93095. this.islandStack[stackCount] = null;
  93096. body.sleeping = false;
  93097. // add rigid body to the island
  93098. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93099. if (body.isStatic) continue;
  93100. // search connections
  93101. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93102. var contact = cs.contact;
  93103. constraint = contact.constraint;
  93104. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93105. // add constraint to the island
  93106. this.islandConstraints[islandNumConstraints++] = constraint;
  93107. constraint.addedToIsland = true;
  93108. var next = cs.body;
  93109. if (next.addedToIsland) continue;
  93110. // add rigid body to stack
  93111. this.islandStack[stackCount++] = next;
  93112. next.addedToIsland = true;
  93113. }
  93114. for (var js = body.jointLink; js !== null; js = js.next) {
  93115. constraint = js.joint;
  93116. if (constraint.addedToIsland) continue;// ignore
  93117. // add constraint to the island
  93118. this.islandConstraints[islandNumConstraints++] = constraint;
  93119. constraint.addedToIsland = true;
  93120. next = js.body;
  93121. if (next.addedToIsland || !next.isDynamic) continue;
  93122. // add rigid body to stack
  93123. this.islandStack[stackCount++] = next;
  93124. next.addedToIsland = true;
  93125. }
  93126. } while (stackCount != 0);
  93127. // update velocities
  93128. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93129. /*var gx=this.gravity.x*this.timeStep;
  93130. var gy=this.gravity.y*this.timeStep;
  93131. var gz=this.gravity.z*this.timeStep;*/
  93132. var j = islandNumRigidBodies;
  93133. while (j--) {
  93134. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93135. body = this.islandRigidBodies[j];
  93136. if (body.isDynamic) {
  93137. body.linearVelocity.addEqual(gVel);
  93138. /*body.linearVelocity.x+=gx;
  93139. body.linearVelocity.y+=gy;
  93140. body.linearVelocity.z+=gz;*/
  93141. }
  93142. }
  93143. // randomizing order
  93144. if (this.enableRandomizer) {
  93145. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93146. j = islandNumConstraints;
  93147. while (j--) {
  93148. if (j !== 0) {
  93149. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93150. constraint = this.islandConstraints[j];
  93151. this.islandConstraints[j] = this.islandConstraints[swap];
  93152. this.islandConstraints[swap] = constraint;
  93153. }
  93154. }
  93155. }
  93156. // solve contraints
  93157. j = islandNumConstraints;
  93158. while (j--) {
  93159. //for(j=0, l=islandNumConstraints; j<l; j++){
  93160. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93161. }
  93162. var k = this.numIterations;
  93163. while (k--) {
  93164. //for(var k=0, l=this.numIterations; k<l; k++){
  93165. j = islandNumConstraints;
  93166. while (j--) {
  93167. //for(j=0, m=islandNumConstraints; j<m; j++){
  93168. this.islandConstraints[j].solve();// main-solve
  93169. }
  93170. }
  93171. j = islandNumConstraints;
  93172. while (j--) {
  93173. //for(j=0, l=islandNumConstraints; j<l; j++){
  93174. this.islandConstraints[j].postSolve();// post-solve
  93175. this.islandConstraints[j] = null;// gc
  93176. }
  93177. // sleeping check
  93178. var sleepTime = 10;
  93179. j = islandNumRigidBodies;
  93180. while (j--) {
  93181. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93182. body = this.islandRigidBodies[j];
  93183. if (this.callSleep(body)) {
  93184. body.sleepTime += this.timeStep;
  93185. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93186. } else {
  93187. body.sleepTime = 0;
  93188. sleepTime = 0;
  93189. continue;
  93190. }
  93191. }
  93192. if (sleepTime > 0.5) {
  93193. // sleep the island
  93194. j = islandNumRigidBodies;
  93195. while (j--) {
  93196. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93197. this.islandRigidBodies[j].sleep();
  93198. this.islandRigidBodies[j] = null;// gc
  93199. }
  93200. } else {
  93201. // update positions
  93202. j = islandNumRigidBodies;
  93203. while (j--) {
  93204. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93205. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93206. this.islandRigidBodies[j] = null;// gc
  93207. }
  93208. }
  93209. this.numIslands++;
  93210. }
  93211. if (stat) {
  93212. time2 = OIMO.now();
  93213. this.performance.solvingTime = time2 - time1;
  93214. //------------------------------------------------------
  93215. // END SIMULATION
  93216. //------------------------------------------------------
  93217. time2 = OIMO.now();
  93218. // fps update
  93219. this.performance.upfps();
  93220. this.performance.totalTime = time2 - time0;
  93221. }
  93222. }
  93223. }
  93224. /**
  93225. * The class of rigid body.
  93226. * Rigid body has the shape of a single or multiple collision processing,
  93227. * I can set the parameters individually.
  93228. * @author saharan
  93229. */
  93230. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93231. this.name = " ";
  93232. // The maximum number of shapes that can be added to a one rigid.
  93233. this.MAX_SHAPES = 64;//64;
  93234. this.prev = null;
  93235. this.next = null;
  93236. // I represent the kind of rigid body.
  93237. // Please do not change from the outside this variable.
  93238. // If you want to change the type of rigid body, always
  93239. // Please specify the type you want to set the arguments of setupMass method.
  93240. this.type = OIMO.BODY_NULL;
  93241. this.massInfo = new OIMO.MassInfo();
  93242. // It is the world coordinate of the center of gravity.
  93243. this.position = new OIMO.Vec3(x, y, z);
  93244. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93245. this.newPosition = new OIMO.Vec3();
  93246. this.controlPos = false;
  93247. this.newOrientation = new OIMO.Quat();
  93248. this.newRotation = new OIMO.Vec3();
  93249. this.currentRotation = new OIMO.Vec3();
  93250. this.controlRot = false;
  93251. this.controlRotInTime = false;
  93252. // Is the translational velocity.
  93253. this.linearVelocity = new OIMO.Vec3();
  93254. // Is the angular velocity.
  93255. this.angularVelocity = new OIMO.Vec3();
  93256. // return matrix for three.js
  93257. this.matrix = new OIMO.Mat44();
  93258. //--------------------------------------------
  93259. // Please do not change from the outside this variables.
  93260. //--------------------------------------------
  93261. // It is a world that rigid body has been added.
  93262. this.parent = null;
  93263. this.contactLink = null;
  93264. this.numContacts = 0;
  93265. // An array of shapes that are included in the rigid body.
  93266. this.shapes = null;
  93267. // The number of shapes that are included in the rigid body.
  93268. this.numShapes = 0;
  93269. // It is the link array of joint that is connected to the rigid body.
  93270. this.jointLink = null;
  93271. // The number of joints that are connected to the rigid body.
  93272. this.numJoints = 0;
  93273. // It is the world coordinate of the center of gravity in the sleep just before.
  93274. this.sleepPosition = new OIMO.Vec3();
  93275. // It is a quaternion that represents the attitude of sleep just before.
  93276. this.sleepOrientation = new OIMO.Quat();
  93277. // I will show this rigid body to determine whether it is a rigid body static.
  93278. this.isStatic = false;
  93279. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93280. this.isDynamic = false;
  93281. // It is a rotation matrix representing the orientation.
  93282. this.rotation = new OIMO.Mat33();
  93283. //--------------------------------------------
  93284. // It will be recalculated automatically from the shape, which is included.
  93285. //--------------------------------------------
  93286. // This is the weight.
  93287. this.mass = NaN;
  93288. // It is the reciprocal of the mass.
  93289. this.inverseMass = NaN;
  93290. // It is the inverse of the inertia tensor in the world system.
  93291. this.inverseInertia = new OIMO.Mat33();
  93292. // It is the inertia tensor in the initial state.
  93293. this.localInertia = new OIMO.Mat33();
  93294. // It is the inverse of the inertia tensor in the initial state.
  93295. this.inverseLocalInertia = new OIMO.Mat33();
  93296. // I indicates rigid body whether it has been added to the simulation Island.
  93297. this.addedToIsland = false;
  93298. // It shows how to sleep rigid body.
  93299. this.allowSleep = true;
  93300. // This is the time from when the rigid body at rest.
  93301. this.sleepTime = 0;
  93302. // I shows rigid body to determine whether it is a sleep state.
  93303. this.sleeping = false;
  93304. };
  93305. OIMO.RigidBody.prototype = {
  93306. constructor: OIMO.RigidBody,
  93307. /**
  93308. * I'll add a shape to rigid body.
  93309. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93310. * @param shape shape to Add
  93311. */
  93312. addShape: function (shape) {
  93313. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93314. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93315. this.shapes = shape;
  93316. shape.parent = this;
  93317. if (this.parent) this.parent.addShape(shape);
  93318. this.numShapes++;
  93319. },
  93320. /**
  93321. * I will delete the shape from the rigid body.
  93322. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93323. * @param shape shape to Delete
  93324. */
  93325. removeShape: function (shape) {
  93326. var remove = shape;
  93327. if (remove.parent != this) return;
  93328. var prev = remove.prev;
  93329. var next = remove.next;
  93330. if (prev != null) prev.next = next;
  93331. if (next != null) next.prev = prev;
  93332. if (this.shapes == remove) this.shapes = next;
  93333. remove.prev = null;
  93334. remove.next = null;
  93335. remove.parent = null;
  93336. if (this.parent) this.parent.removeShape(remove);
  93337. this.numShapes--;
  93338. },
  93339. remove: function () {
  93340. this.dispose();
  93341. },
  93342. dispose: function () {
  93343. this.parent.removeRigidBody(this);
  93344. },
  93345. checkContact: function (name) {
  93346. this.parent.checkContact(this.name, name);
  93347. },
  93348. /**
  93349. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93350. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93351. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93352. * the rigid body's position will be adjusted to the center of gravity.
  93353. * @param type
  93354. * @param adjustPosition
  93355. */
  93356. setupMass: function (type, AdjustPosition) {
  93357. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93358. this.type = type || OIMO.BODY_DYNAMIC;
  93359. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93360. this.isStatic = this.type == OIMO.BODY_STATIC;
  93361. this.mass = 0;
  93362. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93363. var te = this.localInertia.elements;
  93364. //
  93365. var tmpM = new OIMO.Mat33();
  93366. var tmpV = new OIMO.Vec3();
  93367. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93368. shape.calculateMassInfo(this.massInfo);
  93369. var shapeMass = this.massInfo.mass;
  93370. var relX = shape.relativePosition.x;
  93371. var relY = shape.relativePosition.y;
  93372. var relZ = shape.relativePosition.z;
  93373. /*tmpV.x+=relX*shapeMass;
  93374. tmpV.y+=relY*shapeMass;
  93375. tmpV.z+=relZ*shapeMass;*/
  93376. tmpV.addScale(shape.relativePosition, shapeMass);
  93377. this.mass += shapeMass;
  93378. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93379. this.localInertia.addEqual(tmpM);
  93380. // add offset inertia
  93381. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93382. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93383. te[8] += shapeMass * (relX * relX + relY * relY);
  93384. var xy = shapeMass * relX * relY;
  93385. var yz = shapeMass * relY * relZ;
  93386. var zx = shapeMass * relZ * relX;
  93387. te[1] -= xy;
  93388. te[3] -= xy;
  93389. te[2] -= yz;
  93390. te[6] -= yz;
  93391. te[5] -= zx;
  93392. te[7] -= zx;
  93393. }
  93394. this.inverseMass = 1 / this.mass;
  93395. tmpV.scaleEqual(this.inverseMass);
  93396. if (adjustPosition) {
  93397. this.position.addEqual(tmpV);
  93398. for (shape = this.shapes; shape != null; shape = shape.next) {
  93399. shape.relativePosition.subEqual(tmpV);
  93400. }
  93401. // subtract offset inertia
  93402. relX = tmpV.x;
  93403. relY = tmpV.y;
  93404. relZ = tmpV.z;
  93405. //var te = this.localInertia.elements;
  93406. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93407. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93408. te[8] -= this.mass * (relX * relX + relY * relY);
  93409. xy = this.mass * relX * relY;
  93410. yz = this.mass * relY * relZ;
  93411. zx = this.mass * relZ * relX;
  93412. te[1] += xy;
  93413. te[3] += xy;
  93414. te[2] += yz;
  93415. te[6] += yz;
  93416. te[5] += zx;
  93417. te[7] += zx;
  93418. }
  93419. this.inverseLocalInertia.invert(this.localInertia);
  93420. if (this.type == OIMO.BODY_STATIC) {
  93421. this.inverseMass = 0;
  93422. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93423. }
  93424. this.syncShapes();
  93425. this.awake();
  93426. },
  93427. /**
  93428. * Awake the rigid body.
  93429. */
  93430. awake: function () {
  93431. if (!this.allowSleep || !this.sleeping) return;
  93432. this.sleeping = false;
  93433. this.sleepTime = 0;
  93434. // awake connected constraints
  93435. var cs = this.contactLink;
  93436. while (cs != null) {
  93437. cs.body.sleepTime = 0;
  93438. cs.body.sleeping = false;
  93439. cs = cs.next;
  93440. }
  93441. var js = this.jointLink;
  93442. while (js != null) {
  93443. js.body.sleepTime = 0;
  93444. js.body.sleeping = false;
  93445. js = js.next;
  93446. }
  93447. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93448. shape.updateProxy();
  93449. }
  93450. },
  93451. /**
  93452. * Sleep the rigid body.
  93453. */
  93454. sleep: function () {
  93455. if (!this.allowSleep || this.sleeping) return;
  93456. this.linearVelocity.set(0, 0, 0);
  93457. this.angularVelocity.set(0, 0, 0);
  93458. this.sleepPosition.copy(this.position);
  93459. this.sleepOrientation.copy(this.orientation);
  93460. /*this.linearVelocity.x=0;
  93461. this.linearVelocity.y=0;
  93462. this.linearVelocity.z=0;
  93463. this.angularVelocity.x=0;
  93464. this.angularVelocity.y=0;
  93465. this.angularVelocity.z=0;
  93466. this.sleepPosition.x=this.position.x;
  93467. this.sleepPosition.y=this.position.y;
  93468. this.sleepPosition.z=this.position.z;*/
  93469. /*this.sleepOrientation.s=this.orientation.s;
  93470. this.sleepOrientation.x=this.orientation.x;
  93471. this.sleepOrientation.y=this.orientation.y;
  93472. this.sleepOrientation.z=this.orientation.z;*/
  93473. this.sleepTime = 0;
  93474. this.sleeping = true;
  93475. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93476. shape.updateProxy();
  93477. }
  93478. },
  93479. /**
  93480. * Get whether the rigid body has not any connection with others.
  93481. * @return
  93482. */
  93483. isLonely: function () {
  93484. return this.numJoints == 0 && this.numContacts == 0;
  93485. },
  93486. /**
  93487. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93488. * This method is invoked automatically when calling the step of the World,
  93489. * There is no need to call from outside usually.
  93490. * @param timeStep time
  93491. */
  93492. updatePosition: function (timeStep) {
  93493. switch (this.type) {
  93494. case OIMO.BODY_STATIC:
  93495. this.linearVelocity.set(0, 0, 0);
  93496. this.angularVelocity.set(0, 0, 0);
  93497. // ONLY FOR TEST
  93498. if (this.controlPos) {
  93499. this.position.copy(this.newPosition);
  93500. this.controlPos = false;
  93501. }
  93502. if (this.controlRot) {
  93503. this.orientation.copy(this.newOrientation);
  93504. this.controlRot = false;
  93505. }
  93506. /*this.linearVelocity.x=0;
  93507. this.linearVelocity.y=0;
  93508. this.linearVelocity.z=0;
  93509. this.angularVelocity.x=0;
  93510. this.angularVelocity.y=0;
  93511. this.angularVelocity.z=0;*/
  93512. break;
  93513. case OIMO.BODY_DYNAMIC:
  93514. if (this.controlPos) {
  93515. this.angularVelocity.set(0, 0, 0);
  93516. this.linearVelocity.set(0, 0, 0);
  93517. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93518. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93519. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93520. this.controlPos = false;
  93521. }
  93522. if (this.controlRot) {
  93523. this.angularVelocity.set(0, 0, 0);
  93524. this.orientation.copy(this.newOrientation);
  93525. //var t=timeStep//*0.5;
  93526. //var q = new OIMO.Quat();
  93527. //q.sub(this.newOrientation, this.orientation);
  93528. //q.normalize(q);
  93529. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93530. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93531. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93532. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93533. //this.angularVelocity.applyQuaternion(q);
  93534. //this.angularVelocity.x = this.angularVelocity.x/t;
  93535. //this.angularVelocity.y = this.angularVelocity.y/t;
  93536. //this.angularVelocity.z = this.angularVelocity.z/t;
  93537. this.controlRot = false;
  93538. }
  93539. this.position.addTime(this.linearVelocity, timeStep);
  93540. this.orientation.addTime(this.angularVelocity, timeStep);
  93541. break;
  93542. default: OIMO.Error("RigidBody", "Invalid type.");
  93543. }
  93544. this.syncShapes();
  93545. },
  93546. rotateInertia: function (rot, inertia, out) {
  93547. var tm1 = rot.elements;
  93548. var tm2 = inertia.elements;
  93549. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93550. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93551. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93552. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93553. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93554. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93555. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93556. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93557. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93558. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93559. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93560. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93561. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93562. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93563. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93564. var oe = out.elements;
  93565. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93566. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93567. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93568. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93569. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93570. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93571. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93572. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93573. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93574. },
  93575. syncShapes: function () {
  93576. var s = this.orientation.s;
  93577. var x = this.orientation.x;
  93578. var y = this.orientation.y;
  93579. var z = this.orientation.z;
  93580. var x2 = 2 * x;
  93581. var y2 = 2 * y;
  93582. var z2 = 2 * z;
  93583. var xx = x * x2;
  93584. var yy = y * y2;
  93585. var zz = z * z2;
  93586. var xy = x * y2;
  93587. var yz = y * z2;
  93588. var xz = x * z2;
  93589. var sx = s * x2;
  93590. var sy = s * y2;
  93591. var sz = s * z2;
  93592. var tr = this.rotation.elements;
  93593. tr[0] = 1 - yy - zz;
  93594. tr[1] = xy - sz;
  93595. tr[2] = xz + sy;
  93596. tr[3] = xy + sz;
  93597. tr[4] = 1 - xx - zz;
  93598. tr[5] = yz - sx;
  93599. tr[6] = xz - sy;
  93600. tr[7] = yz + sx;
  93601. tr[8] = 1 - xx - yy;
  93602. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93603. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93604. //var relPos=shape.relativePosition;
  93605. //var relRot=shape.relativeRotation;
  93606. //var rot=shape.rotation;
  93607. /*var lx=relPos.x;
  93608. var ly=relPos.y;
  93609. var lz=relPos.z;
  93610. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93611. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93612. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93613. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93614. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93615. // add by QuaziKb
  93616. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93617. shape.updateProxy();
  93618. }
  93619. },
  93620. applyImpulse: function (position, force) {
  93621. this.linearVelocity.addScale(force, this.inverseMass);
  93622. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93623. this.linearVelocity.y+=force.y*this.inverseMass;
  93624. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93625. var rel = new OIMO.Vec3();
  93626. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93627. this.angularVelocity.addEqual(rel);
  93628. /*this.angularVelocity.x+=rel.x;
  93629. this.angularVelocity.y+=rel.y;
  93630. this.angularVelocity.z+=rel.z;*/
  93631. },
  93632. //---------------------------------------------
  93633. //
  93634. // FOR THREE JS
  93635. //
  93636. //---------------------------------------------
  93637. rotationVectToQuad: function (rot) {
  93638. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93639. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93640. },
  93641. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93642. var len = ax * ax + ay * ay + az * az;
  93643. if (len > 0) {
  93644. len = 1 / OIMO.sqrt(len);
  93645. ax *= len;
  93646. ay *= len;
  93647. az *= len;
  93648. }
  93649. var sin = OIMO.sin(rad * 0.5);
  93650. var cos = OIMO.cos(rad * 0.5);
  93651. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93652. },
  93653. //---------------------------------------------
  93654. // SET DYNAMIQUE POSITION AND ROTATION
  93655. //---------------------------------------------
  93656. setPosition: function (pos) {
  93657. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93658. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93659. this.controlPos = true;
  93660. },
  93661. setQuaternion: function (q) {
  93662. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93663. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93664. this.controlRot = true;
  93665. },
  93666. setRotation: function (rot) {
  93667. this.newOrientation = this.rotationVectToQuad(rot);
  93668. this.controlRot = true;
  93669. },
  93670. //---------------------------------------------
  93671. // RESET DYNAMIQUE POSITION AND ROTATION
  93672. //---------------------------------------------
  93673. resetPosition: function (x, y, z) {
  93674. this.linearVelocity.set(0, 0, 0);
  93675. this.angularVelocity.set(0, 0, 0);
  93676. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93677. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93678. this.awake();
  93679. },
  93680. resetQuaternion: function (q) {
  93681. this.angularVelocity.set(0, 0, 0);
  93682. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93683. this.awake();
  93684. },
  93685. resetRotation: function (x, y, z) {
  93686. this.angularVelocity.set(0, 0, 0);
  93687. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93688. this.awake();
  93689. },
  93690. //---------------------------------------------
  93691. // GET POSITION AND ROTATION
  93692. //---------------------------------------------
  93693. getPosition: function () {
  93694. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93695. },
  93696. getRotation: function () {
  93697. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93698. },
  93699. getQuaternion: function () {
  93700. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93701. },
  93702. getMatrix: function () {
  93703. var m = this.matrix.elements;
  93704. var r, p;
  93705. if (!this.sleeping) {
  93706. // rotation matrix
  93707. r = this.rotation.elements;
  93708. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93709. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93710. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93711. // position matrix
  93712. p = this.position;
  93713. m[12] = p.x * OIMO.WORLD_SCALE;
  93714. m[13] = p.y * OIMO.WORLD_SCALE;
  93715. m[14] = p.z * OIMO.WORLD_SCALE;
  93716. // sleep or not ?
  93717. m[15] = 0;
  93718. } else {
  93719. m[15] = 1;
  93720. }
  93721. return m;
  93722. }
  93723. };
  93724. /**
  93725. * The main class of body.
  93726. * is for simplify creation process and data access of rigidRody
  93727. * Rigid body has the shape of a single or multiple collision processing,
  93728. * all setting in object
  93729. *
  93730. * @author loth
  93731. */
  93732. OIMO.Body = function (Obj) {
  93733. var obj = Obj || {};
  93734. if (!obj.world) return;
  93735. if (obj.type === undefined) obj.type = "box";
  93736. this.name = obj.name || '';
  93737. // obsolete use world.add(obj)
  93738. this.body = obj.world.add(obj);
  93739. /*
  93740. // the world where i am
  93741. this.parent = obj.world;
  93742. // Yep my name
  93743. this.name = obj.name || '';
  93744. // I'm dynamique or not
  93745. var move = obj.move || false;
  93746. // I can sleep or not
  93747. var noSleep = obj.noSleep || false;
  93748. // My start position
  93749. var p = obj.pos || [0,0,0];
  93750. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93751. // My size
  93752. var s = obj.size || [1,1,1];
  93753. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93754. // My rotation in degre
  93755. var rot = obj.rot || [0,0,0];
  93756. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93757. var r = [];
  93758. for (var i=0; i<rot.length/3; i++){
  93759. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93760. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93761. }
  93762. // My physics setting
  93763. var sc = obj.sc || new OIMO.ShapeConfig();
  93764. if(obj.config){
  93765. // The density of the shape.
  93766. sc.density = obj.config[0] || 1;
  93767. // The coefficient of friction of the shape.
  93768. sc.friction = obj.config[1] || 0.4;
  93769. // The coefficient of restitution of the shape.
  93770. sc.restitution = obj.config[2] || 0.2;
  93771. // The bits of the collision groups to which the shape belongs.
  93772. sc.belongsTo = obj.config[3] || 1;
  93773. // The bits of the collision groups with which the shape collides.
  93774. sc.collidesWith = obj.config[4] || 0xffffffff;
  93775. }
  93776. if(obj.massPos){
  93777. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93778. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93779. }
  93780. if(obj.massRot){
  93781. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93782. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93783. }
  93784. // My rigidbody
  93785. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93786. // My shapes
  93787. var shapes = [];
  93788. var type = obj.type || "box";
  93789. if( typeof type === 'string' ) type = [type];// single shape
  93790. var n, n2;
  93791. for(var i=0; i<type.length; i++){
  93792. n = i*3;
  93793. n2 = i*4;
  93794. switch(type[i]){
  93795. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93796. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93797. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93798. }
  93799. this.body.addShape(shapes[i]);
  93800. if(i>0){
  93801. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93802. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93803. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93804. }
  93805. }
  93806. // I'm static or i move
  93807. if(move){
  93808. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93809. else this.body.setupMass(0x1, true);
  93810. if(noSleep) this.body.allowSleep = false;
  93811. else this.body.allowSleep = true;
  93812. } else {
  93813. this.body.setupMass(0x2);
  93814. }
  93815. this.body.name = this.name;
  93816. this.sleeping = this.body.sleeping;
  93817. // finaly add to physics world
  93818. this.parent.addRigidBody(this.body);*/
  93819. }
  93820. OIMO.Body.prototype = {
  93821. constructor: OIMO.Body,
  93822. // SET
  93823. setPosition: function (pos) {
  93824. this.body.setPosition(pos);
  93825. },
  93826. setQuaternion: function (q) {
  93827. this.body.setQuaternion(q);
  93828. },
  93829. setRotation: function (rot) {
  93830. this.body.setRotation(rot);
  93831. },
  93832. // GET
  93833. getPosition: function () {
  93834. return this.body.getPosition();
  93835. },
  93836. getRotation: function () {
  93837. return this.body.getRotation();
  93838. },
  93839. getQuaternion: function () {
  93840. return this.body.getQuaternion();
  93841. },
  93842. getMatrix: function () {
  93843. return this.body.getMatrix();
  93844. },
  93845. getSleep: function () {
  93846. return this.body.sleeping;
  93847. },
  93848. // RESET
  93849. resetPosition: function (x, y, z) {
  93850. this.body.resetPosition(x, y, z);
  93851. },
  93852. resetRotation: function (x, y, z) {
  93853. this.body.resetRotation(x, y, z);
  93854. },
  93855. // force wakeup
  93856. awake: function () {
  93857. this.body.awake();
  93858. },
  93859. // remove rigidbody
  93860. remove: function () {
  93861. this.body.dispose();
  93862. //this.parent.removeRigidBody(this.body);
  93863. },
  93864. // test if this object hit another
  93865. checkContact: function (name) {
  93866. this.body.checkContact(name);
  93867. //this.parent.checkContact(this.name, name);
  93868. }
  93869. }
  93870. /**
  93871. * The main class of link.
  93872. * is for simplify creation process and data access of Joint
  93873. * all setting in object
  93874. *
  93875. * @author loth
  93876. */
  93877. OIMO.Link = function (Obj) {
  93878. var obj = Obj || {};
  93879. if (!obj.world) return;
  93880. if (obj.type === undefined) obj.type = "jointHinge";
  93881. this.name = obj.name || '';
  93882. // obsolete use world.add(obj)
  93883. this.joint = obj.world.add(obj);
  93884. // the world where i am
  93885. /*this.parent = obj.world;
  93886. this.name = obj.name || '';
  93887. var type = obj.type || "jointHinge";
  93888. var axe1 = obj.axe1 || [1,0,0];
  93889. var axe2 = obj.axe2 || [1,0,0];
  93890. var pos1 = obj.pos1 || [0,0,0];
  93891. var pos2 = obj.pos2 || [0,0,0];
  93892. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  93893. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  93894. var min, max;
  93895. if(type==="jointDistance"){
  93896. min = obj.min || 0;
  93897. max = obj.max || 10;
  93898. min = min*OIMO.INV_SCALE;
  93899. max = max*OIMO.INV_SCALE;
  93900. }else{
  93901. min = obj.min || 57.29578;
  93902. max = obj.max || 0;
  93903. min = min*OIMO.TO_RAD;
  93904. max = max*OIMO.TO_RAD;
  93905. }
  93906. var limit = obj.limit || null;
  93907. var spring = obj.spring || null;
  93908. var motor = obj.motor || null;
  93909. // joint setting
  93910. var jc = new OIMO.JointConfig();
  93911. jc.allowCollision = obj.collision || false;;
  93912. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  93913. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  93914. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  93915. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  93916. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  93917. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  93918. jc.body1 = obj.body1;
  93919. jc.body2 = obj.body2;
  93920. switch(type){
  93921. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  93922. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  93923. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93924. break;
  93925. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  93926. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  93927. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93928. break;
  93929. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  93930. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  93931. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  93932. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  93933. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  93934. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  93935. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  93936. break;
  93937. }
  93938. this.joint.name = this.name;
  93939. // finaly add to physics world
  93940. this.parent.addJoint(this.joint);*/
  93941. }
  93942. OIMO.Link.prototype = {
  93943. constructor: OIMO.Link,
  93944. getPosition: function () {
  93945. // array of two vect3 [point1, point2]
  93946. return this.joint.getPosition();
  93947. },
  93948. getMatrix: function () {
  93949. return this.joint.getMatrix();
  93950. },
  93951. // remove joint
  93952. remove: function () {
  93953. this.joint.dispose();
  93954. //this.parent.removeJoint(this.joint);
  93955. },
  93956. // force wakeup linked body
  93957. awake: function () {
  93958. this.joint.awake();
  93959. }
  93960. }
  93961. /**
  93962. * The Dictionary class for testing
  93963. * @author lo-th
  93964. */
  93965. OIMO.Dictionary = function () {
  93966. this.data = {};
  93967. this.keys = [];
  93968. };
  93969. OIMO.Dictionary.prototype = {
  93970. constructor: OIMO.Dictionary,
  93971. set: function (value) {
  93972. var key = value.id;
  93973. if (!this.get[key]) this.keys.push(key);
  93974. this.data[key] = value;
  93975. },
  93976. get: function (id) {
  93977. return this.data[id];
  93978. },
  93979. del: function (value) {
  93980. var k = this.keys;
  93981. var n = k.indexOf(value.id);
  93982. if (n > -1) {
  93983. delete this.data[k[n]];
  93984. k.splice(n, 1);
  93985. }
  93986. },
  93987. reset: function () {
  93988. var data = this.data, keys = this.keys, key;
  93989. while (keys.length > 0) {
  93990. key = keys.pop();
  93991. delete data[key];
  93992. }
  93993. }
  93994. };
  93995. OIMO.Performance = function (world) {
  93996. this.parent = world;
  93997. this.infos = new OIMO_ARRAY_TYPE(13);
  93998. this.f = [0, 0, 0];
  93999. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94000. this.broadPhase = this.types[this.parent.broadPhase.types];
  94001. this.version = OIMO.REVISION;
  94002. this.fps = 0;
  94003. this.broadPhaseTime = 0;
  94004. this.narrowPhaseTime = 0;
  94005. this.solvingTime = 0;
  94006. //this.updatingTime = 0;
  94007. this.totalTime = 0;
  94008. };
  94009. OIMO.Performance.prototype = {
  94010. upfps: function () {
  94011. this.f[1] = Date.now();
  94012. 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]++;
  94013. },
  94014. updatingTime: function () {
  94015. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94016. },
  94017. show: function () {
  94018. var info = [
  94019. "Oimo.js " + this.version + "<br>",
  94020. this.broadPhase + "<br><br>",
  94021. "FPS: " + this.fps + " fps<br><br>",
  94022. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94023. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94024. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94025. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94026. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94027. "Time in milliseconde<br><br>",
  94028. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94029. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94030. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94031. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94032. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94033. ].join("\n");
  94034. return info;
  94035. },
  94036. toArray: function () {
  94037. this.infos[0] = this.parent.broadPhase.types;
  94038. this.infos[1] = this.parent.numRigidBodies;
  94039. this.infos[2] = this.parent.numContacts;
  94040. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94041. this.infos[4] = this.parent.numContactPoints;
  94042. this.infos[5] = this.parent.numIslands;
  94043. this.infos[6] = this.broadPhaseTime;
  94044. this.infos[7] = this.narrowPhaseTime;
  94045. this.infos[8] = this.solvingTime;
  94046. this.infos[9] = this.updatingTime();
  94047. this.infos[10] = this.totalTime;
  94048. this.infos[11] = this.fps;
  94049. return this.infos;
  94050. }
  94051. };
  94052. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94053. this.elements = new OIMO_ARRAY_TYPE(16);
  94054. var te = this.elements;
  94055. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94056. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94057. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94058. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94059. };
  94060. OIMO.Mat44.prototype = {
  94061. constructor: OIMO.Mat44,
  94062. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94063. var te = this.elements;
  94064. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94065. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94066. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94067. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94068. return this;
  94069. }/*,
  94070. extractRotation: function () {
  94071. var v1 = new THREE.Vector3();
  94072. return function ( m ) {
  94073. var te = this.elements;
  94074. var me = m.elements;
  94075. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94076. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94077. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94078. te[ 0 ] = me[ 0 ] * scaleX;
  94079. te[ 1 ] = me[ 1 ] * scaleX;
  94080. te[ 2 ] = me[ 2 ] * scaleX;
  94081. te[ 4 ] = me[ 4 ] * scaleY;
  94082. te[ 5 ] = me[ 5 ] * scaleY;
  94083. te[ 6 ] = me[ 6 ] * scaleY;
  94084. te[ 8 ] = me[ 8 ] * scaleZ;
  94085. te[ 9 ] = me[ 9 ] * scaleZ;
  94086. te[ 10 ] = me[ 10 ] * scaleZ;
  94087. return this;
  94088. };
  94089. }() */
  94090. }
  94091. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94092. this.elements = new OIMO_ARRAY_TYPE(9);
  94093. var te = this.elements;
  94094. this.init(
  94095. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94096. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94097. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94098. );
  94099. };
  94100. OIMO.Mat33.prototype = {
  94101. constructor: OIMO.Mat33,
  94102. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94103. var te = this.elements;
  94104. te[0] = e00; te[1] = e01; te[2] = e02;
  94105. te[3] = e10; te[4] = e11; te[5] = e12;
  94106. te[6] = e20; te[7] = e21; te[8] = e22;
  94107. return this;
  94108. },
  94109. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94110. var te = this.elements;
  94111. te[0] = e00; te[1] = e01; te[2] = e02;
  94112. te[3] = e10; te[4] = e11; te[5] = e12;
  94113. te[6] = e20; te[7] = e21; te[8] = e22;
  94114. return this;
  94115. },
  94116. multiply: function (s) {
  94117. var te = this.elements;
  94118. te[0] *= s; te[1] *= s; te[2] *= s;
  94119. te[3] *= s; te[4] *= s; te[5] *= s;
  94120. te[6] *= s; te[7] *= s; te[8] *= s;
  94121. return this;
  94122. },
  94123. add: function (m1, m2) {
  94124. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94125. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94126. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94127. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94128. return this;
  94129. },
  94130. addEqual: function (m) {
  94131. var te = this.elements, tem = m.elements;
  94132. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94133. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94134. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94135. return this;
  94136. },
  94137. sub: function (m1, m2) {
  94138. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94139. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94140. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94141. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94142. return this;
  94143. },
  94144. subEqual: 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. scale: function (m, s) {
  94152. var te = this.elements, tm = m.elements;
  94153. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94154. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94155. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94156. return this;
  94157. },
  94158. scaleEqual: function (s) {
  94159. var te = this.elements;
  94160. te[0] *= s; te[1] *= s; te[2] *= s;
  94161. te[3] *= s; te[4] *= s; te[5] *= s;
  94162. te[6] *= s; te[7] *= s; te[8] *= s;
  94163. return this;
  94164. },
  94165. mul: function (m1, m2) {
  94166. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94167. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94168. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94169. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94170. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94171. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94172. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94173. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94174. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94175. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94176. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94177. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94178. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94179. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94180. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94181. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94182. return this;
  94183. },
  94184. mulScale: function (m, sx, sy, sz, Prepend) {
  94185. var prepend = Prepend || false;
  94186. var te = this.elements, tm = m.elements;
  94187. if (prepend) {
  94188. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94189. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94190. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94191. } else {
  94192. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94193. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94194. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94195. }
  94196. return this;
  94197. },
  94198. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94199. var prepend = Prepend || false;
  94200. var s = OIMO.sin(rad);
  94201. var c = OIMO.cos(rad);
  94202. var c1 = 1 - c;
  94203. var r00 = ax * ax * c1 + c;
  94204. var r01 = ax * ay * c1 - az * s;
  94205. var r02 = ax * az * c1 + ay * s;
  94206. var r10 = ay * ax * c1 + az * s;
  94207. var r11 = ay * ay * c1 + c;
  94208. var r12 = ay * az * c1 - ax * s;
  94209. var r20 = az * ax * c1 - ay * s;
  94210. var r21 = az * ay * c1 + ax * s;
  94211. var r22 = az * az * c1 + c;
  94212. var tm = m.elements;
  94213. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94214. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94215. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94216. var te = this.elements;
  94217. if (prepend) {
  94218. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94219. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94220. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94221. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94222. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94223. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94224. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94225. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94226. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94227. } else {
  94228. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94229. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94230. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94231. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94232. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94233. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94234. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94235. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94236. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94237. }
  94238. return this;
  94239. },
  94240. transpose: function (m) {
  94241. var te = this.elements, tm = m.elements;
  94242. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94243. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94244. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94245. return this;
  94246. },
  94247. setQuat: function (q) {
  94248. var te = this.elements,
  94249. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94250. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94251. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94252. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94253. te[0] = 1 - yy - zz;
  94254. te[1] = xy - sz;
  94255. te[2] = xz + sy;
  94256. te[3] = xy + sz;
  94257. te[4] = 1 - xx - zz;
  94258. te[5] = yz - sx;
  94259. te[6] = xz - sy;
  94260. te[7] = yz + sx;
  94261. te[8] = 1 - xx - yy;
  94262. return this;
  94263. },
  94264. invert: function (m) {
  94265. var te = this.elements, tm = m.elements,
  94266. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94267. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94268. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94269. b01 = a4 * a8 - a7 * a5,
  94270. b11 = a7 * a2 - a1 * a8,
  94271. b21 = a1 * a5 - a4 * a2,
  94272. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94273. if (dt != 0) { dt = 1.0 / dt; }
  94274. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94275. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94276. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94277. te[3] = dt * (a5 * a6 - a3 * a8);
  94278. te[4] = dt * (a0 * a8 - a2 * a6);
  94279. te[5] = dt * (a2 * a3 - a0 * a5);
  94280. te[6] = dt * (a3 * a7 - a4 * a6);
  94281. te[7] = dt * (a1 * a6 - a0 * a7);
  94282. te[8] = dt * (a0 * a4 - a1 * a3);
  94283. return this;
  94284. },
  94285. /*copy: function(m){
  94286. var te = this.elements, tem = m.elements;
  94287. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94288. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94289. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94290. return this;
  94291. },*/
  94292. toEuler: function () { // not work !!
  94293. function clamp(x) {
  94294. return OIMO.min(OIMO.max(x, -1), 1);
  94295. }
  94296. var te = this.elements;
  94297. var m11 = te[0], m12 = te[3], m13 = te[6];
  94298. var m21 = te[1], m22 = te[4], m23 = te[7];
  94299. var m31 = te[2], m32 = te[5], m33 = te[8];
  94300. var p = new OIMO.Vec3();
  94301. var d = new OIMO.Quat();
  94302. var s;
  94303. p.y = OIMO.asin(clamp(m13));
  94304. if (OIMO.abs(m13) < 0.99999) {
  94305. p.x = OIMO.atan2(-m23, m33);
  94306. p.z = OIMO.atan2(-m12, m11);
  94307. } else {
  94308. p.x = OIMO.atan2(m32, m22);
  94309. p.z = 0;
  94310. }
  94311. return p;
  94312. },
  94313. /*clone: function(){
  94314. var te = this.elements;
  94315. return new OIMO.Mat33(
  94316. te[0], te[1], te[2],
  94317. te[3], te[4], te[5],
  94318. te[6], te[7], te[8]
  94319. );
  94320. },*/
  94321. toString: function () {
  94322. var te = this.elements;
  94323. var text =
  94324. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94325. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94326. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94327. return text;
  94328. },
  94329. // OK
  94330. multiplyScalar: function (s) {
  94331. var te = this.elements;
  94332. te[0] *= s; te[3] *= s; te[6] *= s;
  94333. te[1] *= s; te[4] *= s; te[7] *= s;
  94334. te[2] *= s; te[5] *= s; te[8] *= s;
  94335. return this;
  94336. },
  94337. identity: function () {
  94338. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94339. return this;
  94340. },
  94341. clone: function () {
  94342. return new this.constructor().fromArray(this.elements);
  94343. },
  94344. copy: function (m) {
  94345. var me = m.elements;
  94346. this.set(
  94347. me[0], me[3], me[6],
  94348. me[1], me[4], me[7],
  94349. me[2], me[5], me[8]
  94350. );
  94351. return this;
  94352. },
  94353. fromArray: function (array) {
  94354. this.elements.set(array);
  94355. return this;
  94356. },
  94357. toArray: function () {
  94358. var te = this.elements;
  94359. return [
  94360. te[0], te[1], te[2],
  94361. te[3], te[4], te[5],
  94362. te[6], te[7], te[8]
  94363. ];
  94364. }
  94365. };
  94366. OIMO.Quat = function (s, x, y, z) {
  94367. this.s = (s !== undefined) ? s : 1;
  94368. this.x = x || 0;
  94369. this.y = y || 0;
  94370. this.z = z || 0;
  94371. };
  94372. OIMO.Quat.prototype = {
  94373. constructor: OIMO.Quat,
  94374. set: function (x, y, z, w) {
  94375. this.x = x;
  94376. this.y = y;
  94377. this.z = z;
  94378. this.s = w;
  94379. return this;
  94380. },
  94381. init: function (s, x, y, z) {
  94382. this.s = (s !== undefined) ? s : 1;
  94383. this.x = x || 0;
  94384. this.y = y || 0;
  94385. this.z = z || 0;
  94386. return this;
  94387. },
  94388. add: function (q1, q2) {
  94389. this.s = q1.s + q2.s;
  94390. this.x = q1.x + q2.x;
  94391. this.y = q1.y + q2.y;
  94392. this.z = q1.z + q2.z;
  94393. return this;
  94394. },
  94395. addTime: function (v, t) {
  94396. var x = v.x;
  94397. var y = v.y;
  94398. var z = v.z;
  94399. var qs = this.s;
  94400. var qx = this.x;
  94401. var qy = this.y;
  94402. var qz = this.z;
  94403. t *= 0.5;
  94404. var ns = (-x * qx - y * qy - z * qz) * t;
  94405. var nx = (x * qs + y * qz - z * qy) * t;
  94406. var ny = (-x * qz + y * qs + z * qx) * t;
  94407. var nz = (x * qy - y * qx + z * qs) * t;
  94408. qs += ns;
  94409. qx += nx;
  94410. qy += ny;
  94411. qz += nz;
  94412. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94413. this.s = qs * s;
  94414. this.x = qx * s;
  94415. this.y = qy * s;
  94416. this.z = qz * s;
  94417. return this;
  94418. },
  94419. sub: function (q1, q2) {
  94420. this.s = q1.s - q2.s;
  94421. this.x = q1.x - q2.x;
  94422. this.y = q1.y - q2.y;
  94423. this.z = q1.z - q2.z;
  94424. return this;
  94425. },
  94426. scale: function (q, s) {
  94427. this.s = q.s * s;
  94428. this.x = q.x * s;
  94429. this.y = q.y * s;
  94430. this.z = q.z * s;
  94431. return this;
  94432. },
  94433. mul: function (q1, q2) {
  94434. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94435. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94436. this.x = ax * bs + as * bx + ay * bz - az * by;
  94437. this.y = ay * bs + as * by + az * bx - ax * bz;
  94438. this.z = az * bs + as * bz + ax * by - ay * bx;
  94439. this.s = as * bs - ax * bx - ay * by - az * bz;
  94440. return this;
  94441. },
  94442. arc: function (v1, v2) {
  94443. var x1 = v1.x;
  94444. var y1 = v1.y;
  94445. var z1 = v1.z;
  94446. var x2 = v2.x;
  94447. var y2 = v2.y;
  94448. var z2 = v2.z;
  94449. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94450. if (d == -1) {
  94451. x2 = y1 * x1 - z1 * z1;
  94452. y2 = -z1 * y1 - x1 * x1;
  94453. z2 = x1 * z1 + y1 * y1;
  94454. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94455. this.s = 0;
  94456. this.x = x2 * d;
  94457. this.y = y2 * d;
  94458. this.z = z2 * d;
  94459. return this;
  94460. }
  94461. var cx = y1 * z2 - z1 * y2;
  94462. var cy = z1 * x2 - x1 * z2;
  94463. var cz = x1 * y2 - y1 * x2;
  94464. this.s = OIMO.sqrt((1 + d) * 0.5);
  94465. d = 0.5 / this.s;
  94466. this.x = cx * d;
  94467. this.y = cy * d;
  94468. this.z = cz * d;
  94469. return this;
  94470. },
  94471. normalize: function (q) {
  94472. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94473. if (len > 0) { len = 1 / len; }
  94474. this.s = q.s * len;
  94475. this.x = q.x * len;
  94476. this.y = q.y * len;
  94477. this.z = q.z * len;
  94478. return this;
  94479. },
  94480. invert: function (q) {
  94481. this.s = q.s;
  94482. this.x = -q.x;
  94483. this.y = -q.y;
  94484. this.z = -q.z;
  94485. return this;
  94486. },
  94487. length: function () {
  94488. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94489. },
  94490. copy: function (q) {
  94491. this.s = q.s;
  94492. this.x = q.x;
  94493. this.y = q.y;
  94494. this.z = q.z;
  94495. return this;
  94496. },
  94497. testDiff: function (q) {
  94498. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94499. else return false;
  94500. },
  94501. clone: function (q) {
  94502. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94503. },
  94504. toString: function () {
  94505. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94506. }
  94507. }
  94508. // for three easy export
  94509. OIMO.Quaternion = function (x, y, z, w) {
  94510. this.x = x || 0;
  94511. this.y = y || 0;
  94512. this.z = z || 0;
  94513. this.w = (w !== undefined) ? w : 1;
  94514. };
  94515. OIMO.Quaternion.prototype = {
  94516. constructor: OIMO.Quaternion,
  94517. setFromRotationMatrix: function (m) {
  94518. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94519. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94520. var te = m.elements,
  94521. m11 = te[0], m12 = te[1], m13 = te[2],
  94522. m21 = te[3], m22 = te[4], m23 = te[5],
  94523. m31 = te[6], m32 = te[7], m33 = te[8],
  94524. trace = m11 + m22 + m33,
  94525. s;
  94526. if (trace > 0) {
  94527. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94528. this.w = 0.25 / s;
  94529. this.x = (m32 - m23) * s;
  94530. this.y = (m13 - m31) * s;
  94531. this.z = (m21 - m12) * s;
  94532. } else if (m11 > m22 && m11 > m33) {
  94533. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94534. this.w = (m32 - m23) / s;
  94535. this.x = 0.25 * s;
  94536. this.y = (m12 + m21) / s;
  94537. this.z = (m13 + m31) / s;
  94538. } else if (m22 > m33) {
  94539. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94540. this.w = (m13 - m31) / s;
  94541. this.x = (m12 + m21) / s;
  94542. this.y = 0.25 * s;
  94543. this.z = (m23 + m32) / s;
  94544. } else {
  94545. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94546. this.w = (m21 - m12) / s;
  94547. this.x = (m13 + m31) / s;
  94548. this.y = (m23 + m32) / s;
  94549. this.z = 0.25 * s;
  94550. }
  94551. //this.onChangeCallback();
  94552. return this;
  94553. }
  94554. }
  94555. OIMO.Vec3 = function (x, y, z) {
  94556. this.x = x || 0;
  94557. this.y = y || 0;
  94558. this.z = z || 0;
  94559. };
  94560. OIMO.Vec3.prototype = {
  94561. constructor: OIMO.Vec3,
  94562. init: function (x, y, z) {
  94563. this.x = x || 0;
  94564. this.y = y || 0;
  94565. this.z = z || 0;
  94566. return this;
  94567. },
  94568. set: function (x, y, z) {
  94569. this.x = x;
  94570. this.y = y;
  94571. this.z = z;
  94572. return this;
  94573. },
  94574. add: function (v1, v2) {
  94575. this.x = v1.x + v2.x;
  94576. this.y = v1.y + v2.y;
  94577. this.z = v1.z + v2.z;
  94578. return this;
  94579. },
  94580. addEqual: function (v) {
  94581. this.x += v.x;
  94582. this.y += v.y;
  94583. this.z += v.z;
  94584. return this;
  94585. },
  94586. addTime: function (v, t) {
  94587. this.x += v.x * t;
  94588. this.y += v.y * t;
  94589. this.z += v.z * t;
  94590. return this;
  94591. },
  94592. sub: function (v1, v2) {
  94593. this.x = v1.x - v2.x;
  94594. this.y = v1.y - v2.y;
  94595. this.z = v1.z - v2.z;
  94596. return this;
  94597. },
  94598. subEqual: function (v) {
  94599. this.x -= v.x;
  94600. this.y -= v.y;
  94601. this.z -= v.z;
  94602. return this;
  94603. },
  94604. addScale: function (v, s) {
  94605. this.x += v.x * s;
  94606. this.y += v.y * s;
  94607. this.z += v.z * s;
  94608. return this;
  94609. },
  94610. scale: function (v, s) {
  94611. this.x = v.x * s;
  94612. this.y = v.y * s;
  94613. this.z = v.z * s;
  94614. return this;
  94615. },
  94616. scaleEqual: function (s) {
  94617. this.x *= s;
  94618. this.y *= s;
  94619. this.z *= s;
  94620. return this;
  94621. },
  94622. /*dot: function(v){
  94623. return this.x*v.x+this.y*v.y+this.z*v.z;
  94624. },*/
  94625. cross: function (v1, v2) {
  94626. var ax = v1.x, ay = v1.y, az = v1.z,
  94627. bx = v2.x, by = v2.y, bz = v2.z;
  94628. this.x = ay * bz - az * by;
  94629. this.y = az * bx - ax * bz;
  94630. this.z = ax * by - ay * bx;
  94631. return this;
  94632. },
  94633. mul: function (o, v, m) {
  94634. var te = m.elements;
  94635. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94636. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94637. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94638. return this;
  94639. },
  94640. mulMat: function (m, v) {
  94641. var te = m.elements;
  94642. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94643. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94644. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94645. return this;
  94646. },
  94647. normalize: function (v) {
  94648. var x = v.x, y = v.y, z = v.z;
  94649. var l = x * x + y * y + z * z;
  94650. if (l > 0) {
  94651. l = 1 / OIMO.sqrt(l);
  94652. this.x = x * l;
  94653. this.y = y * l;
  94654. this.z = z * l;
  94655. }
  94656. return this;
  94657. },
  94658. /*norm: function(){
  94659. var x = this.x, y = this.y, z = this.z;
  94660. var l = x*x + y*y + z*z;
  94661. if (l > 0) {
  94662. l = 1 / OIMO.sqrt(l);
  94663. this.x = x*l;
  94664. this.y = y*l;
  94665. this.z = z*l;
  94666. }
  94667. return this;
  94668. },*/
  94669. invert: function (v) {
  94670. this.x = -v.x;
  94671. this.y = -v.y;
  94672. this.z = -v.z;
  94673. return this;
  94674. },
  94675. /*length: function(){
  94676. var x = this.x, y = this.y, z = this.z;
  94677. return OIMO.sqrt(x*x + y*y + z*z);
  94678. },*/
  94679. negate: function () {
  94680. this.x = -this.x;
  94681. this.y = -this.y;
  94682. this.z = -this.z;
  94683. return this;
  94684. },
  94685. dot: function (v) {
  94686. return this.x * v.x + this.y * v.y + this.z * v.z;
  94687. },
  94688. lengthSq: function () {
  94689. return this.x * this.x + this.y * this.y + this.z * this.z;
  94690. },
  94691. length: function () {
  94692. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94693. },
  94694. /*len: function(){
  94695. var x = this.x, y = this.y, z = this.z;
  94696. return x*x + y*y + z*z;
  94697. },*/
  94698. copy: function (v) {
  94699. this.x = v.x;
  94700. this.y = v.y;
  94701. this.z = v.z;
  94702. return this;
  94703. },
  94704. applyQuaternion: function (q) {
  94705. var x = this.x;
  94706. var y = this.y;
  94707. var z = this.z;
  94708. var qx = q.x;
  94709. var qy = q.y;
  94710. var qz = q.z;
  94711. var qs = q.s;
  94712. // calculate quat * vector
  94713. var ix = qs * x + qy * z - qz * y;
  94714. var iy = qs * y + qz * x - qx * z;
  94715. var iz = qs * z + qx * y - qy * x;
  94716. var iw = -qx * x - qy * y - qz * z;
  94717. // calculate result * inverse quat
  94718. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94719. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94720. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94721. return this;
  94722. },
  94723. testZero: function () {
  94724. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94725. else return false;
  94726. },
  94727. testDiff: function (v) {
  94728. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94729. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94730. //else return false;
  94731. },
  94732. equals: function (v) {
  94733. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94734. },
  94735. clone: function () {
  94736. return new this.constructor(this.x, this.y, this.z);
  94737. },
  94738. toString: function () {
  94739. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94740. },
  94741. multiplyScalar: function (scalar) {
  94742. if (isFinite(scalar)) {
  94743. this.x *= scalar;
  94744. this.y *= scalar;
  94745. this.z *= scalar;
  94746. } else {
  94747. this.x = 0;
  94748. this.y = 0;
  94749. this.z = 0;
  94750. }
  94751. return this;
  94752. },
  94753. divideScalar: function (scalar) {
  94754. return this.multiplyScalar(1 / scalar);
  94755. },
  94756. // TODO rename to normalize
  94757. norm: function () {
  94758. return this.divideScalar(this.length());
  94759. },
  94760. }
  94761. OIMO.Euler = function (x, y, z, order) {
  94762. this._x = x || 0;
  94763. this._y = y || 0;
  94764. this._z = z || 0;
  94765. this._order = order || OIMO.Euler.DefaultOrder;
  94766. };
  94767. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94768. OIMO.Euler.DefaultOrder = 'XYZ';
  94769. OIMO.clamp = function (x, a, b) {
  94770. return (x < a) ? a : ((x > b) ? b : x);
  94771. }
  94772. OIMO.Euler.prototype = {
  94773. constructor: OIMO.Euler,
  94774. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94775. get x() {
  94776. return this._x;
  94777. },
  94778. set x(value) {
  94779. this._x = value;
  94780. this.onChangeCallback();
  94781. },
  94782. get y() {
  94783. return this._y;
  94784. },
  94785. set y(value) {
  94786. this._y = value;
  94787. this.onChangeCallback();
  94788. },
  94789. get z() {
  94790. return this._z;
  94791. },
  94792. set z(value) {
  94793. this._z = value;
  94794. this.onChangeCallback();
  94795. },
  94796. get order() {
  94797. return this._order;
  94798. },
  94799. set order(value) {
  94800. this._order = value;
  94801. this.onChangeCallback();
  94802. },
  94803. set: function (x, y, z, order) {
  94804. this._x = x;
  94805. this._y = y;
  94806. this._z = z;
  94807. this._order = order || this._order;
  94808. this.onChangeCallback();
  94809. return this;
  94810. },
  94811. copy: function (euler) {
  94812. this._x = euler._x;
  94813. this._y = euler._y;
  94814. this._z = euler._z;
  94815. this._order = euler._order;
  94816. this.onChangeCallback();
  94817. return this;
  94818. },
  94819. setFromRotationMatrix: function (m, order) {
  94820. var clamp = OIMO.clamp;
  94821. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94822. var te = m.elements;
  94823. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94824. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94825. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94826. var m11 = te[0], m12 = te[1], m13 = te[2],
  94827. m21 = te[3], m22 = te[4], m23 = te[5],
  94828. m31 = te[6], m32 = te[7], m33 = te[8];
  94829. order = order || this._order;
  94830. if (order === 'XYZ') {
  94831. this._y = OIMO.asin(clamp(m13, -1, 1));
  94832. if (OIMO.abs(m13) < 0.99999) {
  94833. this._x = OIMO.atan2(-m23, m33);
  94834. this._z = OIMO.atan2(-m12, m11);
  94835. } else {
  94836. this._x = OIMO.atan2(m32, m22);
  94837. this._z = 0;
  94838. }
  94839. } else if (order === 'YXZ') {
  94840. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94841. if (OIMO.abs(m23) < 0.99999) {
  94842. this._y = OIMO.atan2(m13, m33);
  94843. this._z = OIMO.atan2(m21, m22);
  94844. } else {
  94845. this._y = OIMO.atan2(-m31, m11);
  94846. this._z = 0;
  94847. }
  94848. } else if (order === 'ZXY') {
  94849. this._x = OIMO.asin(clamp(m32, -1, 1));
  94850. if (OIMO.abs(m32) < 0.99999) {
  94851. this._y = OIMO.atan2(-m31, m33);
  94852. this._z = OIMO.atan2(-m12, m22);
  94853. } else {
  94854. this._y = 0;
  94855. this._z = OIMO.atan2(m21, m11);
  94856. }
  94857. } else if (order === 'ZYX') {
  94858. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94859. if (OIMO.abs(m31) < 0.99999) {
  94860. this._x = OIMO.atan2(m32, m33);
  94861. this._z = OIMO.atan2(m21, m11);
  94862. } else {
  94863. this._x = 0;
  94864. this._z = OIMO.atan2(-m12, m22);
  94865. }
  94866. } else if (order === 'YZX') {
  94867. this._z = OIMO.asin(clamp(m21, -1, 1));
  94868. if (OIMO.abs(m21) < 0.99999) {
  94869. this._x = OIMO.atan2(-m23, m22);
  94870. this._y = OIMO.atan2(-m31, m11);
  94871. } else {
  94872. this._x = 0;
  94873. this._y = OIMO.atan2(m13, m33);
  94874. }
  94875. } else if (order === 'XZY') {
  94876. this._z = OIMO.asin(-clamp(m12, -1, 1));
  94877. if (OIMO.abs(m12) < 0.99999) {
  94878. this._x = OIMO.atan2(m32, m22);
  94879. this._y = OIMO.atan2(m13, m11);
  94880. } else {
  94881. this._x = OIMO.atan2(-m23, m33);
  94882. this._y = 0;
  94883. }
  94884. } else {
  94885. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  94886. }
  94887. this._order = order;
  94888. this.onChangeCallback();
  94889. return this;
  94890. },
  94891. setFromQuaternion: function (q, order, update) {
  94892. var clamp = OIMO.clamp;
  94893. // q is assumed to be normalized
  94894. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  94895. var sqx = q.x * q.x;
  94896. var sqy = q.y * q.y;
  94897. var sqz = q.z * q.z;
  94898. var sqw = q.s * q.s;
  94899. order = order || this._order;
  94900. if (order === 'XYZ') {
  94901. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  94902. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  94903. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  94904. } else if (order === 'YXZ') {
  94905. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  94906. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  94907. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  94908. } else if (order === 'ZXY') {
  94909. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  94910. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  94911. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  94912. } else if (order === 'ZYX') {
  94913. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  94914. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  94915. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  94916. } else if (order === 'YZX') {
  94917. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  94918. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  94919. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  94920. } else if (order === 'XZY') {
  94921. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  94922. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  94923. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  94924. } else {
  94925. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  94926. }
  94927. this._order = order;
  94928. if (update !== false) this.onChangeCallback();
  94929. return this;
  94930. },
  94931. reorder: function () {
  94932. // WARNING: this discards revolution information -bhouston
  94933. var q = new OIMO.Quat();
  94934. return function (newOrder) {
  94935. q.setFromEuler(this);
  94936. this.setFromQuaternion(q, newOrder);
  94937. };
  94938. }(),
  94939. equals: function (euler) {
  94940. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  94941. },
  94942. fromArray: function (array) {
  94943. this._x = array[0];
  94944. this._y = array[1];
  94945. this._z = array[2];
  94946. if (array[3] !== undefined) this._order = array[3];
  94947. this.onChangeCallback();
  94948. return this;
  94949. },
  94950. toArray: function () {
  94951. return [this._x, this._y, this._z, this._order];
  94952. },
  94953. onChange: function (callback) {
  94954. this.onChangeCallback = callback;
  94955. return this;
  94956. },
  94957. onChangeCallback: function () { },
  94958. clone: function () {
  94959. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  94960. }
  94961. };
  94962. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  94963. var c1 = OIMO.cos(oy * 0.5);//heading
  94964. var s1 = OIMO.sin(oy * 0.5);
  94965. var c2 = OIMO.cos(oz * 0.5);//altitude
  94966. var s2 = OIMO.sin(oz * 0.5);
  94967. var c3 = OIMO.cos(ox * 0.5);//bank
  94968. var s3 = OIMO.sin(ox * 0.5);
  94969. var c1c2 = c1 * c2;
  94970. var s1s2 = s1 * s2;
  94971. var w = c1c2 * c3 - s1s2 * s3;
  94972. var x = c1c2 * s3 + s1s2 * c3;
  94973. var y = s1 * c2 * c3 + c1 * s2 * s3;
  94974. var z = c1 * s2 * c3 - s1 * c2 * s3;
  94975. var angle = 2 * OIMO.acos(w);
  94976. var norm = x * x + y * y + z * z;
  94977. if (norm < 0.001) {
  94978. x = 1;
  94979. y = z = 0;
  94980. } else {
  94981. norm = OIMO.sqrt(norm);
  94982. x /= norm;
  94983. y /= norm;
  94984. z /= norm;
  94985. }
  94986. return [angle, x, y, z];
  94987. }
  94988. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  94989. var ch = OIMO.cos(oy);//heading
  94990. var sh = OIMO.sin(oy);
  94991. var ca = OIMO.cos(oz);//altitude
  94992. var sa = OIMO.sin(oz);
  94993. var cb = OIMO.cos(ox);//bank
  94994. var sb = OIMO.sin(ox);
  94995. var mtx = new OIMO.Mat33();
  94996. var te = mtx.elements;
  94997. te[0] = ch * ca;
  94998. te[1] = sh * sb - ch * sa * cb;
  94999. te[2] = ch * sa * sb + sh * cb;
  95000. te[3] = sa;
  95001. te[4] = ca * cb;
  95002. te[5] = -ca * sb;
  95003. te[6] = -sh * ca;
  95004. te[7] = sh * sa * cb + ch * sb;
  95005. te[8] = -sh * sa * sb + ch * cb;
  95006. return mtx;
  95007. }
  95008. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95009. var te = mtx.elements;
  95010. var x, y, z;
  95011. if (te[3] > 0.998) { // singularity at north pole
  95012. y = OIMO.atan2(te[2], te[8]);
  95013. z = OIMO.PI / 2;
  95014. x = 0;
  95015. } else if (te[3] < -0.998) { // singularity at south pole
  95016. y = OIMO.atan2(te[2], te[8]);
  95017. z = -OIMO.PI / 2;
  95018. x = 0;
  95019. } else {
  95020. y = OIMO.atan2(-te[6], te[0]);
  95021. x = OIMO.atan2(-te[5], te[4]);
  95022. z = OIMO.asin(te[3]);
  95023. }
  95024. return [x, y, z];
  95025. }
  95026. OIMO.unwrapDegrees = function (r) {
  95027. r = r % 360;
  95028. if (r > 180) r -= 360;
  95029. if (r < -180) r += 360;
  95030. return r;
  95031. }
  95032. OIMO.unwrapRadian = function (r) {
  95033. r = r % OIMO.TwoPI;
  95034. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95035. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95036. return r;
  95037. }
  95038. OIMO.Distance3d = function (p1, p2) {
  95039. var xd = p2[0] - p1[0];
  95040. var yd = p2[1] - p1[1];
  95041. var zd = p2[2] - p1[2];
  95042. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95043. }
  95044. /**
  95045. * The base class of all type of the constraints.
  95046. * @author saharan
  95047. */
  95048. OIMO.Constraint = function () {
  95049. // The parent world of the constraint.
  95050. this.parent = null;
  95051. // The first body of the constraint.
  95052. this.body1 = null;
  95053. // The second body of the constraint.
  95054. this.body2 = null;
  95055. // Internal
  95056. this.addedToIsland = false;
  95057. }
  95058. OIMO.Constraint.prototype = {
  95059. constructor: OIMO.Constraint,
  95060. /**
  95061. * Prepare for solving the constraint.
  95062. * @param timeStep
  95063. * @param invTimeStep
  95064. */
  95065. preSolve: function (timeStep, invTimeStep) {
  95066. OIMO.Error("Constraint", "Inheritance error.");
  95067. },
  95068. /**
  95069. * Solve the constraint.
  95070. * This is usually called iteratively.
  95071. */
  95072. solve: function () {
  95073. OIMO.Error("Constraint", "Inheritance error.");
  95074. },
  95075. /**
  95076. * Do the post-processing.
  95077. */
  95078. postSolve: function () {
  95079. OIMO.Error("Constraint", "Inheritance error.");
  95080. }
  95081. }
  95082. /**
  95083. * Joints are used to constrain the motion between two rigid bodies.
  95084. * @author saharan
  95085. * @author lo-th
  95086. */
  95087. OIMO.Joint = function (config) {
  95088. OIMO.Constraint.call(this);
  95089. // joint name
  95090. this.name = "";
  95091. // The type of the joint.
  95092. this.type = OIMO.JOINT_NULL;
  95093. // The previous joint in the world.
  95094. this.prev = null;
  95095. // The next joint in the world.
  95096. this.next = null;
  95097. this.body1 = config.body1;
  95098. this.body2 = config.body2;
  95099. // The anchor point on the first rigid body in local coordinate system.
  95100. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95101. // The anchor point on the second rigid body in local coordinate system.
  95102. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95103. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95104. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95105. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95106. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95107. // The anchor point on the first rigid body in world coordinate system.
  95108. this.anchorPoint1 = new OIMO.Vec3();
  95109. // The anchor point on the second rigid body in world coordinate system.
  95110. this.anchorPoint2 = new OIMO.Vec3();
  95111. // Whether allow collision between connected rigid bodies or not.
  95112. this.allowCollision = config.allowCollision;
  95113. this.b1Link = new OIMO.JointLink(this);
  95114. this.b2Link = new OIMO.JointLink(this);
  95115. this.matrix = new OIMO.Mat44();
  95116. };
  95117. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95118. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95119. // Update all the anchor points.
  95120. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95121. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95122. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95123. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95124. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95125. };
  95126. // Attach the joint from the bodies.
  95127. OIMO.Joint.prototype.attach = function () {
  95128. this.b1Link.body = this.body2;
  95129. this.b2Link.body = this.body1;
  95130. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95131. else this.b1Link.next = null;
  95132. this.body1.jointLink = this.b1Link;
  95133. this.body1.numJoints++;
  95134. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95135. else this.b2Link.next = null;
  95136. this.body2.jointLink = this.b2Link;
  95137. this.body2.numJoints++;
  95138. };
  95139. // Detach the joint from the bodies.
  95140. OIMO.Joint.prototype.detach = function () {
  95141. var prev = this.b1Link.prev;
  95142. var next = this.b1Link.next;
  95143. if (prev != null) prev.next = next;
  95144. if (next != null) next.prev = prev;
  95145. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95146. this.b1Link.prev = null;
  95147. this.b1Link.next = null;
  95148. this.b1Link.body = null;
  95149. this.body1.numJoints--;
  95150. prev = this.b2Link.prev;
  95151. next = this.b2Link.next;
  95152. if (prev != null) prev.next = next;
  95153. if (next != null) next.prev = prev;
  95154. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95155. this.b2Link.prev = null;
  95156. this.b2Link.next = null;
  95157. this.b2Link.body = null;
  95158. this.body2.numJoints--;
  95159. this.b1Link.body = null;
  95160. this.b2Link.body = null;
  95161. };
  95162. // Awake the bodies.
  95163. OIMO.Joint.prototype.awake = function () {
  95164. this.body1.awake();
  95165. this.body2.awake();
  95166. };
  95167. // calculation function
  95168. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95169. };
  95170. OIMO.Joint.prototype.solve = function () {
  95171. };
  95172. OIMO.Joint.prototype.postSolve = function () {
  95173. };
  95174. // Delete process
  95175. OIMO.Joint.prototype.remove = function () {
  95176. this.dispose();
  95177. };
  95178. OIMO.Joint.prototype.dispose = function () {
  95179. this.parent.removeJoint(this);
  95180. };
  95181. // Three js add
  95182. OIMO.Joint.prototype.getPosition = function () {
  95183. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95184. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95185. return [p1, p2];
  95186. };
  95187. OIMO.Joint.prototype.getMatrix = function () {
  95188. var m = this.matrix.elements;
  95189. var p1 = this.anchorPoint1;
  95190. var p2 = this.anchorPoint2;
  95191. m[0] = p1.x * OIMO.WORLD_SCALE;
  95192. m[1] = p1.y * OIMO.WORLD_SCALE;
  95193. m[2] = p1.z * OIMO.WORLD_SCALE;
  95194. m[3] = 0;
  95195. m[4] = p2.x * OIMO.WORLD_SCALE;
  95196. m[5] = p2.y * OIMO.WORLD_SCALE;
  95197. m[6] = p2.z * OIMO.WORLD_SCALE;
  95198. m[7] = 0;
  95199. return m;
  95200. };
  95201. /**
  95202. * A joint configuration holds all configuration data for constructing a joint.
  95203. * Joint configurations can be reused safely.
  95204. * @author saharan
  95205. */
  95206. OIMO.JointConfig = function () {
  95207. // The first rigid body of the joint.
  95208. this.body1 = null;
  95209. // The second rigid body of the joint.
  95210. this.body2 = null;
  95211. // The anchor point on the first rigid body in local coordinate system.
  95212. this.localAnchorPoint1 = new OIMO.Vec3();
  95213. // The anchor point on the second rigid body in local coordinate system.
  95214. this.localAnchorPoint2 = new OIMO.Vec3();
  95215. // The axis in the first body's coordinate system.
  95216. // his property is available in some joints.
  95217. this.localAxis1 = new OIMO.Vec3();
  95218. // The axis in the second body's coordinate system.
  95219. // This property is available in some joints.
  95220. this.localAxis2 = new OIMO.Vec3();
  95221. // Whether allow collision between connected rigid bodies or not.
  95222. this.allowCollision = false;
  95223. };
  95224. /**
  95225. * A link list of joints.
  95226. * @author saharan
  95227. */
  95228. OIMO.JointLink = function (joint) {
  95229. // The previous joint link.
  95230. this.prev = null;
  95231. // The next joint link.
  95232. this.next = null;
  95233. // The other rigid body connected to the joint.
  95234. this.body = null;
  95235. // The joint of the link.
  95236. this.joint = joint;
  95237. };
  95238. /**
  95239. * An information of limit and motor.
  95240. * @author saharan
  95241. */
  95242. OIMO.LimitMotor = function (axis, fixed) {
  95243. fixed = fixed || false;
  95244. // The axis of the constraint.
  95245. this.axis = axis;
  95246. // The current angle for rotational constraints.
  95247. this.angle = 0;
  95248. // The lower limit. Set lower > upper to disable
  95249. this.lowerLimit = fixed ? 0 : 1;
  95250. //if(fixed)this.lowerLimit = 0;
  95251. //else this.lowerLimit = 1;
  95252. // The upper limit. Set lower > upper to disable.
  95253. this.upperLimit = 0;
  95254. // The target motor speed.
  95255. this.motorSpeed = 0;
  95256. // The maximum motor force or torque. Set 0 to disable.
  95257. this.maxMotorForce = 0;
  95258. // The frequency of the spring. Set 0 to disable.
  95259. this.frequency = 0;
  95260. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95261. this.dampingRatio = 0;
  95262. };
  95263. OIMO.LimitMotor.prototype = {
  95264. constructor: OIMO.LimitMotor,
  95265. /**
  95266. * Set limit data into this constraint.
  95267. * @param lowerLimit
  95268. * @param upperLimit
  95269. */
  95270. setLimit: function (lowerLimit, upperLimit) {
  95271. this.lowerLimit = lowerLimit;
  95272. this.upperLimit = upperLimit;
  95273. },
  95274. /**
  95275. * Set motor data into this constraint.
  95276. * @param motorSpeed
  95277. * @param maxMotorForce
  95278. */
  95279. setMotor: function (motorSpeed, maxMotorForce) {
  95280. this.motorSpeed = motorSpeed;
  95281. this.maxMotorForce = maxMotorForce;
  95282. },
  95283. /**
  95284. * Set spring data into this constraint.
  95285. * @param frequency
  95286. * @param dampingRatio
  95287. */
  95288. setSpring: function (frequency, dampingRatio) {
  95289. this.frequency = frequency;
  95290. this.dampingRatio = dampingRatio;
  95291. }
  95292. };
  95293. /**
  95294. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95295. * @author saharan
  95296. * @author lo-th
  95297. */
  95298. OIMO.BallAndSocketJoint = function (config) {
  95299. OIMO.Joint.call(this, config);
  95300. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95301. this.lc = new OIMO.LinearConstraint(this);
  95302. };
  95303. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95304. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95305. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95306. this.updateAnchorPoints();
  95307. this.lc.preSolve(timeStep, invTimeStep);
  95308. };
  95309. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95310. this.lc.solve();
  95311. };
  95312. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95313. };
  95314. /**
  95315. * A distance joint limits the distance between two anchor points on rigid bodies.
  95316. * @author saharan
  95317. * @author lo-th
  95318. */
  95319. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95320. OIMO.Joint.call(this, config);
  95321. this.type = OIMO.JOINT_DISTANCE;
  95322. this.normal = new OIMO.Vec3();
  95323. this.nr = new OIMO.Vec3();
  95324. // The limit and motor information of the joint.
  95325. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95326. this.limitMotor.lowerLimit = minDistance;
  95327. this.limitMotor.upperLimit = maxDistance;
  95328. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95329. };
  95330. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95331. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95332. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95333. this.updateAnchorPoints();
  95334. //var nr = this.nr;
  95335. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95336. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95337. //if(len>0) len = 1/len;
  95338. //this.normal.scale( nr, len );
  95339. this.normal.normalize(this.nr);
  95340. this.t.preSolve(timeStep, invTimeStep);
  95341. };
  95342. OIMO.DistanceJoint.prototype.solve = function () {
  95343. this.t.solve();
  95344. };
  95345. OIMO.DistanceJoint.prototype.postSolve = function () {
  95346. };
  95347. /**
  95348. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95349. * @author saharan
  95350. * @author lo-th
  95351. */
  95352. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95353. OIMO.Joint.call(this, config);
  95354. this.type = OIMO.JOINT_HINGE;
  95355. // The axis in the first body's coordinate system.
  95356. this.localAxis1 = config.localAxis1.clone().norm();
  95357. // The axis in the second body's coordinate system.
  95358. this.localAxis2 = config.localAxis2.clone().norm();
  95359. // make angle axis 1
  95360. this.localAngle1 = new OIMO.Vec3(
  95361. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95362. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95363. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95364. ).norm();
  95365. // make angle axis 2
  95366. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95367. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95368. this.nor = new OIMO.Vec3();
  95369. this.tan = new OIMO.Vec3();
  95370. this.bin = new OIMO.Vec3();
  95371. this.ax1 = new OIMO.Vec3();
  95372. this.ax2 = new OIMO.Vec3();
  95373. this.an1 = new OIMO.Vec3();
  95374. this.an2 = new OIMO.Vec3();
  95375. // The rotational limit and motor information of the joint.
  95376. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95377. this.limitMotor.lowerLimit = lowerAngleLimit;
  95378. this.limitMotor.upperLimit = upperAngleLimit;
  95379. this.lc = new OIMO.LinearConstraint(this);
  95380. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95381. };
  95382. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95383. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95384. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95385. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95386. this.updateAnchorPoints();
  95387. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95388. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95389. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95390. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95391. this.nor.set(
  95392. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95393. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95394. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95395. ).norm();
  95396. this.tan.set(
  95397. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95398. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95399. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95400. ).norm();
  95401. this.bin.set(
  95402. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95403. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95404. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95405. );
  95406. // calculate hinge angle
  95407. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95408. if (
  95409. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95410. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95411. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95412. ) {
  95413. this.limitMotor.angle = -limite;
  95414. } else {
  95415. this.limitMotor.angle = limite;
  95416. }
  95417. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95418. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95419. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95420. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95421. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95422. this.r3.preSolve(timeStep, invTimeStep);
  95423. this.lc.preSolve(timeStep, invTimeStep);
  95424. };
  95425. OIMO.HingeJoint.prototype.solve = function () {
  95426. this.r3.solve();
  95427. this.lc.solve();
  95428. };
  95429. OIMO.HingeJoint.prototype.postSolve = function () {
  95430. };
  95431. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95432. if (cos > 1) return 0;
  95433. else if (cos < -1) return OIMO.PI;
  95434. else return OIMO.acos(cos);
  95435. };
  95436. /**
  95437. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95438. * @author saharan
  95439. * @author lo-th
  95440. */
  95441. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95442. OIMO.Joint.call(this, config);
  95443. this.type = OIMO.JOINT_PRISMATIC;
  95444. // The axis in the first body's coordinate system.
  95445. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95446. // The axis in the second body's coordinate system.
  95447. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95448. this.localAxis1X = this.localAxis1.x;
  95449. this.localAxis1Y = this.localAxis1.y;
  95450. this.localAxis1Z = this.localAxis1.z;
  95451. this.localAxis2X = this.localAxis2.x;
  95452. this.localAxis2Y = this.localAxis2.y;
  95453. this.localAxis2Z = this.localAxis2.z;
  95454. this.nor = new OIMO.Vec3();
  95455. this.tan = new OIMO.Vec3();
  95456. this.bin = new OIMO.Vec3();
  95457. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95458. // The translational limit and motor information of the joint.
  95459. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95460. this.limitMotor.lowerLimit = lowerTranslation;
  95461. this.limitMotor.upperLimit = upperTranslation;
  95462. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95463. };
  95464. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95465. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95466. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95467. var tmpM;
  95468. var tmp1X;
  95469. var tmp1Y;
  95470. var tmp1Z;
  95471. this.updateAnchorPoints();
  95472. tmpM = this.body1.rotation.elements;
  95473. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95474. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95475. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95476. tmpM = this.body2.rotation.elements;
  95477. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95478. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95479. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95480. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95481. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95482. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95483. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95484. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95485. nx *= tmp1X;
  95486. ny *= tmp1X;
  95487. nz *= tmp1X;
  95488. var tx = ny * nx - nz * nz;
  95489. var ty = -nz * ny - nx * nx;
  95490. var tz = nx * nz + ny * ny;
  95491. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95492. tx *= tmp1X;
  95493. ty *= tmp1X;
  95494. tz *= tmp1X;
  95495. var bx = ny * tz - nz * ty;
  95496. var by = nz * tx - nx * tz;
  95497. var bz = nx * ty - ny * tx;
  95498. this.nor.init(nx, ny, nz);
  95499. this.tan.init(tx, ty, tz);
  95500. this.bin.init(bx, by, bz);
  95501. this.ac.preSolve(timeStep, invTimeStep);
  95502. this.t3.preSolve(timeStep, invTimeStep);
  95503. };
  95504. OIMO.PrismaticJoint.prototype.solve = function () {
  95505. this.ac.solve();
  95506. this.t3.solve();
  95507. };
  95508. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95509. };
  95510. /**
  95511. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95512. * @author saharan
  95513. * @author lo-th
  95514. */
  95515. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95516. OIMO.Joint.call(this, config);
  95517. this.type = OIMO.JOINT_SLIDER;
  95518. // The first axis in local coordinate system.
  95519. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95520. // The second axis in local coordinate system.
  95521. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95522. var len;
  95523. this.localAxis1X = this.localAxis1.x;
  95524. this.localAxis1Y = this.localAxis1.y;
  95525. this.localAxis1Z = this.localAxis1.z;
  95526. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95527. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95528. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95529. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95530. this.localAngAxis1X *= len;
  95531. this.localAngAxis1Y *= len;
  95532. this.localAngAxis1Z *= len;
  95533. this.localAxis2X = this.localAxis2.x;
  95534. this.localAxis2Y = this.localAxis2.y;
  95535. this.localAxis2Z = this.localAxis2.z;
  95536. // make angle axis 2
  95537. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95538. var tarc = arc.elements;
  95539. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95540. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95541. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95542. this.nor = new OIMO.Vec3();
  95543. this.tan = new OIMO.Vec3();
  95544. this.bin = new OIMO.Vec3();
  95545. // The limit and motor for the rotation
  95546. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95547. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95548. // The limit and motor for the translation.
  95549. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95550. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95551. this.translationalLimitMotor.upperLimit = upperTranslation;
  95552. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95553. };
  95554. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95555. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95556. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95557. var tmpM;
  95558. var tmp1X;
  95559. var tmp1Y;
  95560. var tmp1Z;
  95561. this.updateAnchorPoints();
  95562. tmpM = this.body1.rotation.elements;
  95563. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95564. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95565. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95566. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95567. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95568. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95569. tmpM = this.body2.rotation.elements;
  95570. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95571. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95572. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95573. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95574. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95575. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95576. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95577. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95578. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95579. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95580. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95581. nx *= tmp1X;
  95582. ny *= tmp1X;
  95583. nz *= tmp1X;
  95584. var tx = ny * nx - nz * nz;
  95585. var ty = -nz * ny - nx * nx;
  95586. var tz = nx * nz + ny * ny;
  95587. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95588. tx *= tmp1X;
  95589. ty *= tmp1X;
  95590. tz *= tmp1X;
  95591. var bx = ny * tz - nz * ty;
  95592. var by = nz * tx - nx * tz;
  95593. var bz = nx * ty - ny * tx;
  95594. this.nor.init(nx, ny, nz);
  95595. this.tan.init(tx, ty, tz);
  95596. this.bin.init(bx, by, bz);
  95597. // ----------------------------------------------
  95598. // calculate hinge angle
  95599. // ----------------------------------------------
  95600. if (
  95601. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95602. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95603. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95604. ) {
  95605. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95606. } else {
  95607. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95608. }
  95609. // angular error
  95610. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95611. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95612. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95613. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95614. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95615. this.r3.preSolve(timeStep, invTimeStep);
  95616. this.t3.preSolve(timeStep, invTimeStep);
  95617. };
  95618. OIMO.SliderJoint.prototype.solve = function () {
  95619. this.r3.solve();
  95620. this.t3.solve();
  95621. };
  95622. OIMO.SliderJoint.prototype.postSolve = function () {
  95623. };
  95624. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95625. if (cos > 1) return 0;
  95626. else if (cos < -1) return OIMO.PI;
  95627. else return OIMO.acos(cos);
  95628. };
  95629. /**
  95630. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95631. * The wheel joint also allows for relative translation for the suspension.
  95632. * @author saharan
  95633. * @author lo-th
  95634. */
  95635. OIMO.WheelJoint = function (config) {
  95636. OIMO.Joint.call(this, config);
  95637. this.type = OIMO.JOINT_WHEEL;
  95638. // The first axis in local coordinate system.
  95639. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95640. // The second axis in local coordinate system.
  95641. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95642. var len;
  95643. this.localAxis1X = this.localAxis1.x;
  95644. this.localAxis1Y = this.localAxis1.y;
  95645. this.localAxis1Z = this.localAxis1.z;
  95646. this.localAxis2X = this.localAxis2.x;
  95647. this.localAxis2Y = this.localAxis2.y;
  95648. this.localAxis2Z = this.localAxis2.z;
  95649. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95650. if (dot > -1 && dot < 1) {
  95651. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95652. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95653. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95654. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95655. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95656. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95657. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95658. this.localAngAxis1X *= len;
  95659. this.localAngAxis1Y *= len;
  95660. this.localAngAxis1Z *= len;
  95661. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95662. this.localAngAxis2X *= len;
  95663. this.localAngAxis2Y *= len;
  95664. this.localAngAxis2Z *= len;
  95665. } else {
  95666. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95667. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95668. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95669. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95670. this.localAngAxis1X *= len;
  95671. this.localAngAxis1Y *= len;
  95672. this.localAngAxis1Z *= len;
  95673. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95674. var tarc = arc.elements;
  95675. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95676. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95677. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95678. }
  95679. this.nor = new OIMO.Vec3();
  95680. this.tan = new OIMO.Vec3();
  95681. this.bin = new OIMO.Vec3();
  95682. // The translational limit and motor information of the joint.
  95683. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95684. this.translationalLimitMotor.frequency = 8;
  95685. this.translationalLimitMotor.dampingRatio = 1;
  95686. // The first rotational limit and motor information of the joint.
  95687. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95688. // The second rotational limit and motor information of the joint.
  95689. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95690. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95691. this.t3.weight = 1;
  95692. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95693. };
  95694. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95695. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95696. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95697. var tmpM;
  95698. var tmp1X;
  95699. var tmp1Y;
  95700. var tmp1Z;
  95701. this.updateAnchorPoints();
  95702. tmpM = this.body1.rotation.elements;
  95703. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95704. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95705. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95706. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95707. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95708. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95709. tmpM = this.body2.rotation.elements;
  95710. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95711. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95712. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95713. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95714. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95715. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95716. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95717. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95718. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95719. } else {
  95720. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95721. }
  95722. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95723. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95724. } else {
  95725. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95726. }
  95727. var nx = y2 * z1 - z2 * y1;
  95728. var ny = z2 * x1 - x2 * z1;
  95729. var nz = x2 * y1 - y2 * x1;
  95730. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95731. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95732. nx *= tmp1X;
  95733. ny *= tmp1X;
  95734. nz *= tmp1X;
  95735. var tx = ny * z2 - nz * y2;
  95736. var ty = nz * x2 - nx * z2;
  95737. var tz = nx * y2 - ny * x2;
  95738. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95739. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95740. tx *= tmp1X;
  95741. ty *= tmp1X;
  95742. tz *= tmp1X;
  95743. var bx = y1 * nz - z1 * ny;
  95744. var by = z1 * nx - x1 * nz;
  95745. var bz = x1 * ny - y1 * nx;
  95746. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95747. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95748. bx *= tmp1X;
  95749. by *= tmp1X;
  95750. bz *= tmp1X;
  95751. this.nor.init(nx, ny, nz);
  95752. this.tan.init(tx, ty, tz);
  95753. this.bin.init(bx, by, bz);
  95754. this.r3.preSolve(timeStep, invTimeStep);
  95755. this.t3.preSolve(timeStep, invTimeStep);
  95756. };
  95757. OIMO.WheelJoint.prototype.solve = function () {
  95758. this.r3.solve();
  95759. this.t3.solve();
  95760. };
  95761. OIMO.WheelJoint.prototype.postSolve = function () {
  95762. };
  95763. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95764. if (cos > 1) return 0;
  95765. else if (cos < -1) return OIMO.PI;
  95766. else return OIMO.acos(cos);
  95767. };
  95768. /**
  95769. * An angular constraint for all axes for various joints.
  95770. * @author saharan
  95771. */
  95772. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95773. this.joint = joint;
  95774. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95775. this.relativeOrientation = new OIMO.Quat();
  95776. this.ii1 = null;
  95777. this.ii2 = null;
  95778. this.dd = null;
  95779. this.vel = new OIMO.Vec3();
  95780. this.imp = new OIMO.Vec3();
  95781. this.rn0 = new OIMO.Vec3();
  95782. this.rn1 = new OIMO.Vec3();
  95783. this.rn2 = new OIMO.Vec3();
  95784. this.b1 = joint.body1;
  95785. this.b2 = joint.body2;
  95786. this.a1 = this.b1.angularVelocity;
  95787. this.a2 = this.b2.angularVelocity;
  95788. this.i1 = this.b1.inverseInertia;
  95789. this.i2 = this.b2.inverseInertia;
  95790. };
  95791. OIMO.AngularConstraint.prototype = {
  95792. constructor: OIMO.AngularConstraint,
  95793. preSolve: function (timeStep, invTimeStep) {
  95794. var inv, len, v, vv;
  95795. this.ii1 = this.i1.clone();
  95796. this.ii2 = this.i2.clone();
  95797. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95798. 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]));
  95799. this.dd = new OIMO.Mat33(
  95800. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95801. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95802. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95803. ).multiply(inv);
  95804. this.relativeOrientation.invert(this.b1.orientation);
  95805. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95806. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95807. inv = this.relativeOrientation.s * 2;
  95808. this.vel.scale(this.relativeOrientation, inv);
  95809. len = this.vel.length();
  95810. if (len > 0.02) {
  95811. len = (0.02 - len) / len * invTimeStep * 0.05;
  95812. this.vel.scaleEqual(len);
  95813. } else {
  95814. this.vel.init();
  95815. }
  95816. this.rn1.mulMat(this.ii1, this.imp);
  95817. this.rn2.mulMat(this.ii2, this.imp);
  95818. this.a1.addEqual(this.rn1);
  95819. this.a2.subEqual(this.rn2);
  95820. },
  95821. solve: function () {
  95822. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95823. this.rn0.mulMat(this.dd, r);
  95824. this.rn1.mulMat(this.ii1, this.rn0);
  95825. this.rn2.mulMat(this.ii2, this.rn0);
  95826. this.imp.addEqual(this.rn0);
  95827. this.a1.addEqual(this.rn1);
  95828. this.a2.subEqual(this.rn2);
  95829. }
  95830. };
  95831. /**
  95832. * A linear constraint for all axes for various joints.
  95833. * @author saharan
  95834. */
  95835. OIMO.LinearConstraint = function (joint) {
  95836. this.m1 = NaN;
  95837. this.m2 = NaN;
  95838. this.ii1 = null;
  95839. this.ii2 = null;
  95840. this.dd = null;
  95841. this.r1x = NaN;
  95842. this.r1y = NaN;
  95843. this.r1z = NaN;
  95844. this.r2x = NaN;
  95845. this.r2y = NaN;
  95846. this.r2z = NaN;
  95847. this.ax1x = NaN;
  95848. this.ax1y = NaN;
  95849. this.ax1z = NaN;
  95850. this.ay1x = NaN;
  95851. this.ay1y = NaN;
  95852. this.ay1z = NaN;
  95853. this.az1x = NaN;
  95854. this.az1y = NaN;
  95855. this.az1z = NaN;
  95856. this.ax2x = NaN;
  95857. this.ax2y = NaN;
  95858. this.ax2z = NaN;
  95859. this.ay2x = NaN;
  95860. this.ay2y = NaN;
  95861. this.ay2z = NaN;
  95862. this.az2x = NaN;
  95863. this.az2y = NaN;
  95864. this.az2z = NaN;
  95865. this.vel = NaN;
  95866. this.velx = NaN;
  95867. this.vely = NaN;
  95868. this.velz = NaN;
  95869. this.joint = joint;
  95870. this.r1 = joint.relativeAnchorPoint1;
  95871. this.r2 = joint.relativeAnchorPoint2;
  95872. this.p1 = joint.anchorPoint1;
  95873. this.p2 = joint.anchorPoint2;
  95874. this.b1 = joint.body1;
  95875. this.b2 = joint.body2;
  95876. this.l1 = this.b1.linearVelocity;
  95877. this.l2 = this.b2.linearVelocity;
  95878. this.a1 = this.b1.angularVelocity;
  95879. this.a2 = this.b2.angularVelocity;
  95880. this.i1 = this.b1.inverseInertia;
  95881. this.i2 = this.b2.inverseInertia;
  95882. this.impx = 0;
  95883. this.impy = 0;
  95884. this.impz = 0;
  95885. }
  95886. OIMO.LinearConstraint.prototype = {
  95887. constructor: OIMO.LinearConstraint,
  95888. preSolve: function (timeStep, invTimeStep) {
  95889. this.r1x = this.r1.x;
  95890. this.r1y = this.r1.y;
  95891. this.r1z = this.r1.z;
  95892. this.r2x = this.r2.x;
  95893. this.r2y = this.r2.y;
  95894. this.r2z = this.r2.z;
  95895. this.m1 = this.b1.inverseMass;
  95896. this.m2 = this.b2.inverseMass;
  95897. this.ii1 = this.i1.clone();
  95898. this.ii2 = this.i2.clone();
  95899. var ii1 = this.ii1.elements;
  95900. var ii2 = this.ii2.elements;
  95901. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  95902. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  95903. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  95904. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  95905. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  95906. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  95907. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  95908. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  95909. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  95910. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  95911. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  95912. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  95913. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  95914. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  95915. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  95916. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  95917. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  95918. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  95919. // calculate point-to-point mass matrix
  95920. // from impulse equation
  95921. //
  95922. // M = ([/m] - [r^][/I][r^]) ^ -1
  95923. //
  95924. // where
  95925. //
  95926. // [/m] = |1/m, 0, 0|
  95927. // |0, 1/m, 0|
  95928. // |0, 0, 1/m|
  95929. //
  95930. // [r^] = |0, -rz, ry|
  95931. // |rz, 0, -rx|
  95932. // |-ry, rx, 0|
  95933. //
  95934. // [/I] = Inverted moment inertia
  95935. var rxx = this.m1 + this.m2;
  95936. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  95937. var k = kk.elements;
  95938. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  95939. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95940. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  95941. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95942. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  95943. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  95944. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  95945. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  95946. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  95947. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  95948. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95949. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  95950. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95951. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  95952. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  95953. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  95954. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  95955. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  95956. 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]));
  95957. this.dd = new OIMO.Mat33(
  95958. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  95959. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  95960. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  95961. ).multiply(inv);
  95962. this.velx = this.p2.x - this.p1.x;
  95963. this.vely = this.p2.y - this.p1.y;
  95964. this.velz = this.p2.z - this.p1.z;
  95965. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  95966. if (len > 0.005) {
  95967. len = (0.005 - len) / len * invTimeStep * 0.05;
  95968. this.velx *= len;
  95969. this.vely *= len;
  95970. this.velz *= len;
  95971. } else {
  95972. this.velx = 0;
  95973. this.vely = 0;
  95974. this.velz = 0;
  95975. }
  95976. this.impx *= 0.95;
  95977. this.impy *= 0.95;
  95978. this.impz *= 0.95;
  95979. this.l1.x += this.impx * this.m1;
  95980. this.l1.y += this.impy * this.m1;
  95981. this.l1.z += this.impz * this.m1;
  95982. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  95983. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  95984. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  95985. this.l2.x -= this.impx * this.m2;
  95986. this.l2.y -= this.impy * this.m2;
  95987. this.l2.z -= this.impz * this.m2;
  95988. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  95989. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  95990. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  95991. },
  95992. solve: function () {
  95993. var d = this.dd.elements;
  95994. 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;
  95995. 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;
  95996. 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;
  95997. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  95998. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  95999. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96000. this.impx += nimpx;
  96001. this.impy += nimpy;
  96002. this.impz += nimpz;
  96003. this.l1.x += nimpx * this.m1;
  96004. this.l1.y += nimpy * this.m1;
  96005. this.l1.z += nimpz * this.m1;
  96006. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96007. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96008. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96009. this.l2.x -= nimpx * this.m2;
  96010. this.l2.y -= nimpy * this.m2;
  96011. this.l2.z -= nimpz * this.m2;
  96012. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96013. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96014. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96015. }
  96016. }
  96017. /**
  96018. * A three-axis rotational constraint for various joints.
  96019. * @author saharan
  96020. */
  96021. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96022. this.cfm1 = NaN;
  96023. this.cfm2 = NaN;
  96024. this.cfm3 = NaN;
  96025. this.i1e00 = NaN;
  96026. this.i1e01 = NaN;
  96027. this.i1e02 = NaN;
  96028. this.i1e10 = NaN;
  96029. this.i1e11 = NaN;
  96030. this.i1e12 = NaN;
  96031. this.i1e20 = NaN;
  96032. this.i1e21 = NaN;
  96033. this.i1e22 = NaN;
  96034. this.i2e00 = NaN;
  96035. this.i2e01 = NaN;
  96036. this.i2e02 = NaN;
  96037. this.i2e10 = NaN;
  96038. this.i2e11 = NaN;
  96039. this.i2e12 = NaN;
  96040. this.i2e20 = NaN;
  96041. this.i2e21 = NaN;
  96042. this.i2e22 = NaN;
  96043. this.ax1 = NaN;
  96044. this.ay1 = NaN;
  96045. this.az1 = NaN;
  96046. this.ax2 = NaN;
  96047. this.ay2 = NaN;
  96048. this.az2 = NaN;
  96049. this.ax3 = NaN;
  96050. this.ay3 = NaN;
  96051. this.az3 = NaN;
  96052. this.a1x1 = NaN; // jacoians
  96053. this.a1y1 = NaN;
  96054. this.a1z1 = NaN;
  96055. this.a2x1 = NaN;
  96056. this.a2y1 = NaN;
  96057. this.a2z1 = NaN;
  96058. this.a1x2 = NaN;
  96059. this.a1y2 = NaN;
  96060. this.a1z2 = NaN;
  96061. this.a2x2 = NaN;
  96062. this.a2y2 = NaN;
  96063. this.a2z2 = NaN;
  96064. this.a1x3 = NaN;
  96065. this.a1y3 = NaN;
  96066. this.a1z3 = NaN;
  96067. this.a2x3 = NaN;
  96068. this.a2y3 = NaN;
  96069. this.a2z3 = NaN;
  96070. this.lowerLimit1 = NaN;
  96071. this.upperLimit1 = NaN;
  96072. this.limitVelocity1 = NaN;
  96073. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96074. this.enableMotor1 = false;
  96075. this.motorSpeed1 = NaN;
  96076. this.maxMotorForce1 = NaN;
  96077. this.maxMotorImpulse1 = NaN;
  96078. this.lowerLimit2 = NaN;
  96079. this.upperLimit2 = NaN;
  96080. this.limitVelocity2 = NaN;
  96081. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96082. this.enableMotor2 = false;
  96083. this.motorSpeed2 = NaN;
  96084. this.maxMotorForce2 = NaN;
  96085. this.maxMotorImpulse2 = NaN;
  96086. this.lowerLimit3 = NaN;
  96087. this.upperLimit3 = NaN;
  96088. this.limitVelocity3 = NaN;
  96089. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96090. this.enableMotor3 = false;
  96091. this.motorSpeed3 = NaN;
  96092. this.maxMotorForce3 = NaN;
  96093. this.maxMotorImpulse3 = NaN;
  96094. this.k00 = NaN; // K = J*M*JT
  96095. this.k01 = NaN;
  96096. this.k02 = NaN;
  96097. this.k10 = NaN;
  96098. this.k11 = NaN;
  96099. this.k12 = NaN;
  96100. this.k20 = NaN;
  96101. this.k21 = NaN;
  96102. this.k22 = NaN;
  96103. this.kv00 = NaN; // diagonals without CFMs
  96104. this.kv11 = NaN;
  96105. this.kv22 = NaN;
  96106. this.dv00 = NaN; // ...inverted
  96107. this.dv11 = NaN;
  96108. this.dv22 = NaN;
  96109. this.d00 = NaN; // K^-1
  96110. this.d01 = NaN;
  96111. this.d02 = NaN;
  96112. this.d10 = NaN;
  96113. this.d11 = NaN;
  96114. this.d12 = NaN;
  96115. this.d20 = NaN;
  96116. this.d21 = NaN;
  96117. this.d22 = NaN;
  96118. this.limitMotor1 = limitMotor1;
  96119. this.limitMotor2 = limitMotor2;
  96120. this.limitMotor3 = limitMotor3;
  96121. this.b1 = joint.body1;
  96122. this.b2 = joint.body2;
  96123. this.a1 = this.b1.angularVelocity;
  96124. this.a2 = this.b2.angularVelocity;
  96125. this.i1 = this.b1.inverseInertia;
  96126. this.i2 = this.b2.inverseInertia;
  96127. this.limitImpulse1 = 0;
  96128. this.motorImpulse1 = 0;
  96129. this.limitImpulse2 = 0;
  96130. this.motorImpulse2 = 0;
  96131. this.limitImpulse3 = 0;
  96132. this.motorImpulse3 = 0;
  96133. }
  96134. OIMO.Rotational3Constraint.prototype = {
  96135. constructor: OIMO.Rotational3Constraint,
  96136. preSolve: function (timeStep, invTimeStep) {
  96137. this.ax1 = this.limitMotor1.axis.x;
  96138. this.ay1 = this.limitMotor1.axis.y;
  96139. this.az1 = this.limitMotor1.axis.z;
  96140. this.ax2 = this.limitMotor2.axis.x;
  96141. this.ay2 = this.limitMotor2.axis.y;
  96142. this.az2 = this.limitMotor2.axis.z;
  96143. this.ax3 = this.limitMotor3.axis.x;
  96144. this.ay3 = this.limitMotor3.axis.y;
  96145. this.az3 = this.limitMotor3.axis.z;
  96146. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96147. this.upperLimit1 = this.limitMotor1.upperLimit;
  96148. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96149. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96150. this.enableMotor1 = this.maxMotorForce1 > 0;
  96151. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96152. this.upperLimit2 = this.limitMotor2.upperLimit;
  96153. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96154. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96155. this.enableMotor2 = this.maxMotorForce2 > 0;
  96156. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96157. this.upperLimit3 = this.limitMotor3.upperLimit;
  96158. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96159. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96160. this.enableMotor3 = this.maxMotorForce3 > 0;
  96161. var ti1 = this.i1.elements;
  96162. var ti2 = this.i2.elements;
  96163. this.i1e00 = ti1[0];
  96164. this.i1e01 = ti1[1];
  96165. this.i1e02 = ti1[2];
  96166. this.i1e10 = ti1[3];
  96167. this.i1e11 = ti1[4];
  96168. this.i1e12 = ti1[5];
  96169. this.i1e20 = ti1[6];
  96170. this.i1e21 = ti1[7];
  96171. this.i1e22 = ti1[8];
  96172. this.i2e00 = ti2[0];
  96173. this.i2e01 = ti2[1];
  96174. this.i2e02 = ti2[2];
  96175. this.i2e10 = ti2[3];
  96176. this.i2e11 = ti2[4];
  96177. this.i2e12 = ti2[5];
  96178. this.i2e20 = ti2[6];
  96179. this.i2e21 = ti2[7];
  96180. this.i2e22 = ti2[8];
  96181. var frequency1 = this.limitMotor1.frequency;
  96182. var frequency2 = this.limitMotor2.frequency;
  96183. var frequency3 = this.limitMotor3.frequency;
  96184. var enableSpring1 = frequency1 > 0;
  96185. var enableSpring2 = frequency2 > 0;
  96186. var enableSpring3 = frequency3 > 0;
  96187. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96188. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96189. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96190. var angle1 = this.limitMotor1.angle;
  96191. if (enableLimit1) {
  96192. if (this.lowerLimit1 == this.upperLimit1) {
  96193. if (this.limitState1 != 0) {
  96194. this.limitState1 = 0;
  96195. this.limitImpulse1 = 0;
  96196. }
  96197. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96198. } else if (angle1 < this.lowerLimit1) {
  96199. if (this.limitState1 != -1) {
  96200. this.limitState1 = -1;
  96201. this.limitImpulse1 = 0;
  96202. }
  96203. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96204. } else if (angle1 > this.upperLimit1) {
  96205. if (this.limitState1 != 1) {
  96206. this.limitState1 = 1;
  96207. this.limitImpulse1 = 0;
  96208. }
  96209. this.limitVelocity1 = this.upperLimit1 - angle1;
  96210. } else {
  96211. this.limitState1 = 2;
  96212. this.limitImpulse1 = 0;
  96213. this.limitVelocity1 = 0;
  96214. }
  96215. if (!enableSpring1) {
  96216. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96217. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96218. else this.limitVelocity1 = 0;
  96219. }
  96220. } else {
  96221. this.limitState1 = 2;
  96222. this.limitImpulse1 = 0;
  96223. }
  96224. var angle2 = this.limitMotor2.angle;
  96225. if (enableLimit2) {
  96226. if (this.lowerLimit2 == this.upperLimit2) {
  96227. if (this.limitState2 != 0) {
  96228. this.limitState2 = 0;
  96229. this.limitImpulse2 = 0;
  96230. }
  96231. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96232. } else if (angle2 < this.lowerLimit2) {
  96233. if (this.limitState2 != -1) {
  96234. this.limitState2 = -1;
  96235. this.limitImpulse2 = 0;
  96236. }
  96237. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96238. } else if (angle2 > this.upperLimit2) {
  96239. if (this.limitState2 != 1) {
  96240. this.limitState2 = 1;
  96241. this.limitImpulse2 = 0;
  96242. }
  96243. this.limitVelocity2 = this.upperLimit2 - angle2;
  96244. } else {
  96245. this.limitState2 = 2;
  96246. this.limitImpulse2 = 0;
  96247. this.limitVelocity2 = 0;
  96248. }
  96249. if (!enableSpring2) {
  96250. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96251. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96252. else this.limitVelocity2 = 0;
  96253. }
  96254. } else {
  96255. this.limitState2 = 2;
  96256. this.limitImpulse2 = 0;
  96257. }
  96258. var angle3 = this.limitMotor3.angle;
  96259. if (enableLimit3) {
  96260. if (this.lowerLimit3 == this.upperLimit3) {
  96261. if (this.limitState3 != 0) {
  96262. this.limitState3 = 0;
  96263. this.limitImpulse3 = 0;
  96264. }
  96265. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96266. } else if (angle3 < this.lowerLimit3) {
  96267. if (this.limitState3 != -1) {
  96268. this.limitState3 = -1;
  96269. this.limitImpulse3 = 0;
  96270. }
  96271. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96272. } else if (angle3 > this.upperLimit3) {
  96273. if (this.limitState3 != 1) {
  96274. this.limitState3 = 1;
  96275. this.limitImpulse3 = 0;
  96276. }
  96277. this.limitVelocity3 = this.upperLimit3 - angle3;
  96278. } else {
  96279. this.limitState3 = 2;
  96280. this.limitImpulse3 = 0;
  96281. this.limitVelocity3 = 0;
  96282. }
  96283. if (!enableSpring3) {
  96284. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96285. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96286. else this.limitVelocity3 = 0;
  96287. }
  96288. } else {
  96289. this.limitState3 = 2;
  96290. this.limitImpulse3 = 0;
  96291. }
  96292. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96293. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96294. } else {
  96295. this.motorImpulse1 = 0;
  96296. this.maxMotorImpulse1 = 0;
  96297. }
  96298. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96299. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96300. } else {
  96301. this.motorImpulse2 = 0;
  96302. this.maxMotorImpulse2 = 0;
  96303. }
  96304. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96305. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96306. } else {
  96307. this.motorImpulse3 = 0;
  96308. this.maxMotorImpulse3 = 0;
  96309. }
  96310. // build jacobians
  96311. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96312. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96313. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96314. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96315. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96316. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96317. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96318. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96319. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96320. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96321. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96322. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96323. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96324. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96325. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96326. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96327. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96328. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96329. // build an impulse matrix
  96330. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96331. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96332. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96333. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96334. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96335. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96336. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96337. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96338. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96339. this.kv00 = this.k00;
  96340. this.kv11 = this.k11;
  96341. this.kv22 = this.k22;
  96342. this.dv00 = 1 / this.kv00;
  96343. this.dv11 = 1 / this.kv11;
  96344. this.dv22 = 1 / this.kv22;
  96345. if (enableSpring1 && this.limitState1 != 2) {
  96346. var omega = 6.2831853 * frequency1;
  96347. var k = omega * omega * timeStep;
  96348. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96349. this.cfm1 = this.kv00 * dmp;
  96350. this.limitVelocity1 *= k * dmp;
  96351. } else {
  96352. this.cfm1 = 0;
  96353. this.limitVelocity1 *= invTimeStep * 0.05;
  96354. }
  96355. if (enableSpring2 && this.limitState2 != 2) {
  96356. omega = 6.2831853 * frequency2;
  96357. k = omega * omega * timeStep;
  96358. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96359. this.cfm2 = this.kv11 * dmp;
  96360. this.limitVelocity2 *= k * dmp;
  96361. } else {
  96362. this.cfm2 = 0;
  96363. this.limitVelocity2 *= invTimeStep * 0.05;
  96364. }
  96365. if (enableSpring3 && this.limitState3 != 2) {
  96366. omega = 6.2831853 * frequency3;
  96367. k = omega * omega * timeStep;
  96368. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96369. this.cfm3 = this.kv22 * dmp;
  96370. this.limitVelocity3 *= k * dmp;
  96371. } else {
  96372. this.cfm3 = 0;
  96373. this.limitVelocity3 *= invTimeStep * 0.05;
  96374. }
  96375. this.k00 += this.cfm1;
  96376. this.k11 += this.cfm2;
  96377. this.k22 += this.cfm3;
  96378. var inv = 1 / (
  96379. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96380. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96381. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96382. );
  96383. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96384. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96385. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96386. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96387. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96388. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96389. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96390. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96391. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96392. this.limitImpulse1 *= 0.95;
  96393. this.motorImpulse1 *= 0.95;
  96394. this.limitImpulse2 *= 0.95;
  96395. this.motorImpulse2 *= 0.95;
  96396. this.limitImpulse3 *= 0.95;
  96397. this.motorImpulse3 *= 0.95;
  96398. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96399. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96400. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96401. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96402. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96403. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96404. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96405. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96406. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96407. },
  96408. solve_: function () {
  96409. var rvx = this.a2.x - this.a1.x;
  96410. var rvy = this.a2.y - this.a1.y;
  96411. var rvz = this.a2.z - this.a1.z;
  96412. this.limitVelocity3 = 30;
  96413. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96414. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96415. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96416. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96417. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96418. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96419. this.limitImpulse1 += dLimitImpulse1;
  96420. this.limitImpulse2 += dLimitImpulse2;
  96421. this.limitImpulse3 += dLimitImpulse3;
  96422. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96423. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96424. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96425. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96426. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96427. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96428. },
  96429. solve: function () {
  96430. var rvx = this.a2.x - this.a1.x;
  96431. var rvy = this.a2.y - this.a1.y;
  96432. var rvz = this.a2.z - this.a1.z;
  96433. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96434. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96435. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96436. var oldMotorImpulse1 = this.motorImpulse1;
  96437. var oldMotorImpulse2 = this.motorImpulse2;
  96438. var oldMotorImpulse3 = this.motorImpulse3;
  96439. var dMotorImpulse1 = 0;
  96440. var dMotorImpulse2 = 0;
  96441. var dMotorImpulse3 = 0;
  96442. if (this.enableMotor1) {
  96443. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96444. this.motorImpulse1 += dMotorImpulse1;
  96445. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96446. this.motorImpulse1 = this.maxMotorImpulse1;
  96447. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96448. this.motorImpulse1 = -this.maxMotorImpulse1;
  96449. }
  96450. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96451. }
  96452. if (this.enableMotor2) {
  96453. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96454. this.motorImpulse2 += dMotorImpulse2;
  96455. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96456. this.motorImpulse2 = this.maxMotorImpulse2;
  96457. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96458. this.motorImpulse2 = -this.maxMotorImpulse2;
  96459. }
  96460. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96461. }
  96462. if (this.enableMotor3) {
  96463. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96464. this.motorImpulse3 += dMotorImpulse3;
  96465. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96466. this.motorImpulse3 = this.maxMotorImpulse3;
  96467. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96468. this.motorImpulse3 = -this.maxMotorImpulse3;
  96469. }
  96470. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96471. }
  96472. // apply motor impulse to relative velocity
  96473. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96474. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96475. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96476. // subtract target velocity and applied impulse
  96477. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96478. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96479. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96480. var oldLimitImpulse1 = this.limitImpulse1;
  96481. var oldLimitImpulse2 = this.limitImpulse2;
  96482. var oldLimitImpulse3 = this.limitImpulse3;
  96483. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96484. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96485. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96486. this.limitImpulse1 += dLimitImpulse1;
  96487. this.limitImpulse2 += dLimitImpulse2;
  96488. this.limitImpulse3 += dLimitImpulse3;
  96489. // clamp
  96490. var clampState = 0;
  96491. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96492. dLimitImpulse1 = -oldLimitImpulse1;
  96493. rvn2 += dLimitImpulse1 * this.k10;
  96494. rvn3 += dLimitImpulse1 * this.k20;
  96495. clampState |= 1;
  96496. }
  96497. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96498. dLimitImpulse2 = -oldLimitImpulse2;
  96499. rvn1 += dLimitImpulse2 * this.k01;
  96500. rvn3 += dLimitImpulse2 * this.k21;
  96501. clampState |= 2;
  96502. }
  96503. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96504. dLimitImpulse3 = -oldLimitImpulse3;
  96505. rvn1 += dLimitImpulse3 * this.k02;
  96506. rvn2 += dLimitImpulse3 * this.k12;
  96507. clampState |= 4;
  96508. }
  96509. // update un-clamped impulse
  96510. // TODO: isolate division
  96511. var det;
  96512. switch (clampState) {
  96513. case 1: // update 2 3
  96514. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96515. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96516. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96517. break;
  96518. case 2: // update 1 3
  96519. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96520. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96521. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96522. break;
  96523. case 3: // update 3
  96524. dLimitImpulse3 = rvn3 / this.k22;
  96525. break;
  96526. case 4: // update 1 2
  96527. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96528. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96529. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96530. break;
  96531. case 5: // update 2
  96532. dLimitImpulse2 = rvn2 / this.k11;
  96533. break;
  96534. case 6: // update 1
  96535. dLimitImpulse1 = rvn1 / this.k00;
  96536. break;
  96537. }
  96538. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96539. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96540. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96541. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96542. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96543. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96544. // apply impulse
  96545. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96546. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96547. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96548. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96549. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96550. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96551. rvx = this.a2.x - this.a1.x;
  96552. rvy = this.a2.y - this.a1.y;
  96553. rvz = this.a2.z - this.a1.z;
  96554. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96555. }
  96556. }
  96557. /**
  96558. * A rotational constraint for various joints.
  96559. * @author saharan
  96560. */
  96561. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96562. this.cfm = NaN;
  96563. this.i1e00 = NaN;
  96564. this.i1e01 = NaN;
  96565. this.i1e02 = NaN;
  96566. this.i1e10 = NaN;
  96567. this.i1e11 = NaN;
  96568. this.i1e12 = NaN;
  96569. this.i1e20 = NaN;
  96570. this.i1e21 = NaN;
  96571. this.i1e22 = NaN;
  96572. this.i2e00 = NaN;
  96573. this.i2e01 = NaN;
  96574. this.i2e02 = NaN;
  96575. this.i2e10 = NaN;
  96576. this.i2e11 = NaN;
  96577. this.i2e12 = NaN;
  96578. this.i2e20 = NaN;
  96579. this.i2e21 = NaN;
  96580. this.i2e22 = NaN;
  96581. this.motorDenom = NaN;
  96582. this.invMotorDenom = NaN;
  96583. this.invDenom = NaN;
  96584. this.ax = NaN;
  96585. this.ay = NaN;
  96586. this.az = NaN;
  96587. this.a1x = NaN;
  96588. this.a1y = NaN;
  96589. this.a1z = NaN;
  96590. this.a2x = NaN;
  96591. this.a2y = NaN;
  96592. this.a2z = NaN;
  96593. this.enableLimit = false;
  96594. this.lowerLimit = NaN;
  96595. this.upperLimit = NaN;
  96596. this.limitVelocity = NaN;
  96597. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96598. this.enableMotor = false;
  96599. this.motorSpeed = NaN;
  96600. this.maxMotorForce = NaN;
  96601. this.maxMotorImpulse = NaN;
  96602. this.limitMotor = limitMotor;
  96603. this.b1 = joint.body1;
  96604. this.b2 = joint.body2;
  96605. this.a1 = this.b1.angularVelocity;
  96606. this.a2 = this.b2.angularVelocity;
  96607. this.i1 = this.b1.inverseInertia;
  96608. this.i2 = this.b2.inverseInertia;
  96609. this.limitImpulse = 0;
  96610. this.motorImpulse = 0;
  96611. }
  96612. OIMO.RotationalConstraint.prototype = {
  96613. constructor: OIMO.RotationalConstraint,
  96614. preSolve: function (timeStep, invTimeStep) {
  96615. this.ax = this.limitMotor.axis.x;
  96616. this.ay = this.limitMotor.axis.y;
  96617. this.az = this.limitMotor.axis.z;
  96618. this.lowerLimit = this.limitMotor.lowerLimit;
  96619. this.upperLimit = this.limitMotor.upperLimit;
  96620. this.motorSpeed = this.limitMotor.motorSpeed;
  96621. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96622. this.enableMotor = this.maxMotorForce > 0;
  96623. var ti1 = this.i1.elements;
  96624. var ti2 = this.i2.elements;
  96625. this.i1e00 = ti1[0];
  96626. this.i1e01 = ti1[1];
  96627. this.i1e02 = ti1[2];
  96628. this.i1e10 = ti1[3];
  96629. this.i1e11 = ti1[4];
  96630. this.i1e12 = ti1[5];
  96631. this.i1e20 = ti1[6];
  96632. this.i1e21 = ti1[7];
  96633. this.i1e22 = ti1[8];
  96634. this.i2e00 = ti2[0];
  96635. this.i2e01 = ti2[1];
  96636. this.i2e02 = ti2[2];
  96637. this.i2e10 = ti2[3];
  96638. this.i2e11 = ti2[4];
  96639. this.i2e12 = ti2[5];
  96640. this.i2e20 = ti2[6];
  96641. this.i2e21 = ti2[7];
  96642. this.i2e22 = ti2[8];
  96643. var frequency = this.limitMotor.frequency;
  96644. var enableSpring = frequency > 0;
  96645. var enableLimit = this.lowerLimit <= this.upperLimit;
  96646. var angle = this.limitMotor.angle;
  96647. if (enableLimit) {
  96648. if (this.lowerLimit == this.upperLimit) {
  96649. if (this.limitState != 0) {
  96650. this.limitState = 0;
  96651. this.limitImpulse = 0;
  96652. }
  96653. this.limitVelocity = this.lowerLimit - angle;
  96654. } else if (angle < this.lowerLimit) {
  96655. if (this.limitState != -1) {
  96656. this.limitState = -1;
  96657. this.limitImpulse = 0;
  96658. }
  96659. this.limitVelocity = this.lowerLimit - angle;
  96660. } else if (angle > this.upperLimit) {
  96661. if (this.limitState != 1) {
  96662. this.limitState = 1;
  96663. this.limitImpulse = 0;
  96664. }
  96665. this.limitVelocity = this.upperLimit - angle;
  96666. } else {
  96667. this.limitState = 2;
  96668. this.limitImpulse = 0;
  96669. this.limitVelocity = 0;
  96670. }
  96671. if (!enableSpring) {
  96672. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96673. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96674. else this.limitVelocity = 0;
  96675. }
  96676. } else {
  96677. this.limitState = 2;
  96678. this.limitImpulse = 0;
  96679. }
  96680. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96681. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96682. } else {
  96683. this.motorImpulse = 0;
  96684. this.maxMotorImpulse = 0;
  96685. }
  96686. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96687. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96688. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96689. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96690. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96691. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96692. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96693. this.invMotorDenom = 1 / this.motorDenom;
  96694. if (enableSpring && this.limitState != 2) {
  96695. var omega = 6.2831853 * frequency;
  96696. var k = omega * omega * timeStep;
  96697. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96698. this.cfm = this.motorDenom * dmp;
  96699. this.limitVelocity *= k * dmp;
  96700. } else {
  96701. this.cfm = 0;
  96702. this.limitVelocity *= invTimeStep * 0.05;
  96703. }
  96704. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96705. this.limitImpulse *= 0.95;
  96706. this.motorImpulse *= 0.95;
  96707. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96708. this.a1.x += totalImpulse * this.a1x;
  96709. this.a1.y += totalImpulse * this.a1y;
  96710. this.a1.z += totalImpulse * this.a1z;
  96711. this.a2.x -= totalImpulse * this.a2x;
  96712. this.a2.y -= totalImpulse * this.a2y;
  96713. this.a2.z -= totalImpulse * this.a2z;
  96714. },
  96715. solve: function () {
  96716. 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);
  96717. // motor part
  96718. var newMotorImpulse;
  96719. if (this.enableMotor) {
  96720. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96721. var oldMotorImpulse = this.motorImpulse;
  96722. this.motorImpulse += newMotorImpulse;
  96723. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96724. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96725. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96726. rvn -= newMotorImpulse * this.motorDenom;
  96727. } else newMotorImpulse = 0;
  96728. // limit part
  96729. var newLimitImpulse;
  96730. if (this.limitState != 2) {
  96731. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96732. var oldLimitImpulse = this.limitImpulse;
  96733. this.limitImpulse += newLimitImpulse;
  96734. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96735. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96736. } else newLimitImpulse = 0;
  96737. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96738. this.a1.x += totalImpulse * this.a1x;
  96739. this.a1.y += totalImpulse * this.a1y;
  96740. this.a1.z += totalImpulse * this.a1z;
  96741. this.a2.x -= totalImpulse * this.a2x;
  96742. this.a2.y -= totalImpulse * this.a2y;
  96743. this.a2.z -= totalImpulse * this.a2z;
  96744. }
  96745. }
  96746. /**
  96747. * A three-axis translational constraint for various joints.
  96748. * @author saharan
  96749. */
  96750. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96751. this.m1 = NaN;
  96752. this.m2 = NaN;
  96753. this.i1e00 = NaN;
  96754. this.i1e01 = NaN;
  96755. this.i1e02 = NaN;
  96756. this.i1e10 = NaN;
  96757. this.i1e11 = NaN;
  96758. this.i1e12 = NaN;
  96759. this.i1e20 = NaN;
  96760. this.i1e21 = NaN;
  96761. this.i1e22 = NaN;
  96762. this.i2e00 = NaN;
  96763. this.i2e01 = NaN;
  96764. this.i2e02 = NaN;
  96765. this.i2e10 = NaN;
  96766. this.i2e11 = NaN;
  96767. this.i2e12 = NaN;
  96768. this.i2e20 = NaN;
  96769. this.i2e21 = NaN;
  96770. this.i2e22 = NaN;
  96771. this.ax1 = NaN;
  96772. this.ay1 = NaN;
  96773. this.az1 = NaN;
  96774. this.ax2 = NaN;
  96775. this.ay2 = NaN;
  96776. this.az2 = NaN;
  96777. this.ax3 = NaN;
  96778. this.ay3 = NaN;
  96779. this.az3 = NaN;
  96780. this.r1x = NaN;
  96781. this.r1y = NaN;
  96782. this.r1z = NaN;
  96783. this.r2x = NaN;
  96784. this.r2y = NaN;
  96785. this.r2z = NaN;
  96786. this.t1x1 = NaN;// jacobians
  96787. this.t1y1 = NaN;
  96788. this.t1z1 = NaN;
  96789. this.t2x1 = NaN;
  96790. this.t2y1 = NaN;
  96791. this.t2z1 = NaN;
  96792. this.l1x1 = NaN;
  96793. this.l1y1 = NaN;
  96794. this.l1z1 = NaN;
  96795. this.l2x1 = NaN;
  96796. this.l2y1 = NaN;
  96797. this.l2z1 = NaN;
  96798. this.a1x1 = NaN;
  96799. this.a1y1 = NaN;
  96800. this.a1z1 = NaN;
  96801. this.a2x1 = NaN;
  96802. this.a2y1 = NaN;
  96803. this.a2z1 = NaN;
  96804. this.t1x2 = NaN;
  96805. this.t1y2 = NaN;
  96806. this.t1z2 = NaN;
  96807. this.t2x2 = NaN;
  96808. this.t2y2 = NaN;
  96809. this.t2z2 = NaN;
  96810. this.l1x2 = NaN;
  96811. this.l1y2 = NaN;
  96812. this.l1z2 = NaN;
  96813. this.l2x2 = NaN;
  96814. this.l2y2 = NaN;
  96815. this.l2z2 = NaN;
  96816. this.a1x2 = NaN;
  96817. this.a1y2 = NaN;
  96818. this.a1z2 = NaN;
  96819. this.a2x2 = NaN;
  96820. this.a2y2 = NaN;
  96821. this.a2z2 = NaN;
  96822. this.t1x3 = NaN;
  96823. this.t1y3 = NaN;
  96824. this.t1z3 = NaN;
  96825. this.t2x3 = NaN;
  96826. this.t2y3 = NaN;
  96827. this.t2z3 = NaN;
  96828. this.l1x3 = NaN;
  96829. this.l1y3 = NaN;
  96830. this.l1z3 = NaN;
  96831. this.l2x3 = NaN;
  96832. this.l2y3 = NaN;
  96833. this.l2z3 = NaN;
  96834. this.a1x3 = NaN;
  96835. this.a1y3 = NaN;
  96836. this.a1z3 = NaN;
  96837. this.a2x3 = NaN;
  96838. this.a2y3 = NaN;
  96839. this.a2z3 = NaN;
  96840. this.lowerLimit1 = NaN;
  96841. this.upperLimit1 = NaN;
  96842. this.limitVelocity1 = NaN;
  96843. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96844. this.enableMotor1 = false;
  96845. this.motorSpeed1 = NaN;
  96846. this.maxMotorForce1 = NaN;
  96847. this.maxMotorImpulse1 = NaN;
  96848. this.lowerLimit2 = NaN;
  96849. this.upperLimit2 = NaN;
  96850. this.limitVelocity2 = NaN;
  96851. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96852. this.enableMotor2 = false;
  96853. this.motorSpeed2 = NaN;
  96854. this.maxMotorForce2 = NaN;
  96855. this.maxMotorImpulse2 = NaN;
  96856. this.lowerLimit3 = NaN;
  96857. this.upperLimit3 = NaN;
  96858. this.limitVelocity3 = NaN;
  96859. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96860. this.enableMotor3 = false;
  96861. this.motorSpeed3 = NaN;
  96862. this.maxMotorForce3 = NaN;
  96863. this.maxMotorImpulse3 = NaN;
  96864. this.k00 = NaN; // K = J*M*JT
  96865. this.k01 = NaN;
  96866. this.k02 = NaN;
  96867. this.k10 = NaN;
  96868. this.k11 = NaN;
  96869. this.k12 = NaN;
  96870. this.k20 = NaN;
  96871. this.k21 = NaN;
  96872. this.k22 = NaN;
  96873. this.kv00 = NaN; // diagonals without CFMs
  96874. this.kv11 = NaN;
  96875. this.kv22 = NaN;
  96876. this.dv00 = NaN; // ...inverted
  96877. this.dv11 = NaN;
  96878. this.dv22 = NaN;
  96879. this.d00 = NaN; // K^-1
  96880. this.d01 = NaN;
  96881. this.d02 = NaN;
  96882. this.d10 = NaN;
  96883. this.d11 = NaN;
  96884. this.d12 = NaN;
  96885. this.d20 = NaN;
  96886. this.d21 = NaN;
  96887. this.d22 = NaN;
  96888. this.limitMotor1 = limitMotor1;
  96889. this.limitMotor2 = limitMotor2;
  96890. this.limitMotor3 = limitMotor3;
  96891. this.b1 = joint.body1;
  96892. this.b2 = joint.body2;
  96893. this.p1 = joint.anchorPoint1;
  96894. this.p2 = joint.anchorPoint2;
  96895. this.r1 = joint.relativeAnchorPoint1;
  96896. this.r2 = joint.relativeAnchorPoint2;
  96897. this.l1 = this.b1.linearVelocity;
  96898. this.l2 = this.b2.linearVelocity;
  96899. this.a1 = this.b1.angularVelocity;
  96900. this.a2 = this.b2.angularVelocity;
  96901. this.i1 = this.b1.inverseInertia;
  96902. this.i2 = this.b2.inverseInertia;
  96903. this.limitImpulse1 = 0;
  96904. this.motorImpulse1 = 0;
  96905. this.limitImpulse2 = 0;
  96906. this.motorImpulse2 = 0;
  96907. this.limitImpulse3 = 0;
  96908. this.motorImpulse3 = 0;
  96909. this.cfm1 = 0;// Constraint Force Mixing
  96910. this.cfm2 = 0;
  96911. this.cfm3 = 0;
  96912. this.weight = -1;
  96913. }
  96914. OIMO.Translational3Constraint.prototype = {
  96915. constructor: OIMO.Translational3Constraint,
  96916. preSolve: function (timeStep, invTimeStep) {
  96917. this.ax1 = this.limitMotor1.axis.x;
  96918. this.ay1 = this.limitMotor1.axis.y;
  96919. this.az1 = this.limitMotor1.axis.z;
  96920. this.ax2 = this.limitMotor2.axis.x;
  96921. this.ay2 = this.limitMotor2.axis.y;
  96922. this.az2 = this.limitMotor2.axis.z;
  96923. this.ax3 = this.limitMotor3.axis.x;
  96924. this.ay3 = this.limitMotor3.axis.y;
  96925. this.az3 = this.limitMotor3.axis.z;
  96926. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96927. this.upperLimit1 = this.limitMotor1.upperLimit;
  96928. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96929. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96930. this.enableMotor1 = this.maxMotorForce1 > 0;
  96931. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96932. this.upperLimit2 = this.limitMotor2.upperLimit;
  96933. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96934. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96935. this.enableMotor2 = this.maxMotorForce2 > 0;
  96936. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96937. this.upperLimit3 = this.limitMotor3.upperLimit;
  96938. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96939. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96940. this.enableMotor3 = this.maxMotorForce3 > 0;
  96941. this.m1 = this.b1.inverseMass;
  96942. this.m2 = this.b2.inverseMass;
  96943. var ti1 = this.i1.elements;
  96944. var ti2 = this.i2.elements;
  96945. this.i1e00 = ti1[0];
  96946. this.i1e01 = ti1[1];
  96947. this.i1e02 = ti1[2];
  96948. this.i1e10 = ti1[3];
  96949. this.i1e11 = ti1[4];
  96950. this.i1e12 = ti1[5];
  96951. this.i1e20 = ti1[6];
  96952. this.i1e21 = ti1[7];
  96953. this.i1e22 = ti1[8];
  96954. this.i2e00 = ti2[0];
  96955. this.i2e01 = ti2[1];
  96956. this.i2e02 = ti2[2];
  96957. this.i2e10 = ti2[3];
  96958. this.i2e11 = ti2[4];
  96959. this.i2e12 = ti2[5];
  96960. this.i2e20 = ti2[6];
  96961. this.i2e21 = ti2[7];
  96962. this.i2e22 = ti2[8];
  96963. var dx = this.p2.x - this.p1.x;
  96964. var dy = this.p2.y - this.p1.y;
  96965. var dz = this.p2.z - this.p1.z;
  96966. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  96967. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  96968. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  96969. var frequency1 = this.limitMotor1.frequency;
  96970. var frequency2 = this.limitMotor2.frequency;
  96971. var frequency3 = this.limitMotor3.frequency;
  96972. var enableSpring1 = frequency1 > 0;
  96973. var enableSpring2 = frequency2 > 0;
  96974. var enableSpring3 = frequency3 > 0;
  96975. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96976. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96977. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96978. // for stability
  96979. if (enableSpring1 && d1 > 20 || d1 < -20) {
  96980. enableSpring1 = false;
  96981. }
  96982. if (enableSpring2 && d2 > 20 || d2 < -20) {
  96983. enableSpring2 = false;
  96984. }
  96985. if (enableSpring3 && d3 > 20 || d3 < -20) {
  96986. enableSpring3 = false;
  96987. }
  96988. if (enableLimit1) {
  96989. if (this.lowerLimit1 == this.upperLimit1) {
  96990. if (this.limitState1 != 0) {
  96991. this.limitState1 = 0;
  96992. this.limitImpulse1 = 0;
  96993. }
  96994. this.limitVelocity1 = this.lowerLimit1 - d1;
  96995. if (!enableSpring1) d1 = this.lowerLimit1;
  96996. } else if (d1 < this.lowerLimit1) {
  96997. if (this.limitState1 != -1) {
  96998. this.limitState1 = -1;
  96999. this.limitImpulse1 = 0;
  97000. }
  97001. this.limitVelocity1 = this.lowerLimit1 - d1;
  97002. if (!enableSpring1) d1 = this.lowerLimit1;
  97003. } else if (d1 > this.upperLimit1) {
  97004. if (this.limitState1 != 1) {
  97005. this.limitState1 = 1;
  97006. this.limitImpulse1 = 0;
  97007. }
  97008. this.limitVelocity1 = this.upperLimit1 - d1;
  97009. if (!enableSpring1) d1 = this.upperLimit1;
  97010. } else {
  97011. this.limitState1 = 2;
  97012. this.limitImpulse1 = 0;
  97013. this.limitVelocity1 = 0;
  97014. }
  97015. if (!enableSpring1) {
  97016. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97017. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97018. else this.limitVelocity1 = 0;
  97019. }
  97020. } else {
  97021. this.limitState1 = 2;
  97022. this.limitImpulse1 = 0;
  97023. }
  97024. if (enableLimit2) {
  97025. if (this.lowerLimit2 == this.upperLimit2) {
  97026. if (this.limitState2 != 0) {
  97027. this.limitState2 = 0;
  97028. this.limitImpulse2 = 0;
  97029. }
  97030. this.limitVelocity2 = this.lowerLimit2 - d2;
  97031. if (!enableSpring2) d2 = this.lowerLimit2;
  97032. } else if (d2 < this.lowerLimit2) {
  97033. if (this.limitState2 != -1) {
  97034. this.limitState2 = -1;
  97035. this.limitImpulse2 = 0;
  97036. }
  97037. this.limitVelocity2 = this.lowerLimit2 - d2;
  97038. if (!enableSpring2) d2 = this.lowerLimit2;
  97039. } else if (d2 > this.upperLimit2) {
  97040. if (this.limitState2 != 1) {
  97041. this.limitState2 = 1;
  97042. this.limitImpulse2 = 0;
  97043. }
  97044. this.limitVelocity2 = this.upperLimit2 - d2;
  97045. if (!enableSpring2) d2 = this.upperLimit2;
  97046. } else {
  97047. this.limitState2 = 2;
  97048. this.limitImpulse2 = 0;
  97049. this.limitVelocity2 = 0;
  97050. }
  97051. if (!enableSpring2) {
  97052. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97053. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97054. else this.limitVelocity2 = 0;
  97055. }
  97056. } else {
  97057. this.limitState2 = 2;
  97058. this.limitImpulse2 = 0;
  97059. }
  97060. if (enableLimit3) {
  97061. if (this.lowerLimit3 == this.upperLimit3) {
  97062. if (this.limitState3 != 0) {
  97063. this.limitState3 = 0;
  97064. this.limitImpulse3 = 0;
  97065. }
  97066. this.limitVelocity3 = this.lowerLimit3 - d3;
  97067. if (!enableSpring3) d3 = this.lowerLimit3;
  97068. } else if (d3 < this.lowerLimit3) {
  97069. if (this.limitState3 != -1) {
  97070. this.limitState3 = -1;
  97071. this.limitImpulse3 = 0;
  97072. }
  97073. this.limitVelocity3 = this.lowerLimit3 - d3;
  97074. if (!enableSpring3) d3 = this.lowerLimit3;
  97075. } else if (d3 > this.upperLimit3) {
  97076. if (this.limitState3 != 1) {
  97077. this.limitState3 = 1;
  97078. this.limitImpulse3 = 0;
  97079. }
  97080. this.limitVelocity3 = this.upperLimit3 - d3;
  97081. if (!enableSpring3) d3 = this.upperLimit3;
  97082. } else {
  97083. this.limitState3 = 2;
  97084. this.limitImpulse3 = 0;
  97085. this.limitVelocity3 = 0;
  97086. }
  97087. if (!enableSpring3) {
  97088. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97089. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97090. else this.limitVelocity3 = 0;
  97091. }
  97092. } else {
  97093. this.limitState3 = 2;
  97094. this.limitImpulse3 = 0;
  97095. }
  97096. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97097. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97098. } else {
  97099. this.motorImpulse1 = 0;
  97100. this.maxMotorImpulse1 = 0;
  97101. }
  97102. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97103. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97104. } else {
  97105. this.motorImpulse2 = 0;
  97106. this.maxMotorImpulse2 = 0;
  97107. }
  97108. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97109. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97110. } else {
  97111. this.motorImpulse3 = 0;
  97112. this.maxMotorImpulse3 = 0;
  97113. }
  97114. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97115. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97116. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97117. var w1 = this.m2 / (this.m1 + this.m2);
  97118. if (this.weight >= 0) w1 = this.weight; // use given weight
  97119. var w2 = 1 - w1;
  97120. this.r1x = this.r1.x + rdx * w1;
  97121. this.r1y = this.r1.y + rdy * w1;
  97122. this.r1z = this.r1.z + rdz * w1;
  97123. this.r2x = this.r2.x - rdx * w2;
  97124. this.r2y = this.r2.y - rdy * w2;
  97125. this.r2z = this.r2.z - rdz * w2;
  97126. // build jacobians
  97127. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97128. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97129. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97130. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97131. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97132. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97133. this.l1x1 = this.ax1 * this.m1;
  97134. this.l1y1 = this.ay1 * this.m1;
  97135. this.l1z1 = this.az1 * this.m1;
  97136. this.l2x1 = this.ax1 * this.m2;
  97137. this.l2y1 = this.ay1 * this.m2;
  97138. this.l2z1 = this.az1 * this.m2;
  97139. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97140. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97141. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97142. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97143. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97144. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97145. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97146. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97147. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97148. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97149. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97150. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97151. this.l1x2 = this.ax2 * this.m1;
  97152. this.l1y2 = this.ay2 * this.m1;
  97153. this.l1z2 = this.az2 * this.m1;
  97154. this.l2x2 = this.ax2 * this.m2;
  97155. this.l2y2 = this.ay2 * this.m2;
  97156. this.l2z2 = this.az2 * this.m2;
  97157. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97158. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97159. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97160. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97161. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97162. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97163. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97164. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97165. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97166. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97167. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97168. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97169. this.l1x3 = this.ax3 * this.m1;
  97170. this.l1y3 = this.ay3 * this.m1;
  97171. this.l1z3 = this.az3 * this.m1;
  97172. this.l2x3 = this.ax3 * this.m2;
  97173. this.l2y3 = this.ay3 * this.m2;
  97174. this.l2z3 = this.az3 * this.m2;
  97175. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97176. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97177. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97178. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97179. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97180. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97181. // build an impulse matrix
  97182. var m12 = this.m1 + this.m2;
  97183. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97184. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97185. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97186. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97187. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97188. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97189. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97190. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97191. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97192. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97193. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97194. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97195. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97196. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97197. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97198. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97199. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97200. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97201. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97202. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97203. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97204. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97205. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97206. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97207. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97208. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97209. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97210. this.kv00 = this.k00;
  97211. this.kv11 = this.k11;
  97212. this.kv22 = this.k22;
  97213. this.dv00 = 1 / this.kv00;
  97214. this.dv11 = 1 / this.kv11;
  97215. this.dv22 = 1 / this.kv22;
  97216. if (enableSpring1 && this.limitState1 != 2) {
  97217. var omega = 6.2831853 * frequency1;
  97218. var k = omega * omega * timeStep;
  97219. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97220. this.cfm1 = this.kv00 * dmp;
  97221. this.limitVelocity1 *= k * dmp;
  97222. } else {
  97223. this.cfm1 = 0;
  97224. this.limitVelocity1 *= invTimeStep * 0.05;
  97225. }
  97226. if (enableSpring2 && this.limitState2 != 2) {
  97227. omega = 6.2831853 * frequency2;
  97228. k = omega * omega * timeStep;
  97229. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97230. this.cfm2 = this.kv11 * dmp;
  97231. this.limitVelocity2 *= k * dmp;
  97232. } else {
  97233. this.cfm2 = 0;
  97234. this.limitVelocity2 *= invTimeStep * 0.05;
  97235. }
  97236. if (enableSpring3 && this.limitState3 != 2) {
  97237. omega = 6.2831853 * frequency3;
  97238. k = omega * omega * timeStep;
  97239. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97240. this.cfm3 = this.kv22 * dmp;
  97241. this.limitVelocity3 *= k * dmp;
  97242. } else {
  97243. this.cfm3 = 0;
  97244. this.limitVelocity3 *= invTimeStep * 0.05;
  97245. }
  97246. this.k00 += this.cfm1;
  97247. this.k11 += this.cfm2;
  97248. this.k22 += this.cfm3;
  97249. var inv = 1 / (
  97250. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97251. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97252. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97253. );
  97254. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97255. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97256. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97257. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97258. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97259. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97260. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97261. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97262. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97263. // warm starting
  97264. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97265. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97266. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97267. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97268. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97269. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97270. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97271. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97272. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97273. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97274. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97275. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97276. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97277. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97278. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97279. },
  97280. solve: function () {
  97281. 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;
  97282. 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;
  97283. 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;
  97284. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97285. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97286. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97287. var oldMotorImpulse1 = this.motorImpulse1;
  97288. var oldMotorImpulse2 = this.motorImpulse2;
  97289. var oldMotorImpulse3 = this.motorImpulse3;
  97290. var dMotorImpulse1 = 0;
  97291. var dMotorImpulse2 = 0;
  97292. var dMotorImpulse3 = 0;
  97293. if (this.enableMotor1) {
  97294. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97295. this.motorImpulse1 += dMotorImpulse1;
  97296. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97297. this.motorImpulse1 = this.maxMotorImpulse1;
  97298. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97299. this.motorImpulse1 = -this.maxMotorImpulse1;
  97300. }
  97301. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97302. }
  97303. if (this.enableMotor2) {
  97304. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97305. this.motorImpulse2 += dMotorImpulse2;
  97306. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97307. this.motorImpulse2 = this.maxMotorImpulse2;
  97308. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97309. this.motorImpulse2 = -this.maxMotorImpulse2;
  97310. }
  97311. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97312. }
  97313. if (this.enableMotor3) {
  97314. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97315. this.motorImpulse3 += dMotorImpulse3;
  97316. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97317. this.motorImpulse3 = this.maxMotorImpulse3;
  97318. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97319. this.motorImpulse3 = -this.maxMotorImpulse3;
  97320. }
  97321. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97322. }
  97323. // apply motor impulse to relative velocity
  97324. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97325. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97326. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97327. // subtract target velocity and applied impulse
  97328. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97329. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97330. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97331. var oldLimitImpulse1 = this.limitImpulse1;
  97332. var oldLimitImpulse2 = this.limitImpulse2;
  97333. var oldLimitImpulse3 = this.limitImpulse3;
  97334. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97335. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97336. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97337. this.limitImpulse1 += dLimitImpulse1;
  97338. this.limitImpulse2 += dLimitImpulse2;
  97339. this.limitImpulse3 += dLimitImpulse3;
  97340. // clamp
  97341. var clampState = 0;
  97342. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97343. dLimitImpulse1 = -oldLimitImpulse1;
  97344. rvn2 += dLimitImpulse1 * this.k10;
  97345. rvn3 += dLimitImpulse1 * this.k20;
  97346. clampState |= 1;
  97347. }
  97348. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97349. dLimitImpulse2 = -oldLimitImpulse2;
  97350. rvn1 += dLimitImpulse2 * this.k01;
  97351. rvn3 += dLimitImpulse2 * this.k21;
  97352. clampState |= 2;
  97353. }
  97354. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97355. dLimitImpulse3 = -oldLimitImpulse3;
  97356. rvn1 += dLimitImpulse3 * this.k02;
  97357. rvn2 += dLimitImpulse3 * this.k12;
  97358. clampState |= 4;
  97359. }
  97360. // update un-clamped impulse
  97361. // TODO: isolate division
  97362. var det;
  97363. switch (clampState) {
  97364. case 1:// update 2 3
  97365. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97366. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97367. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97368. break;
  97369. case 2:// update 1 3
  97370. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97371. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97372. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97373. break;
  97374. case 3:// update 3
  97375. dLimitImpulse3 = rvn3 / this.k22;
  97376. break;
  97377. case 4:// update 1 2
  97378. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97379. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97380. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97381. break;
  97382. case 5:// update 2
  97383. dLimitImpulse2 = rvn2 / this.k11;
  97384. break;
  97385. case 6:// update 1
  97386. dLimitImpulse1 = rvn1 / this.k00;
  97387. break;
  97388. }
  97389. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97390. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97391. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97392. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97393. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97394. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97395. // apply impulse
  97396. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97397. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97398. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97399. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97400. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97401. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97402. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97403. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97404. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97405. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97406. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97407. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97408. }
  97409. }
  97410. /**
  97411. * A translational constraint for various joints.
  97412. * @author saharan
  97413. */
  97414. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97415. this.cfm = NaN;
  97416. this.m1 = NaN;
  97417. this.m2 = NaN;
  97418. this.i1e00 = NaN;
  97419. this.i1e01 = NaN;
  97420. this.i1e02 = NaN;
  97421. this.i1e10 = NaN;
  97422. this.i1e11 = NaN;
  97423. this.i1e12 = NaN;
  97424. this.i1e20 = NaN;
  97425. this.i1e21 = NaN;
  97426. this.i1e22 = NaN;
  97427. this.i2e00 = NaN;
  97428. this.i2e01 = NaN;
  97429. this.i2e02 = NaN;
  97430. this.i2e10 = NaN;
  97431. this.i2e11 = NaN;
  97432. this.i2e12 = NaN;
  97433. this.i2e20 = NaN;
  97434. this.i2e21 = NaN;
  97435. this.i2e22 = NaN;
  97436. this.motorDenom = NaN;
  97437. this.invMotorDenom = NaN;
  97438. this.invDenom = NaN;
  97439. this.ax = NaN;
  97440. this.ay = NaN;
  97441. this.az = NaN;
  97442. this.r1x = NaN;
  97443. this.r1y = NaN;
  97444. this.r1z = NaN;
  97445. this.r2x = NaN;
  97446. this.r2y = NaN;
  97447. this.r2z = NaN;
  97448. this.t1x = NaN;
  97449. this.t1y = NaN;
  97450. this.t1z = NaN;
  97451. this.t2x = NaN;
  97452. this.t2y = NaN;
  97453. this.t2z = NaN;
  97454. this.l1x = NaN;
  97455. this.l1y = NaN;
  97456. this.l1z = NaN;
  97457. this.l2x = NaN;
  97458. this.l2y = NaN;
  97459. this.l2z = NaN;
  97460. this.a1x = NaN;
  97461. this.a1y = NaN;
  97462. this.a1z = NaN;
  97463. this.a2x = NaN;
  97464. this.a2y = NaN;
  97465. this.a2z = NaN;
  97466. this.lowerLimit = NaN;
  97467. this.upperLimit = NaN;
  97468. this.limitVelocity = NaN;
  97469. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97470. this.enableMotor = false;
  97471. this.motorSpeed = NaN;
  97472. this.maxMotorForce = NaN;
  97473. this.maxMotorImpulse = NaN;
  97474. this.limitMotor = limitMotor;
  97475. this.b1 = joint.body1;
  97476. this.b2 = joint.body2;
  97477. this.p1 = joint.anchorPoint1;
  97478. this.p2 = joint.anchorPoint2;
  97479. this.r1 = joint.relativeAnchorPoint1;
  97480. this.r2 = joint.relativeAnchorPoint2;
  97481. this.l1 = this.b1.linearVelocity;
  97482. this.l2 = this.b2.linearVelocity;
  97483. this.a1 = this.b1.angularVelocity;
  97484. this.a2 = this.b2.angularVelocity;
  97485. this.i1 = this.b1.inverseInertia;
  97486. this.i2 = this.b2.inverseInertia;
  97487. this.limitImpulse = 0;
  97488. this.motorImpulse = 0;
  97489. }
  97490. OIMO.TranslationalConstraint.prototype = {
  97491. constructor: OIMO.TranslationalConstraint,
  97492. preSolve: function (timeStep, invTimeStep) {
  97493. this.ax = this.limitMotor.axis.x;
  97494. this.ay = this.limitMotor.axis.y;
  97495. this.az = this.limitMotor.axis.z;
  97496. this.lowerLimit = this.limitMotor.lowerLimit;
  97497. this.upperLimit = this.limitMotor.upperLimit;
  97498. this.motorSpeed = this.limitMotor.motorSpeed;
  97499. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97500. this.enableMotor = this.maxMotorForce > 0;
  97501. this.m1 = this.b1.inverseMass;
  97502. this.m2 = this.b2.inverseMass;
  97503. var ti1 = this.i1.elements;
  97504. var ti2 = this.i2.elements;
  97505. this.i1e00 = ti1[0];
  97506. this.i1e01 = ti1[1];
  97507. this.i1e02 = ti1[2];
  97508. this.i1e10 = ti1[3];
  97509. this.i1e11 = ti1[4];
  97510. this.i1e12 = ti1[5];
  97511. this.i1e20 = ti1[6];
  97512. this.i1e21 = ti1[7];
  97513. this.i1e22 = ti1[8];
  97514. this.i2e00 = ti2[0];
  97515. this.i2e01 = ti2[1];
  97516. this.i2e02 = ti2[2];
  97517. this.i2e10 = ti2[3];
  97518. this.i2e11 = ti2[4];
  97519. this.i2e12 = ti2[5];
  97520. this.i2e20 = ti2[6];
  97521. this.i2e21 = ti2[7];
  97522. this.i2e22 = ti2[8];
  97523. var dx = this.p2.x - this.p1.x;
  97524. var dy = this.p2.y - this.p1.y;
  97525. var dz = this.p2.z - this.p1.z;
  97526. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97527. var frequency = this.limitMotor.frequency;
  97528. var enableSpring = frequency > 0;
  97529. var enableLimit = this.lowerLimit <= this.upperLimit;
  97530. if (enableSpring && d > 20 || d < -20) {
  97531. enableSpring = false;
  97532. }
  97533. if (enableLimit) {
  97534. if (this.lowerLimit == this.upperLimit) {
  97535. if (this.limitState != 0) {
  97536. this.limitState = 0;
  97537. this.limitImpulse = 0;
  97538. }
  97539. this.limitVelocity = this.lowerLimit - d;
  97540. if (!enableSpring) d = this.lowerLimit;
  97541. } else if (d < this.lowerLimit) {
  97542. if (this.limitState != -1) {
  97543. this.limitState = -1;
  97544. this.limitImpulse = 0;
  97545. }
  97546. this.limitVelocity = this.lowerLimit - d;
  97547. if (!enableSpring) d = this.lowerLimit;
  97548. } else if (d > this.upperLimit) {
  97549. if (this.limitState != 1) {
  97550. this.limitState = 1;
  97551. this.limitImpulse = 0;
  97552. }
  97553. this.limitVelocity = this.upperLimit - d;
  97554. if (!enableSpring) d = this.upperLimit;
  97555. } else {
  97556. this.limitState = 2;
  97557. this.limitImpulse = 0;
  97558. this.limitVelocity = 0;
  97559. }
  97560. if (!enableSpring) {
  97561. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97562. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97563. else this.limitVelocity = 0;
  97564. }
  97565. } else {
  97566. this.limitState = 2;
  97567. this.limitImpulse = 0;
  97568. }
  97569. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97570. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97571. } else {
  97572. this.motorImpulse = 0;
  97573. this.maxMotorImpulse = 0;
  97574. }
  97575. var rdx = d * this.ax;
  97576. var rdy = d * this.ay;
  97577. var rdz = d * this.az;
  97578. var w1 = this.m1 / (this.m1 + this.m2);
  97579. var w2 = 1 - w1;
  97580. this.r1x = this.r1.x + rdx * w1;
  97581. this.r1y = this.r1.y + rdy * w1;
  97582. this.r1z = this.r1.z + rdz * w1;
  97583. this.r2x = this.r2.x - rdx * w2;
  97584. this.r2y = this.r2.y - rdy * w2;
  97585. this.r2z = this.r2.z - rdz * w2;
  97586. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97587. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97588. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97589. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97590. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97591. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97592. this.l1x = this.ax * this.m1;
  97593. this.l1y = this.ay * this.m1;
  97594. this.l1z = this.az * this.m1;
  97595. this.l2x = this.ax * this.m2;
  97596. this.l2y = this.ay * this.m2;
  97597. this.l2z = this.az * this.m2;
  97598. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97599. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97600. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97601. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97602. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97603. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97604. this.motorDenom =
  97605. this.m1 + this.m2 +
  97606. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97607. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97608. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97609. this.invMotorDenom = 1 / this.motorDenom;
  97610. if (enableSpring && this.limitState != 2) {
  97611. var omega = 6.2831853 * frequency;
  97612. var k = omega * omega * timeStep;
  97613. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97614. this.cfm = this.motorDenom * dmp;
  97615. this.limitVelocity *= k * dmp;
  97616. } else {
  97617. this.cfm = 0;
  97618. this.limitVelocity *= invTimeStep * 0.05;
  97619. }
  97620. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97621. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97622. this.l1.x += totalImpulse * this.l1x;
  97623. this.l1.y += totalImpulse * this.l1y;
  97624. this.l1.z += totalImpulse * this.l1z;
  97625. this.a1.x += totalImpulse * this.a1x;
  97626. this.a1.y += totalImpulse * this.a1y;
  97627. this.a1.z += totalImpulse * this.a1z;
  97628. this.l2.x -= totalImpulse * this.l2x;
  97629. this.l2.y -= totalImpulse * this.l2y;
  97630. this.l2.z -= totalImpulse * this.l2z;
  97631. this.a2.x -= totalImpulse * this.a2x;
  97632. this.a2.y -= totalImpulse * this.a2y;
  97633. this.a2.z -= totalImpulse * this.a2z;
  97634. },
  97635. solve: function () {
  97636. var rvn =
  97637. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97638. 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;
  97639. // motor part
  97640. var newMotorImpulse;
  97641. if (this.enableMotor) {
  97642. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97643. var oldMotorImpulse = this.motorImpulse;
  97644. this.motorImpulse += newMotorImpulse;
  97645. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97646. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97647. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97648. rvn -= newMotorImpulse * this.motorDenom;
  97649. } else newMotorImpulse = 0;
  97650. // limit part
  97651. var newLimitImpulse;
  97652. if (this.limitState != 2) {
  97653. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97654. var oldLimitImpulse = this.limitImpulse;
  97655. this.limitImpulse += newLimitImpulse;
  97656. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97657. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97658. } else newLimitImpulse = 0;
  97659. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97660. this.l1.x += totalImpulse * this.l1x;
  97661. this.l1.y += totalImpulse * this.l1y;
  97662. this.l1.z += totalImpulse * this.l1z;
  97663. this.a1.x += totalImpulse * this.a1x;
  97664. this.a1.y += totalImpulse * this.a1y;
  97665. this.a1.z += totalImpulse * this.a1z;
  97666. this.l2.x -= totalImpulse * this.l2x;
  97667. this.l2.y -= totalImpulse * this.l2y;
  97668. this.l2.z -= totalImpulse * this.l2z;
  97669. this.a2.x -= totalImpulse * this.a2x;
  97670. this.a2.y -= totalImpulse * this.a2y;
  97671. this.a2.z -= totalImpulse * this.a2z;
  97672. }
  97673. }
  97674. /**
  97675. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97676. * @author saharan
  97677. */
  97678. OIMO.Contact = function () {
  97679. // The first shape.
  97680. this.shape1 = null;
  97681. // The second shape.
  97682. this.shape2 = null;
  97683. // The first rigid body.
  97684. this.body1 = null;
  97685. // The second rigid body.
  97686. this.body2 = null;
  97687. // The previous contact in the world.
  97688. this.prev = null;
  97689. // The next contact in the world.
  97690. this.next = null;
  97691. // Internal
  97692. this.persisting = false;
  97693. // Whether both the rigid bodies are sleeping or not.
  97694. this.sleeping = false;
  97695. // The collision detector between two shapes.
  97696. this.detector = null;
  97697. // The contact constraint of the contact.
  97698. this.constraint = null;
  97699. // Whether the shapes are touching or not.
  97700. this.touching = false;
  97701. this.b1Link = new OIMO.ContactLink(this);
  97702. this.b2Link = new OIMO.ContactLink(this);
  97703. this.s1Link = new OIMO.ContactLink(this);
  97704. this.s2Link = new OIMO.ContactLink(this);
  97705. // The contact manifold of the contact.
  97706. this.manifold = new OIMO.ContactManifold();
  97707. this.buffer = [];// vector 4
  97708. this.buffer.length = 4;
  97709. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97710. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97711. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97712. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97713. this.points = this.manifold.points;
  97714. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97715. }
  97716. OIMO.Contact.prototype = {
  97717. constructor: OIMO.Contact,
  97718. mixRestitution: function (restitution1, restitution2) {
  97719. return OIMO.sqrt(restitution1 * restitution2);
  97720. },
  97721. mixFriction: function (friction1, friction2) {
  97722. return OIMO.sqrt(friction1 * friction2);
  97723. },
  97724. /**
  97725. * Update the contact manifold.
  97726. */
  97727. updateManifold: function () {
  97728. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97729. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97730. var numBuffers = this.manifold.numPoints;
  97731. var i = numBuffers;
  97732. while (i--) {
  97733. //for(var i=0;i<numBuffers;i++){
  97734. var b = this.buffer[i];
  97735. var p = this.points[i];
  97736. b.lp1X = p.localPoint1.x;
  97737. b.lp1Y = p.localPoint1.y;
  97738. b.lp1Z = p.localPoint1.z;
  97739. b.lp2X = p.localPoint2.x;
  97740. b.lp2Y = p.localPoint2.y;
  97741. b.lp2Z = p.localPoint2.z;
  97742. b.impulse = p.normalImpulse;
  97743. }
  97744. this.manifold.numPoints = 0;
  97745. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97746. var num = this.manifold.numPoints;
  97747. if (num == 0) {
  97748. this.touching = false;
  97749. return;
  97750. }
  97751. this.touching = true;
  97752. i = num;
  97753. while (i--) {
  97754. //for(i=0; i<num; i++){
  97755. p = this.points[i];
  97756. var lp1x = p.localPoint1.x;
  97757. var lp1y = p.localPoint1.y;
  97758. var lp1z = p.localPoint1.z;
  97759. var lp2x = p.localPoint2.x;
  97760. var lp2y = p.localPoint2.y;
  97761. var lp2z = p.localPoint2.z;
  97762. var index = -1;
  97763. var minDistance = 0.0004;
  97764. var j = numBuffers;
  97765. while (j--) {
  97766. //for(var j=0;j<numBuffers;j++){
  97767. b = this.buffer[j];
  97768. var dx = b.lp1X - lp1x;
  97769. var dy = b.lp1Y - lp1y;
  97770. var dz = b.lp1Z - lp1z;
  97771. var distance1 = dx * dx + dy * dy + dz * dz;
  97772. dx = b.lp2X - lp2x;
  97773. dy = b.lp2Y - lp2y;
  97774. dz = b.lp2Z - lp2z;
  97775. var distance2 = dx * dx + dy * dy + dz * dz;
  97776. if (distance1 < distance2) {
  97777. if (distance1 < minDistance) {
  97778. minDistance = distance1;
  97779. index = j;
  97780. }
  97781. } else {
  97782. if (distance2 < minDistance) {
  97783. minDistance = distance2;
  97784. index = j;
  97785. }
  97786. }
  97787. }
  97788. if (index != -1) {
  97789. var tmp = this.buffer[index];
  97790. this.buffer[index] = this.buffer[--numBuffers];
  97791. this.buffer[numBuffers] = tmp;
  97792. p.normalImpulse = tmp.impulse;
  97793. p.warmStarted = true;
  97794. } else {
  97795. p.normalImpulse = 0;
  97796. p.warmStarted = false;
  97797. }
  97798. }
  97799. },
  97800. /**
  97801. * Attach the contact to the shapes.
  97802. * @param shape1
  97803. * @param shape2
  97804. */
  97805. attach: function (shape1, shape2) {
  97806. this.shape1 = shape1;
  97807. this.shape2 = shape2;
  97808. this.body1 = shape1.parent;
  97809. this.body2 = shape2.parent;
  97810. this.manifold.body1 = this.body1;
  97811. this.manifold.body2 = this.body2;
  97812. this.constraint.body1 = this.body1;
  97813. this.constraint.body2 = this.body2;
  97814. this.constraint.attach();
  97815. this.s1Link.shape = shape2;
  97816. this.s1Link.body = this.body2;
  97817. this.s2Link.shape = shape1;
  97818. this.s2Link.body = this.body1;
  97819. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97820. else this.s1Link.next = null;
  97821. shape1.contactLink = this.s1Link;
  97822. shape1.numContacts++;
  97823. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97824. else this.s2Link.next = null;
  97825. shape2.contactLink = this.s2Link;
  97826. shape2.numContacts++;
  97827. this.b1Link.shape = shape2;
  97828. this.b1Link.body = this.body2;
  97829. this.b2Link.shape = shape1;
  97830. this.b2Link.body = this.body1;
  97831. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97832. else this.b1Link.next = null;
  97833. this.body1.contactLink = this.b1Link;
  97834. this.body1.numContacts++;
  97835. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97836. else this.b2Link.next = null;
  97837. this.body2.contactLink = this.b2Link;
  97838. this.body2.numContacts++;
  97839. this.prev = null;
  97840. this.next = null;
  97841. this.persisting = true;
  97842. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97843. this.manifold.numPoints = 0;
  97844. },
  97845. /**
  97846. * Detach the contact from the shapes.
  97847. */
  97848. detach: function () {
  97849. var prev = this.s1Link.prev;
  97850. var next = this.s1Link.next;
  97851. if (prev !== null) prev.next = next;
  97852. if (next !== null) next.prev = prev;
  97853. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97854. this.s1Link.prev = null;
  97855. this.s1Link.next = null;
  97856. this.s1Link.shape = null;
  97857. this.s1Link.body = null;
  97858. this.shape1.numContacts--;
  97859. prev = this.s2Link.prev;
  97860. next = this.s2Link.next;
  97861. if (prev !== null) prev.next = next;
  97862. if (next !== null) next.prev = prev;
  97863. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  97864. this.s2Link.prev = null;
  97865. this.s2Link.next = null;
  97866. this.s2Link.shape = null;
  97867. this.s2Link.body = null;
  97868. this.shape2.numContacts--;
  97869. prev = this.b1Link.prev;
  97870. next = this.b1Link.next;
  97871. if (prev !== null) prev.next = next;
  97872. if (next !== null) next.prev = prev;
  97873. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  97874. this.b1Link.prev = null;
  97875. this.b1Link.next = null;
  97876. this.b1Link.shape = null;
  97877. this.b1Link.body = null;
  97878. this.body1.numContacts--;
  97879. prev = this.b2Link.prev;
  97880. next = this.b2Link.next;
  97881. if (prev !== null) prev.next = next;
  97882. if (next !== null) next.prev = prev;
  97883. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  97884. this.b2Link.prev = null;
  97885. this.b2Link.next = null;
  97886. this.b2Link.shape = null;
  97887. this.b2Link.body = null;
  97888. this.body2.numContacts--;
  97889. this.manifold.body1 = null;
  97890. this.manifold.body2 = null;
  97891. this.constraint.body1 = null;
  97892. this.constraint.body2 = null;
  97893. this.constraint.detach();
  97894. this.shape1 = null;
  97895. this.shape2 = null;
  97896. this.body1 = null;
  97897. this.body2 = null;
  97898. }
  97899. }
  97900. /**
  97901. * ...
  97902. * @author saharan
  97903. */
  97904. OIMO.ContactConstraint = function (manifold) {
  97905. OIMO.Constraint.call(this);
  97906. // The contact manifold of the constraint.
  97907. this.manifold = manifold;
  97908. // The coefficient of restitution of the constraint.
  97909. this.restitution = NaN;
  97910. // The coefficient of friction of the constraint.
  97911. this.friction = NaN;
  97912. this.p1 = null;
  97913. this.p2 = null;
  97914. this.lv1 = null;
  97915. this.lv2 = null;
  97916. this.av1 = null;
  97917. this.av2 = null;
  97918. this.i1 = null;
  97919. this.i2 = null;
  97920. this.ii1 = null;
  97921. this.ii2 = null;
  97922. this.m1 = NaN;
  97923. this.m2 = NaN;
  97924. this.num = 0;
  97925. this.ps = manifold.points;
  97926. this.cs = new OIMO.ContactPointDataBuffer();
  97927. this.cs.next = new OIMO.ContactPointDataBuffer();
  97928. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  97929. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  97930. }
  97931. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  97932. /**
  97933. * Attach the constraint to the bodies.
  97934. */
  97935. OIMO.ContactConstraint.prototype.attach = function () {
  97936. this.p1 = this.body1.position;
  97937. this.p2 = this.body2.position;
  97938. this.lv1 = this.body1.linearVelocity;
  97939. this.av1 = this.body1.angularVelocity;
  97940. this.lv2 = this.body2.linearVelocity;
  97941. this.av2 = this.body2.angularVelocity;
  97942. this.i1 = this.body1.inverseInertia;
  97943. this.i2 = this.body2.inverseInertia;
  97944. }
  97945. /**
  97946. * Detach the constraint from the bodies.
  97947. */
  97948. OIMO.ContactConstraint.prototype.detach = function () {
  97949. this.p1 = null;
  97950. this.p2 = null;
  97951. this.lv1 = null;
  97952. this.lv2 = null;
  97953. this.av1 = null;
  97954. this.av2 = null;
  97955. this.i1 = null;
  97956. this.i2 = null;
  97957. }
  97958. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  97959. this.m1 = this.body1.inverseMass;
  97960. this.m2 = this.body2.inverseMass;
  97961. this.ii1 = this.i1.clone();
  97962. this.ii2 = this.i2.clone();
  97963. var ii1 = this.ii1.elements;
  97964. var ii2 = this.ii2.elements;
  97965. var p1x = this.p1.x;
  97966. var p1y = this.p1.y;
  97967. var p1z = this.p1.z;
  97968. var p2x = this.p2.x;
  97969. var p2y = this.p2.y;
  97970. var p2z = this.p2.z;
  97971. var m1m2 = this.m1 + this.m2;
  97972. this.num = this.manifold.numPoints;
  97973. var c = this.cs;
  97974. for (var i = 0; i < this.num; i++) {
  97975. var p = this.ps[i];
  97976. var tmp1X;
  97977. var tmp1Y;
  97978. var tmp1Z;
  97979. var tmp2X;
  97980. var tmp2Y;
  97981. var tmp2Z;
  97982. tmp1X = p.position.x;
  97983. tmp1Y = p.position.y;
  97984. tmp1Z = p.position.z;
  97985. var rp1X = tmp1X - p1x;
  97986. var rp1Y = tmp1Y - p1y;
  97987. var rp1Z = tmp1Z - p1z;
  97988. var rp2X = tmp1X - p2x;
  97989. var rp2Y = tmp1Y - p2y;
  97990. var rp2Z = tmp1Z - p2z;
  97991. c.rp1X = rp1X;
  97992. c.rp1Y = rp1Y;
  97993. c.rp1Z = rp1Z;
  97994. c.rp2X = rp2X;
  97995. c.rp2Y = rp2Y;
  97996. c.rp2Z = rp2Z;
  97997. c.norImp = p.normalImpulse;
  97998. c.tanImp = p.tangentImpulse;
  97999. c.binImp = p.binormalImpulse;
  98000. var norX = p.normal.x;
  98001. var norY = p.normal.y;
  98002. var norZ = p.normal.z;
  98003. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98004. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98005. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98006. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98007. var tanX = rvX - rvn * norX;
  98008. var tanY = rvY - rvn * norY;
  98009. var tanZ = rvZ - rvn * norZ;
  98010. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98011. if (len > 0.04) {
  98012. len = 1 / OIMO.sqrt(len);
  98013. } else {
  98014. tanX = norY * norX - norZ * norZ;
  98015. tanY = -norZ * norY - norX * norX;
  98016. tanZ = norX * norZ + norY * norY;
  98017. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98018. }
  98019. tanX *= len;
  98020. tanY *= len;
  98021. tanZ *= len;
  98022. var binX = norY * tanZ - norZ * tanY;
  98023. var binY = norZ * tanX - norX * tanZ;
  98024. var binZ = norX * tanY - norY * tanX;
  98025. c.norX = norX;
  98026. c.norY = norY;
  98027. c.norZ = norZ;
  98028. c.tanX = tanX;
  98029. c.tanY = tanY;
  98030. c.tanZ = tanZ;
  98031. c.binX = binX;
  98032. c.binY = binY;
  98033. c.binZ = binZ;
  98034. c.norU1X = norX * this.m1;
  98035. c.norU1Y = norY * this.m1;
  98036. c.norU1Z = norZ * this.m1;
  98037. c.norU2X = norX * this.m2;
  98038. c.norU2Y = norY * this.m2;
  98039. c.norU2Z = norZ * this.m2;
  98040. c.tanU1X = tanX * this.m1;
  98041. c.tanU1Y = tanY * this.m1;
  98042. c.tanU1Z = tanZ * this.m1;
  98043. c.tanU2X = tanX * this.m2;
  98044. c.tanU2Y = tanY * this.m2;
  98045. c.tanU2Z = tanZ * this.m2;
  98046. c.binU1X = binX * this.m1;
  98047. c.binU1Y = binY * this.m1;
  98048. c.binU1Z = binZ * this.m1;
  98049. c.binU2X = binX * this.m2;
  98050. c.binU2Y = binY * this.m2;
  98051. c.binU2Z = binZ * this.m2;
  98052. var norT1X = rp1Y * norZ - rp1Z * norY;
  98053. var norT1Y = rp1Z * norX - rp1X * norZ;
  98054. var norT1Z = rp1X * norY - rp1Y * norX;
  98055. var norT2X = rp2Y * norZ - rp2Z * norY;
  98056. var norT2Y = rp2Z * norX - rp2X * norZ;
  98057. var norT2Z = rp2X * norY - rp2Y * norX;
  98058. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98059. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98060. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98061. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98062. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98063. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98064. var binT1X = rp1Y * binZ - rp1Z * binY;
  98065. var binT1Y = rp1Z * binX - rp1X * binZ;
  98066. var binT1Z = rp1X * binY - rp1Y * binX;
  98067. var binT2X = rp2Y * binZ - rp2Z * binY;
  98068. var binT2Y = rp2Z * binX - rp2X * binZ;
  98069. var binT2Z = rp2X * binY - rp2Y * binX;
  98070. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98071. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98072. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98073. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98074. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98075. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98076. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98077. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98078. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98079. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98080. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98081. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98082. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98083. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98084. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98085. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98086. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98087. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98088. c.norT1X = norT1X;
  98089. c.norT1Y = norT1Y;
  98090. c.norT1Z = norT1Z;
  98091. c.tanT1X = tanT1X;
  98092. c.tanT1Y = tanT1Y;
  98093. c.tanT1Z = tanT1Z;
  98094. c.binT1X = binT1X;
  98095. c.binT1Y = binT1Y;
  98096. c.binT1Z = binT1Z;
  98097. c.norT2X = norT2X;
  98098. c.norT2Y = norT2Y;
  98099. c.norT2Z = norT2Z;
  98100. c.tanT2X = tanT2X;
  98101. c.tanT2Y = tanT2Y;
  98102. c.tanT2Z = tanT2Z;
  98103. c.binT2X = binT2X;
  98104. c.binT2Y = binT2Y;
  98105. c.binT2Z = binT2Z;
  98106. c.norTU1X = norTU1X;
  98107. c.norTU1Y = norTU1Y;
  98108. c.norTU1Z = norTU1Z;
  98109. c.tanTU1X = tanTU1X;
  98110. c.tanTU1Y = tanTU1Y;
  98111. c.tanTU1Z = tanTU1Z;
  98112. c.binTU1X = binTU1X;
  98113. c.binTU1Y = binTU1Y;
  98114. c.binTU1Z = binTU1Z;
  98115. c.norTU2X = norTU2X;
  98116. c.norTU2Y = norTU2Y;
  98117. c.norTU2Z = norTU2Z;
  98118. c.tanTU2X = tanTU2X;
  98119. c.tanTU2Y = tanTU2Y;
  98120. c.tanTU2Z = tanTU2Z;
  98121. c.binTU2X = binTU2X;
  98122. c.binTU2Y = binTU2Y;
  98123. c.binTU2Z = binTU2Z;
  98124. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98125. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98126. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98127. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98128. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98129. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98130. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98131. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98132. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98133. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98134. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98135. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98136. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98137. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98138. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98139. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98140. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98141. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98142. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98143. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98144. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98145. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98146. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98147. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98148. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98149. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98150. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98151. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98152. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98153. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98154. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98155. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98156. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98157. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98158. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98159. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98160. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98161. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98162. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98163. c.norDen = norDen;
  98164. c.tanDen = tanDen;
  98165. c.binDen = binDen;
  98166. if (p.warmStarted) {
  98167. var norImp = p.normalImpulse;
  98168. this.lv1.x += c.norU1X * norImp;
  98169. this.lv1.y += c.norU1Y * norImp;
  98170. this.lv1.z += c.norU1Z * norImp;
  98171. this.av1.x += norTU1X * norImp;
  98172. this.av1.y += norTU1Y * norImp;
  98173. this.av1.z += norTU1Z * norImp;
  98174. this.lv2.x -= c.norU2X * norImp;
  98175. this.lv2.y -= c.norU2Y * norImp;
  98176. this.lv2.z -= c.norU2Z * norImp;
  98177. this.av2.x -= norTU2X * norImp;
  98178. this.av2.y -= norTU2Y * norImp;
  98179. this.av2.z -= norTU2Z * norImp;
  98180. c.norImp = norImp;
  98181. c.tanImp = 0;
  98182. c.binImp = 0;
  98183. rvn = 0; // disable bouncing
  98184. } else {
  98185. c.norImp = 0;
  98186. c.tanImp = 0;
  98187. c.binImp = 0;
  98188. }
  98189. if (rvn > -1) {
  98190. rvn = 0; // disable bouncing
  98191. }
  98192. var norTar = this.restitution * -rvn;
  98193. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98194. if (norTar < sepV) norTar = sepV;
  98195. c.norTar = norTar;
  98196. c.last = i == this.num - 1;
  98197. c = c.next;
  98198. }
  98199. }
  98200. OIMO.ContactConstraint.prototype.solve = function () {
  98201. var lv1x = this.lv1.x;
  98202. var lv1y = this.lv1.y;
  98203. var lv1z = this.lv1.z;
  98204. var lv2x = this.lv2.x;
  98205. var lv2y = this.lv2.y;
  98206. var lv2z = this.lv2.z;
  98207. var av1x = this.av1.x;
  98208. var av1y = this.av1.y;
  98209. var av1z = this.av1.z;
  98210. var av2x = this.av2.x;
  98211. var av2y = this.av2.y;
  98212. var av2z = this.av2.z;
  98213. var c = this.cs;
  98214. while (true) {
  98215. var oldImp1;
  98216. var newImp1;
  98217. var oldImp2;
  98218. var newImp2;
  98219. var rvn;
  98220. var norImp = c.norImp;
  98221. var tanImp = c.tanImp;
  98222. var binImp = c.binImp;
  98223. var max = -norImp * this.friction;
  98224. var rvX = lv2x - lv1x;
  98225. var rvY = lv2y - lv1y;
  98226. var rvZ = lv2z - lv1z;
  98227. rvn =
  98228. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98229. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98230. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98231. ;
  98232. oldImp1 = tanImp;
  98233. newImp1 = rvn * c.tanDen;
  98234. tanImp += newImp1;
  98235. rvn =
  98236. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98237. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98238. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98239. ;
  98240. oldImp2 = binImp;
  98241. newImp2 = rvn * c.binDen;
  98242. binImp += newImp2;
  98243. // cone friction clamp
  98244. var len = tanImp * tanImp + binImp * binImp;
  98245. if (len > max * max) {
  98246. len = max / OIMO.sqrt(len);
  98247. tanImp *= len;
  98248. binImp *= len;
  98249. }
  98250. newImp1 = tanImp - oldImp1;
  98251. newImp2 = binImp - oldImp2;
  98252. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98253. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98254. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98255. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98256. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98257. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98258. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98259. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98260. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98261. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98262. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98263. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98264. // restitution part
  98265. rvn =
  98266. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98267. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98268. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98269. oldImp1 = norImp;
  98270. newImp1 = (rvn - c.norTar) * c.norDen;
  98271. norImp += newImp1;
  98272. if (norImp > 0) norImp = 0;
  98273. newImp1 = norImp - oldImp1;
  98274. lv1x += c.norU1X * newImp1;
  98275. lv1y += c.norU1Y * newImp1;
  98276. lv1z += c.norU1Z * newImp1;
  98277. av1x += c.norTU1X * newImp1;
  98278. av1y += c.norTU1Y * newImp1;
  98279. av1z += c.norTU1Z * newImp1;
  98280. lv2x -= c.norU2X * newImp1;
  98281. lv2y -= c.norU2Y * newImp1;
  98282. lv2z -= c.norU2Z * newImp1;
  98283. av2x -= c.norTU2X * newImp1;
  98284. av2y -= c.norTU2Y * newImp1;
  98285. av2z -= c.norTU2Z * newImp1;
  98286. c.norImp = norImp;
  98287. c.tanImp = tanImp;
  98288. c.binImp = binImp;
  98289. if (c.last) break;
  98290. c = c.next;
  98291. }
  98292. this.lv1.x = lv1x;
  98293. this.lv1.y = lv1y;
  98294. this.lv1.z = lv1z;
  98295. this.lv2.x = lv2x;
  98296. this.lv2.y = lv2y;
  98297. this.lv2.z = lv2z;
  98298. this.av1.x = av1x;
  98299. this.av1.y = av1y;
  98300. this.av1.z = av1z;
  98301. this.av2.x = av2x;
  98302. this.av2.y = av2y;
  98303. this.av2.z = av2z;
  98304. }
  98305. OIMO.ContactConstraint.prototype.postSolve = function () {
  98306. var c = this.cs;
  98307. var i = this.num;
  98308. while (i--) {
  98309. //for(var i=0;i<this.num;i++){
  98310. var p = this.ps[i];
  98311. p.normal.x = c.norX;
  98312. p.normal.y = c.norY;
  98313. p.normal.z = c.norZ;
  98314. p.tangent.x = c.tanX;
  98315. p.tangent.y = c.tanY;
  98316. p.tangent.z = c.tanZ;
  98317. p.binormal.x = c.binX;
  98318. p.binormal.y = c.binY;
  98319. p.binormal.z = c.binZ;
  98320. p.normalImpulse = c.norImp;
  98321. p.tangentImpulse = c.tanImp;
  98322. p.binormalImpulse = c.binImp;
  98323. p.normalDenominator = c.norDen;
  98324. p.tangentDenominator = c.tanDen;
  98325. p.binormalDenominator = c.binDen;
  98326. c = c.next;
  98327. }
  98328. }
  98329. /**
  98330. * A link list of contacts.
  98331. * @author saharan
  98332. */
  98333. OIMO.ContactLink = function (contact) {
  98334. // The previous contact link.
  98335. this.prev = null;
  98336. // The next contact link.
  98337. this.next = null;
  98338. // The shape of the contact.
  98339. this.shape = null;
  98340. // The other rigid body.
  98341. this.body = null;
  98342. // The contact of the link.
  98343. this.contact = contact;
  98344. }
  98345. /**
  98346. * A contact manifold between two shapes.
  98347. * @author saharan
  98348. */
  98349. OIMO.ContactManifold = function () {
  98350. // The first rigid body.
  98351. this.body1 = null;
  98352. // The second rigid body.
  98353. this.body2 = null;
  98354. // The number of manifold points.
  98355. this.numPoints = 0;
  98356. // The manifold points.
  98357. this.points = [];
  98358. this.points.length = 4;
  98359. this.points[0] = new OIMO.ManifoldPoint();
  98360. this.points[1] = new OIMO.ManifoldPoint();
  98361. this.points[2] = new OIMO.ManifoldPoint();
  98362. this.points[3] = new OIMO.ManifoldPoint();
  98363. }
  98364. OIMO.ContactManifold.prototype = {
  98365. constructor: OIMO.ContactManifold,
  98366. /**
  98367. * Reset the manifold.
  98368. * @param shape1
  98369. * @param shape2
  98370. */
  98371. reset: function (shape1, shape2) {
  98372. this.body1 = shape1.parent;
  98373. this.body2 = shape2.parent;
  98374. this.numPoints = 0;
  98375. },
  98376. /**
  98377. * Add a point into this manifold.
  98378. * @param x
  98379. * @param y
  98380. * @param z
  98381. * @param normalX
  98382. * @param normalY
  98383. * @param normalZ
  98384. * @param penetration
  98385. * @param flip
  98386. */
  98387. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98388. var p = this.points[this.numPoints++];
  98389. p.position.x = x;
  98390. p.position.y = y;
  98391. p.position.z = z;
  98392. var r = this.body1.rotation;
  98393. var rx = x - this.body1.position.x;
  98394. var ry = y - this.body1.position.y;
  98395. var rz = z - this.body1.position.z;
  98396. var tr = r.elements;
  98397. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98398. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98399. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98400. r = this.body2.rotation;
  98401. rx = x - this.body2.position.x;
  98402. ry = y - this.body2.position.y;
  98403. rz = z - this.body2.position.z;
  98404. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98405. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98406. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98407. p.normalImpulse = 0;
  98408. if (flip) {
  98409. p.normal.x = -normalX;
  98410. p.normal.y = -normalY;
  98411. p.normal.z = -normalZ;
  98412. } else {
  98413. p.normal.x = normalX;
  98414. p.normal.y = normalY;
  98415. p.normal.z = normalZ;
  98416. }
  98417. p.penetration = penetration;
  98418. p.warmStarted = false;
  98419. }
  98420. }
  98421. OIMO.ContactPointDataBuffer = function () {
  98422. this.norX = NaN;
  98423. this.norY = NaN;
  98424. this.norZ = NaN;
  98425. this.tanX = NaN;
  98426. this.tanY = NaN;
  98427. this.tanZ = NaN;
  98428. this.binX = NaN;
  98429. this.binY = NaN;
  98430. this.binZ = NaN;
  98431. this.rp1X = NaN;
  98432. this.rp1Y = NaN;
  98433. this.rp1Z = NaN;
  98434. this.rp2X = NaN;
  98435. this.rp2Y = NaN;
  98436. this.rp2Z = NaN;
  98437. this.norU1X = NaN;
  98438. this.norU1Y = NaN;
  98439. this.norU1Z = NaN;
  98440. this.norU2X = NaN;
  98441. this.norU2Y = NaN;
  98442. this.norU2Z = NaN;
  98443. this.tanU1X = NaN;
  98444. this.tanU1Y = NaN;
  98445. this.tanU1Z = NaN;
  98446. this.tanU2X = NaN;
  98447. this.tanU2Y = NaN;
  98448. this.tanU2Z = NaN;
  98449. this.binU1X = NaN;
  98450. this.binU1Y = NaN;
  98451. this.binU1Z = NaN;
  98452. this.binU2X = NaN;
  98453. this.binU2Y = NaN;
  98454. this.binU2Z = NaN;
  98455. this.norT1X = NaN;
  98456. this.norT1Y = NaN;
  98457. this.norT1Z = NaN;
  98458. this.norT2X = NaN;
  98459. this.norT2Y = NaN;
  98460. this.norT2Z = NaN;
  98461. this.tanT1X = NaN;
  98462. this.tanT1Y = NaN;
  98463. this.tanT1Z = NaN;
  98464. this.tanT2X = NaN;
  98465. this.tanT2Y = NaN;
  98466. this.tanT2Z = NaN;
  98467. this.binT1X = NaN;
  98468. this.binT1Y = NaN;
  98469. this.binT1Z = NaN;
  98470. this.binT2X = NaN;
  98471. this.binT2Y = NaN;
  98472. this.binT2Z = NaN;
  98473. this.norTU1X = NaN;
  98474. this.norTU1Y = NaN;
  98475. this.norTU1Z = NaN;
  98476. this.norTU2X = NaN;
  98477. this.norTU2Y = NaN;
  98478. this.norTU2Z = NaN;
  98479. this.tanTU1X = NaN;
  98480. this.tanTU1Y = NaN;
  98481. this.tanTU1Z = NaN;
  98482. this.tanTU2X = NaN;
  98483. this.tanTU2Y = NaN;
  98484. this.tanTU2Z = NaN;
  98485. this.binTU1X = NaN;
  98486. this.binTU1Y = NaN;
  98487. this.binTU1Z = NaN;
  98488. this.binTU2X = NaN;
  98489. this.binTU2Y = NaN;
  98490. this.binTU2Z = NaN;
  98491. this.norImp = NaN;
  98492. this.tanImp = NaN;
  98493. this.binImp = NaN;
  98494. this.norDen = NaN;
  98495. this.tanDen = NaN;
  98496. this.binDen = NaN;
  98497. this.norTar = NaN;
  98498. this.next = null;
  98499. this.last = false;
  98500. }
  98501. OIMO.ImpulseDataBuffer = function () {
  98502. this.lp1X = NaN;
  98503. this.lp1Y = NaN;
  98504. this.lp1Z = NaN;
  98505. this.lp2X = NaN;
  98506. this.lp2Y = NaN;
  98507. this.lp2Z = NaN;
  98508. this.impulse = NaN;
  98509. }
  98510. /**
  98511. * The class holds details of the contact point.
  98512. * @author saharan
  98513. */
  98514. OIMO.ManifoldPoint = function () {
  98515. // Whether this manifold point is persisting or not.
  98516. this.warmStarted = false;
  98517. // The position of this manifold point.
  98518. this.position = new OIMO.Vec3();
  98519. // The position in the first shape's coordinate.
  98520. this.localPoint1 = new OIMO.Vec3();
  98521. // The position in the second shape's coordinate.
  98522. this.localPoint2 = new OIMO.Vec3();
  98523. // The normal vector of this manifold point.
  98524. this.normal = new OIMO.Vec3();
  98525. // The tangent vector of this manifold point.
  98526. this.tangent = new OIMO.Vec3();
  98527. // The binormal vector of this manifold point.
  98528. this.binormal = new OIMO.Vec3();
  98529. // The impulse in normal direction.
  98530. this.normalImpulse = 0;
  98531. // The impulse in tangent direction.
  98532. this.tangentImpulse = 0;
  98533. // The impulse in binormal direction.
  98534. this.binormalImpulse = 0;
  98535. // The denominator in normal direction.
  98536. this.normalDenominator = 0;
  98537. // The denominator in tangent direction.
  98538. this.tangentDenominator = 0;
  98539. // The denominator in binormal direction.
  98540. this.binormalDenominator = 0;
  98541. // The depth of penetration.
  98542. this.penetration = 0;
  98543. }
  98544. /**
  98545. * This class holds mass information of a shape.
  98546. * @author saharan
  98547. */
  98548. OIMO.MassInfo = function () {
  98549. // Mass of the shape.
  98550. this.mass = 0;
  98551. // The moment inertia of the shape.
  98552. this.inertia = new OIMO.Mat33();
  98553. };
  98554. /**
  98555. * A shape is used to detect collisions of rigid bodies.
  98556. * @author saharan
  98557. * @author lo-th
  98558. */
  98559. OIMO.Shape = function (config) {
  98560. this.type = OIMO.SHAPE_NULL;
  98561. // The global identification of the shape should be unique to the shape.
  98562. this.id = OIMO.nextID++;
  98563. // The previous shape in parent rigid body.
  98564. this.prev = null;
  98565. // The next shape in parent rigid body.
  98566. this.next = null;
  98567. // The proxy of the shape used for broad-phase collision detection.
  98568. this.proxy = null;
  98569. // The parent rigid body of the shape.
  98570. this.parent = null;
  98571. // The linked list of the contacts with the shape.
  98572. this.contactLink = null;
  98573. // The number of the contacts with the shape.
  98574. this.numContacts = 0;
  98575. // The center of gravity of the shape in world coordinate system.
  98576. this.position = new OIMO.Vec3();
  98577. // The rotation matrix of the shape in world coordinate system
  98578. this.rotation = new OIMO.Mat33();
  98579. // The position of the shape in parent's coordinate system.
  98580. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98581. // The rotation matrix of the shape in parent's coordinate system.
  98582. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98583. // The axis-aligned bounding box of the shape.
  98584. this.aabb = new OIMO.AABB();
  98585. // The density of the shape.
  98586. this.density = config.density;
  98587. // The coefficient of friction of the shape.
  98588. this.friction = config.friction;
  98589. // The coefficient of restitution of the shape.
  98590. this.restitution = config.restitution;
  98591. // The bits of the collision groups to which the shape belongs.
  98592. this.belongsTo = config.belongsTo;
  98593. // The bits of the collision groups with which the shape collides.
  98594. this.collidesWith = config.collidesWith;
  98595. };
  98596. OIMO.Shape.prototype = {
  98597. constructor: OIMO.Shape,
  98598. // Calculate the mass information of the shape.
  98599. calculateMassInfo: function (out) {
  98600. OIMO.Error("Shape", "Inheritance error.");
  98601. },
  98602. // Update the proxy of the shape.
  98603. updateProxy: function () {
  98604. OIMO.Error("Shape", "Inheritance error.");
  98605. }
  98606. };
  98607. /**
  98608. * A shape configuration holds common configuration data for constructing a shape.
  98609. * Shape configurations can be reused safely.
  98610. * @author saharan
  98611. */
  98612. OIMO.ShapeConfig = function () {
  98613. // The position of the shape in parent's coordinate system.
  98614. this.relativePosition = new OIMO.Vec3();
  98615. // The rotation matrix of the shape in parent's coordinate system.
  98616. this.relativeRotation = new OIMO.Mat33();
  98617. // The coefficient of friction of the shape.
  98618. this.friction = 0.4;
  98619. // The coefficient of restitution of the shape.
  98620. this.restitution = 0.2;
  98621. // The density of the shape.
  98622. this.density = 1;
  98623. // The bits of the collision groups to which the shape belongs.
  98624. this.belongsTo = 1;
  98625. // The bits of the collision groups with which the shape collides.
  98626. this.collidesWith = 0xffffffff;
  98627. };
  98628. /**
  98629. * A box shape.
  98630. * @author saharan
  98631. * @author lo-th
  98632. */
  98633. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98634. OIMO.Shape.call(this, config);
  98635. this.type = OIMO.SHAPE_BOX;
  98636. // The width of the box.
  98637. this.width = Width;
  98638. // The height of the box.
  98639. this.height = Height;
  98640. // The depth of the box.
  98641. this.depth = Depth;
  98642. // The half-width of the box.
  98643. this.halfWidth = Width * 0.5;
  98644. // The half-height of the box.
  98645. this.halfHeight = Height * 0.5;
  98646. // The half-depth of the box.
  98647. this.halfDepth = Depth * 0.5;
  98648. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98649. this.elements = new OIMO_ARRAY_TYPE(24);
  98650. };
  98651. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98652. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98653. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98654. var mass = this.width * this.height * this.depth * this.density;
  98655. var divid = 1 / 12;
  98656. out.mass = mass;
  98657. out.inertia.set(
  98658. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98659. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98660. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98661. );
  98662. };
  98663. OIMO.BoxShape.prototype.updateProxy = function () {
  98664. var te = this.rotation.elements;
  98665. var di = this.dimentions;
  98666. // Width
  98667. di[0] = te[0];
  98668. di[1] = te[3];
  98669. di[2] = te[6];
  98670. // Height
  98671. di[3] = te[1];
  98672. di[4] = te[4];
  98673. di[5] = te[7];
  98674. // Depth
  98675. di[6] = te[2];
  98676. di[7] = te[5];
  98677. di[8] = te[8];
  98678. // halp Width
  98679. di[9] = te[0] * this.halfWidth;
  98680. di[10] = te[3] * this.halfWidth;
  98681. di[11] = te[6] * this.halfWidth;
  98682. // halp Height
  98683. di[12] = te[1] * this.halfHeight;
  98684. di[13] = te[4] * this.halfHeight;
  98685. di[14] = te[7] * this.halfHeight;
  98686. // halp Depth
  98687. di[15] = te[2] * this.halfDepth;
  98688. di[16] = te[5] * this.halfDepth;
  98689. di[17] = te[8] * this.halfDepth;
  98690. var wx = di[9];
  98691. var wy = di[10];
  98692. var wz = di[11];
  98693. var hx = di[12];
  98694. var hy = di[13];
  98695. var hz = di[14];
  98696. var dx = di[15];
  98697. var dy = di[16];
  98698. var dz = di[17];
  98699. var x = this.position.x;
  98700. var y = this.position.y;
  98701. var z = this.position.z;
  98702. var v = this.elements;
  98703. //v1
  98704. v[0] = x + wx + hx + dx;
  98705. v[1] = y + wy + hy + dy;
  98706. v[2] = z + wz + hz + dz;
  98707. //v2
  98708. v[3] = x + wx + hx - dx;
  98709. v[4] = y + wy + hy - dy;
  98710. v[5] = z + wz + hz - dz;
  98711. //v3
  98712. v[6] = x + wx - hx + dx;
  98713. v[7] = y + wy - hy + dy;
  98714. v[8] = z + wz - hz + dz;
  98715. //v4
  98716. v[9] = x + wx - hx - dx;
  98717. v[10] = y + wy - hy - dy;
  98718. v[11] = z + wz - hz - dz;
  98719. //v5
  98720. v[12] = x - wx + hx + dx;
  98721. v[13] = y - wy + hy + dy;
  98722. v[14] = z - wz + hz + dz;
  98723. //v6
  98724. v[15] = x - wx + hx - dx;
  98725. v[16] = y - wy + hy - dy;
  98726. v[17] = z - wz + hz - dz;
  98727. //v7
  98728. v[18] = x - wx - hx + dx;
  98729. v[19] = y - wy - hy + dy;
  98730. v[20] = z - wz - hz + dz;
  98731. //v8
  98732. v[21] = x - wx - hx - dx;
  98733. v[22] = y - wy - hy - dy;
  98734. v[23] = z - wz - hz - dz;
  98735. var w = di[9] < 0 ? -di[9] : di[9];
  98736. var h = di[10] < 0 ? -di[10] : di[10];
  98737. var d = di[11] < 0 ? -di[11] : di[11];
  98738. w = di[12] < 0 ? w - di[12] : w + di[12];
  98739. h = di[13] < 0 ? h - di[13] : h + di[13];
  98740. d = di[14] < 0 ? d - di[14] : d + di[14];
  98741. w = di[15] < 0 ? w - di[15] : w + di[15];
  98742. h = di[16] < 0 ? h - di[16] : h + di[16];
  98743. d = di[17] < 0 ? d - di[17] : d + di[17];
  98744. var p = OIMO.AABB_PROX;
  98745. this.aabb.set(
  98746. this.position.x - w - p, this.position.x + w + p,
  98747. this.position.y - h - p, this.position.y + h + p,
  98748. this.position.z - d - p, this.position.z + d + p
  98749. );
  98750. if (this.proxy != null) this.proxy.update();
  98751. };
  98752. /**
  98753. * A sphere shape.
  98754. * @author saharan
  98755. * @author lo-th
  98756. */
  98757. OIMO.SphereShape = function (config, radius) {
  98758. OIMO.Shape.call(this, config);
  98759. this.type = OIMO.SHAPE_SPHERE;
  98760. // The radius of the shape.
  98761. this.radius = radius;
  98762. };
  98763. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98764. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98765. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98766. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98767. out.mass = mass;
  98768. var inertia = mass * this.radius * this.radius * 0.4;
  98769. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98770. };
  98771. OIMO.SphereShape.prototype.updateProxy = function () {
  98772. var p = OIMO.AABB_PROX;
  98773. this.aabb.set(
  98774. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98775. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98776. this.position.z - this.radius - p, this.position.z + this.radius + p
  98777. );
  98778. if (this.proxy != null) this.proxy.update();
  98779. };
  98780. /**
  98781. * A cylinder shap.
  98782. * @author saharan
  98783. * @author lo-th
  98784. */
  98785. OIMO.CylinderShape = function (config, radius, height) {
  98786. OIMO.Shape.call(this, config);
  98787. this.type = OIMO.SHAPE_CYLINDER;
  98788. this.radius = radius;
  98789. this.height = height;
  98790. this.halfHeight = height * 0.5;
  98791. this.normalDirection = new OIMO.Vec3();
  98792. this.halfDirection = new OIMO.Vec3();
  98793. };
  98794. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98795. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98796. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98797. var rsq = this.radius * this.radius;
  98798. var mass = OIMO.PI * rsq * this.height * this.density;
  98799. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98800. var inertiaY = 0.5 * rsq;
  98801. out.mass = mass;
  98802. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98803. };
  98804. OIMO.CylinderShape.prototype.updateProxy = function () {
  98805. var te = this.rotation.elements;
  98806. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98807. xx = te[1] * te[1];
  98808. yy = te[4] * te[4];
  98809. zz = te[7] * te[7];
  98810. this.normalDirection.set(te[1], te[4], te[7]);
  98811. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98812. wx = 1 - xx;
  98813. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98814. if (len > 0) len = this.radius / len;
  98815. wx *= len;
  98816. hy = 1 - yy;
  98817. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98818. if (len > 0) len = this.radius / len;
  98819. hy *= len;
  98820. dz = 1 - zz;
  98821. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98822. if (len > 0) len = this.radius / len;
  98823. dz *= len;
  98824. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98825. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98826. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98827. w = wx < 0 ? w - wx : w + wx;
  98828. h = hy < 0 ? h - hy : h + hy;
  98829. d = dz < 0 ? d - dz : d + dz;
  98830. p = OIMO.AABB_PROX;
  98831. this.aabb.set(
  98832. this.position.x - w - p, this.position.x + w + p,
  98833. this.position.y - h - p, this.position.y + h + p,
  98834. this.position.z - d - p, this.position.z + d + p
  98835. );
  98836. if (this.proxy != null) this.proxy.update();
  98837. };
  98838. /**
  98839. * A tetra shape.
  98840. * @author xprogram
  98841. */
  98842. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98843. OIMO.Shape.call(this, config);
  98844. this.type = OIMO.SHAPE_TETRA;
  98845. // Vertices and faces of tetra
  98846. this.verts = [p1, p2, p3, p4];
  98847. this.faces = [
  98848. mtri(0, 1, 2),
  98849. mtri(1, 2, 3),
  98850. mtri(2, 3, 4),
  98851. mtri(4, 0, 1),
  98852. ];
  98853. };
  98854. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98855. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98856. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98857. // I guess you could calculate box mass and split it
  98858. // in half for the tetra...
  98859. };
  98860. OIMO.TetraShape.prototype.updateProxy = function () {
  98861. this.aabb.setFromPoints(this.verts);
  98862. if (this.proxy !== null)
  98863. this.proxy.update();
  98864. };
  98865. function mtri(a, b, c) {
  98866. return { a: a, b: b, c: c };
  98867. }
  98868. OIMO.CollisionDetector = function () {
  98869. this.flip = false;
  98870. };
  98871. OIMO.CollisionDetector.prototype = {
  98872. constructor: OIMO.CollisionDetector,
  98873. detectCollision: function (shape1, shape2, manifold) {
  98874. OIMO.Error("CollisionDetector", "Inheritance error.");
  98875. }
  98876. };
  98877. /**
  98878. * A collision detector which detects collisions between two boxes.
  98879. * @author saharan
  98880. */
  98881. OIMO.BoxBoxCollisionDetector = function () {
  98882. OIMO.CollisionDetector.call(this);
  98883. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  98884. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  98885. this.used = new OIMO_ARRAY_TYPE(8);
  98886. this.INF = 1 / 0;
  98887. };
  98888. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98889. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  98890. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98891. // What you are doing
  98892. // · I to prepare a separate axis of the fifteen
  98893. //-Six in each of three normal vectors of the xyz direction of the box both
  98894. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  98895. // · Calculate the depth to the separation axis
  98896. // Calculates the distance using the inner product and put the amount of embedment
  98897. // · However a vertical separation axis and side to weight a little to avoid vibration
  98898. // And end when there is a separate axis that is remote even one
  98899. // · I look for separation axis with little to dent most
  98900. // Men and if separation axis of the first six - end collision
  98901. // Heng If it separate axis of nine other - side collision
  98902. // Heng - case of a side collision
  98903. // · Find points of two sides on which you made ​​the separation axis
  98904. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  98905. //-Surface - the case of the plane crash
  98906. //-Box A, box B and the other a box of better made ​​a separate axis
  98907. // • 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
  98908. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  98909. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  98910. // • If more than one candidate 5 exists, scraping up to four
  98911. // For potential collision points of all, to examine the distance between the surface A
  98912. // • If you were on the inside surface of A, and the collision point
  98913. var b1;
  98914. var b2;
  98915. if (shape1.id < shape2.id) {
  98916. b1 = (shape1);
  98917. b2 = (shape2);
  98918. } else {
  98919. b1 = (shape2);
  98920. b2 = (shape1);
  98921. }
  98922. var V1 = b1.elements;
  98923. var V2 = b2.elements;
  98924. var D1 = b1.dimentions;
  98925. var D2 = b2.dimentions;
  98926. var p1 = b1.position;
  98927. var p2 = b2.position;
  98928. var p1x = p1.x;
  98929. var p1y = p1.y;
  98930. var p1z = p1.z;
  98931. var p2x = p2.x;
  98932. var p2y = p2.y;
  98933. var p2z = p2.z;
  98934. // diff
  98935. var dx = p2x - p1x;
  98936. var dy = p2y - p1y;
  98937. var dz = p2z - p1z;
  98938. // distance
  98939. var w1 = b1.halfWidth;
  98940. var h1 = b1.halfHeight;
  98941. var d1 = b1.halfDepth;
  98942. var w2 = b2.halfWidth;
  98943. var h2 = b2.halfHeight;
  98944. var d2 = b2.halfDepth;
  98945. // direction
  98946. // ----------------------------
  98947. // 15 separating axes
  98948. // 1~6: face
  98949. // 7~f: edge
  98950. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  98951. // ----------------------------
  98952. var a1x = D1[0];
  98953. var a1y = D1[1];
  98954. var a1z = D1[2];
  98955. var a2x = D1[3];
  98956. var a2y = D1[4];
  98957. var a2z = D1[5];
  98958. var a3x = D1[6];
  98959. var a3y = D1[7];
  98960. var a3z = D1[8];
  98961. var d1x = D1[9];
  98962. var d1y = D1[10];
  98963. var d1z = D1[11];
  98964. var d2x = D1[12];
  98965. var d2y = D1[13];
  98966. var d2z = D1[14];
  98967. var d3x = D1[15];
  98968. var d3y = D1[16];
  98969. var d3z = D1[17];
  98970. var a4x = D2[0];
  98971. var a4y = D2[1];
  98972. var a4z = D2[2];
  98973. var a5x = D2[3];
  98974. var a5y = D2[4];
  98975. var a5z = D2[5];
  98976. var a6x = D2[6];
  98977. var a6y = D2[7];
  98978. var a6z = D2[8];
  98979. var d4x = D2[9];
  98980. var d4y = D2[10];
  98981. var d4z = D2[11];
  98982. var d5x = D2[12];
  98983. var d5y = D2[13];
  98984. var d5z = D2[14];
  98985. var d6x = D2[15];
  98986. var d6y = D2[16];
  98987. var d6z = D2[17];
  98988. var a7x = a1y * a4z - a1z * a4y;
  98989. var a7y = a1z * a4x - a1x * a4z;
  98990. var a7z = a1x * a4y - a1y * a4x;
  98991. var a8x = a1y * a5z - a1z * a5y;
  98992. var a8y = a1z * a5x - a1x * a5z;
  98993. var a8z = a1x * a5y - a1y * a5x;
  98994. var a9x = a1y * a6z - a1z * a6y;
  98995. var a9y = a1z * a6x - a1x * a6z;
  98996. var a9z = a1x * a6y - a1y * a6x;
  98997. var aax = a2y * a4z - a2z * a4y;
  98998. var aay = a2z * a4x - a2x * a4z;
  98999. var aaz = a2x * a4y - a2y * a4x;
  99000. var abx = a2y * a5z - a2z * a5y;
  99001. var aby = a2z * a5x - a2x * a5z;
  99002. var abz = a2x * a5y - a2y * a5x;
  99003. var acx = a2y * a6z - a2z * a6y;
  99004. var acy = a2z * a6x - a2x * a6z;
  99005. var acz = a2x * a6y - a2y * a6x;
  99006. var adx = a3y * a4z - a3z * a4y;
  99007. var ady = a3z * a4x - a3x * a4z;
  99008. var adz = a3x * a4y - a3y * a4x;
  99009. var aex = a3y * a5z - a3z * a5y;
  99010. var aey = a3z * a5x - a3x * a5z;
  99011. var aez = a3x * a5y - a3y * a5x;
  99012. var afx = a3y * a6z - a3z * a6y;
  99013. var afy = a3z * a6x - a3x * a6z;
  99014. var afz = a3x * a6y - a3y * a6x;
  99015. // right or left flags
  99016. var right1;
  99017. var right2;
  99018. var right3;
  99019. var right4;
  99020. var right5;
  99021. var right6;
  99022. var right7;
  99023. var right8;
  99024. var right9;
  99025. var righta;
  99026. var rightb;
  99027. var rightc;
  99028. var rightd;
  99029. var righte;
  99030. var rightf;
  99031. // overlapping distances
  99032. var overlap1;
  99033. var overlap2;
  99034. var overlap3;
  99035. var overlap4;
  99036. var overlap5;
  99037. var overlap6;
  99038. var overlap7;
  99039. var overlap8;
  99040. var overlap9;
  99041. var overlapa;
  99042. var overlapb;
  99043. var overlapc;
  99044. var overlapd;
  99045. var overlape;
  99046. var overlapf;
  99047. // invalid flags
  99048. var invalid7 = false;
  99049. var invalid8 = false;
  99050. var invalid9 = false;
  99051. var invalida = false;
  99052. var invalidb = false;
  99053. var invalidc = false;
  99054. var invalidd = false;
  99055. var invalide = false;
  99056. var invalidf = false;
  99057. // temporary variables
  99058. var len;
  99059. var len1;
  99060. var len2;
  99061. var dot1;
  99062. var dot2;
  99063. var dot3;
  99064. // try axis 1
  99065. len = a1x * dx + a1y * dy + a1z * dz;
  99066. right1 = len > 0;
  99067. if (!right1) len = -len;
  99068. len1 = w1;
  99069. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99070. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99071. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99072. if (dot1 < 0) dot1 = -dot1;
  99073. if (dot2 < 0) dot2 = -dot2;
  99074. if (dot3 < 0) dot3 = -dot3;
  99075. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99076. overlap1 = len - len1 - len2;
  99077. if (overlap1 > 0) return;
  99078. // try axis 2
  99079. len = a2x * dx + a2y * dy + a2z * dz;
  99080. right2 = len > 0;
  99081. if (!right2) len = -len;
  99082. len1 = h1;
  99083. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99084. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99085. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99086. if (dot1 < 0) dot1 = -dot1;
  99087. if (dot2 < 0) dot2 = -dot2;
  99088. if (dot3 < 0) dot3 = -dot3;
  99089. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99090. overlap2 = len - len1 - len2;
  99091. if (overlap2 > 0) return;
  99092. // try axis 3
  99093. len = a3x * dx + a3y * dy + a3z * dz;
  99094. right3 = len > 0;
  99095. if (!right3) len = -len;
  99096. len1 = d1;
  99097. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99098. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99099. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99100. if (dot1 < 0) dot1 = -dot1;
  99101. if (dot2 < 0) dot2 = -dot2;
  99102. if (dot3 < 0) dot3 = -dot3;
  99103. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99104. overlap3 = len - len1 - len2;
  99105. if (overlap3 > 0) return;
  99106. // try axis 4
  99107. len = a4x * dx + a4y * dy + a4z * dz;
  99108. right4 = len > 0;
  99109. if (!right4) len = -len;
  99110. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99111. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99112. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99113. if (dot1 < 0) dot1 = -dot1;
  99114. if (dot2 < 0) dot2 = -dot2;
  99115. if (dot3 < 0) dot3 = -dot3;
  99116. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99117. len2 = w2;
  99118. overlap4 = (len - len1 - len2) * 1.0;
  99119. if (overlap4 > 0) return;
  99120. // try axis 5
  99121. len = a5x * dx + a5y * dy + a5z * dz;
  99122. right5 = len > 0;
  99123. if (!right5) len = -len;
  99124. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99125. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99126. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99127. if (dot1 < 0) dot1 = -dot1;
  99128. if (dot2 < 0) dot2 = -dot2;
  99129. if (dot3 < 0) dot3 = -dot3;
  99130. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99131. len2 = h2;
  99132. overlap5 = (len - len1 - len2) * 1.0;
  99133. if (overlap5 > 0) return;
  99134. // try axis 6
  99135. len = a6x * dx + a6y * dy + a6z * dz;
  99136. right6 = len > 0;
  99137. if (!right6) len = -len;
  99138. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99139. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99140. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99141. if (dot1 < 0) dot1 = -dot1;
  99142. if (dot2 < 0) dot2 = -dot2;
  99143. if (dot3 < 0) dot3 = -dot3;
  99144. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99145. len2 = d2;
  99146. overlap6 = (len - len1 - len2) * 1.0;
  99147. if (overlap6 > 0) return;
  99148. // try axis 7
  99149. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99150. if (len > 1e-5) {
  99151. len = 1 / OIMO.sqrt(len);
  99152. a7x *= len;
  99153. a7y *= len;
  99154. a7z *= len;
  99155. len = a7x * dx + a7y * dy + a7z * dz;
  99156. right7 = len > 0;
  99157. if (!right7) len = -len;
  99158. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99159. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99160. if (dot1 < 0) dot1 = -dot1;
  99161. if (dot2 < 0) dot2 = -dot2;
  99162. len1 = dot1 * h1 + dot2 * d1;
  99163. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99164. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99165. if (dot1 < 0) dot1 = -dot1;
  99166. if (dot2 < 0) dot2 = -dot2;
  99167. len2 = dot1 * h2 + dot2 * d2;
  99168. overlap7 = len - len1 - len2;
  99169. if (overlap7 > 0) return;
  99170. } else {
  99171. right7 = false;
  99172. overlap7 = 0;
  99173. invalid7 = true;
  99174. }
  99175. // try axis 8
  99176. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99177. if (len > 1e-5) {
  99178. len = 1 / OIMO.sqrt(len);
  99179. a8x *= len;
  99180. a8y *= len;
  99181. a8z *= len;
  99182. len = a8x * dx + a8y * dy + a8z * dz;
  99183. right8 = len > 0;
  99184. if (!right8) len = -len;
  99185. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99186. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99187. if (dot1 < 0) dot1 = -dot1;
  99188. if (dot2 < 0) dot2 = -dot2;
  99189. len1 = dot1 * h1 + dot2 * d1;
  99190. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99191. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99192. if (dot1 < 0) dot1 = -dot1;
  99193. if (dot2 < 0) dot2 = -dot2;
  99194. len2 = dot1 * w2 + dot2 * d2;
  99195. overlap8 = len - len1 - len2;
  99196. if (overlap8 > 0) return;
  99197. } else {
  99198. right8 = false;
  99199. overlap8 = 0;
  99200. invalid8 = true;
  99201. }
  99202. // try axis 9
  99203. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99204. if (len > 1e-5) {
  99205. len = 1 / OIMO.sqrt(len);
  99206. a9x *= len;
  99207. a9y *= len;
  99208. a9z *= len;
  99209. len = a9x * dx + a9y * dy + a9z * dz;
  99210. right9 = len > 0;
  99211. if (!right9) len = -len;
  99212. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99213. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99214. if (dot1 < 0) dot1 = -dot1;
  99215. if (dot2 < 0) dot2 = -dot2;
  99216. len1 = dot1 * h1 + dot2 * d1;
  99217. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99218. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99219. if (dot1 < 0) dot1 = -dot1;
  99220. if (dot2 < 0) dot2 = -dot2;
  99221. len2 = dot1 * w2 + dot2 * h2;
  99222. overlap9 = len - len1 - len2;
  99223. if (overlap9 > 0) return;
  99224. } else {
  99225. right9 = false;
  99226. overlap9 = 0;
  99227. invalid9 = true;
  99228. }
  99229. // try axis 10
  99230. len = aax * aax + aay * aay + aaz * aaz;
  99231. if (len > 1e-5) {
  99232. len = 1 / OIMO.sqrt(len);
  99233. aax *= len;
  99234. aay *= len;
  99235. aaz *= len;
  99236. len = aax * dx + aay * dy + aaz * dz;
  99237. righta = len > 0;
  99238. if (!righta) len = -len;
  99239. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99240. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99241. if (dot1 < 0) dot1 = -dot1;
  99242. if (dot2 < 0) dot2 = -dot2;
  99243. len1 = dot1 * w1 + dot2 * d1;
  99244. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99245. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99246. if (dot1 < 0) dot1 = -dot1;
  99247. if (dot2 < 0) dot2 = -dot2;
  99248. len2 = dot1 * h2 + dot2 * d2;
  99249. overlapa = len - len1 - len2;
  99250. if (overlapa > 0) return;
  99251. } else {
  99252. righta = false;
  99253. overlapa = 0;
  99254. invalida = true;
  99255. }
  99256. // try axis 11
  99257. len = abx * abx + aby * aby + abz * abz;
  99258. if (len > 1e-5) {
  99259. len = 1 / OIMO.sqrt(len);
  99260. abx *= len;
  99261. aby *= len;
  99262. abz *= len;
  99263. len = abx * dx + aby * dy + abz * dz;
  99264. rightb = len > 0;
  99265. if (!rightb) len = -len;
  99266. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99267. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99268. if (dot1 < 0) dot1 = -dot1;
  99269. if (dot2 < 0) dot2 = -dot2;
  99270. len1 = dot1 * w1 + dot2 * d1;
  99271. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99272. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99273. if (dot1 < 0) dot1 = -dot1;
  99274. if (dot2 < 0) dot2 = -dot2;
  99275. len2 = dot1 * w2 + dot2 * d2;
  99276. overlapb = len - len1 - len2;
  99277. if (overlapb > 0) return;
  99278. } else {
  99279. rightb = false;
  99280. overlapb = 0;
  99281. invalidb = true;
  99282. }
  99283. // try axis 12
  99284. len = acx * acx + acy * acy + acz * acz;
  99285. if (len > 1e-5) {
  99286. len = 1 / OIMO.sqrt(len);
  99287. acx *= len;
  99288. acy *= len;
  99289. acz *= len;
  99290. len = acx * dx + acy * dy + acz * dz;
  99291. rightc = len > 0;
  99292. if (!rightc) len = -len;
  99293. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99294. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99295. if (dot1 < 0) dot1 = -dot1;
  99296. if (dot2 < 0) dot2 = -dot2;
  99297. len1 = dot1 * w1 + dot2 * d1;
  99298. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99299. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99300. if (dot1 < 0) dot1 = -dot1;
  99301. if (dot2 < 0) dot2 = -dot2;
  99302. len2 = dot1 * w2 + dot2 * h2;
  99303. overlapc = len - len1 - len2;
  99304. if (overlapc > 0) return;
  99305. } else {
  99306. rightc = false;
  99307. overlapc = 0;
  99308. invalidc = true;
  99309. }
  99310. // try axis 13
  99311. len = adx * adx + ady * ady + adz * adz;
  99312. if (len > 1e-5) {
  99313. len = 1 / OIMO.sqrt(len);
  99314. adx *= len;
  99315. ady *= len;
  99316. adz *= len;
  99317. len = adx * dx + ady * dy + adz * dz;
  99318. rightd = len > 0;
  99319. if (!rightd) len = -len;
  99320. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99321. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99322. if (dot1 < 0) dot1 = -dot1;
  99323. if (dot2 < 0) dot2 = -dot2;
  99324. len1 = dot1 * w1 + dot2 * h1;
  99325. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99326. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99327. if (dot1 < 0) dot1 = -dot1;
  99328. if (dot2 < 0) dot2 = -dot2;
  99329. len2 = dot1 * h2 + dot2 * d2;
  99330. overlapd = len - len1 - len2;
  99331. if (overlapd > 0) return;
  99332. } else {
  99333. rightd = false;
  99334. overlapd = 0;
  99335. invalidd = true;
  99336. }
  99337. // try axis 14
  99338. len = aex * aex + aey * aey + aez * aez;
  99339. if (len > 1e-5) {
  99340. len = 1 / OIMO.sqrt(len);
  99341. aex *= len;
  99342. aey *= len;
  99343. aez *= len;
  99344. len = aex * dx + aey * dy + aez * dz;
  99345. righte = len > 0;
  99346. if (!righte) len = -len;
  99347. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99348. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99349. if (dot1 < 0) dot1 = -dot1;
  99350. if (dot2 < 0) dot2 = -dot2;
  99351. len1 = dot1 * w1 + dot2 * h1;
  99352. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99353. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99354. if (dot1 < 0) dot1 = -dot1;
  99355. if (dot2 < 0) dot2 = -dot2;
  99356. len2 = dot1 * w2 + dot2 * d2;
  99357. overlape = len - len1 - len2;
  99358. if (overlape > 0) return;
  99359. } else {
  99360. righte = false;
  99361. overlape = 0;
  99362. invalide = true;
  99363. }
  99364. // try axis 15
  99365. len = afx * afx + afy * afy + afz * afz;
  99366. if (len > 1e-5) {
  99367. len = 1 / OIMO.sqrt(len);
  99368. afx *= len;
  99369. afy *= len;
  99370. afz *= len;
  99371. len = afx * dx + afy * dy + afz * dz;
  99372. rightf = len > 0;
  99373. if (!rightf) len = -len;
  99374. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99375. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99376. if (dot1 < 0) dot1 = -dot1;
  99377. if (dot2 < 0) dot2 = -dot2;
  99378. len1 = dot1 * w1 + dot2 * h1;
  99379. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99380. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99381. if (dot1 < 0) dot1 = -dot1;
  99382. if (dot2 < 0) dot2 = -dot2;
  99383. len2 = dot1 * w2 + dot2 * h2;
  99384. overlapf = len - len1 - len2;
  99385. if (overlapf > 0) return;
  99386. } else {
  99387. rightf = false;
  99388. overlapf = 0;
  99389. invalidf = true;
  99390. }
  99391. // boxes are overlapping
  99392. var depth = overlap1;
  99393. var depth2 = overlap1;
  99394. var minIndex = 0;
  99395. var right = right1;
  99396. if (overlap2 > depth2) {
  99397. depth = overlap2;
  99398. depth2 = overlap2;
  99399. minIndex = 1;
  99400. right = right2;
  99401. }
  99402. if (overlap3 > depth2) {
  99403. depth = overlap3;
  99404. depth2 = overlap3;
  99405. minIndex = 2;
  99406. right = right3;
  99407. }
  99408. if (overlap4 > depth2) {
  99409. depth = overlap4;
  99410. depth2 = overlap4;
  99411. minIndex = 3;
  99412. right = right4;
  99413. }
  99414. if (overlap5 > depth2) {
  99415. depth = overlap5;
  99416. depth2 = overlap5;
  99417. minIndex = 4;
  99418. right = right5;
  99419. }
  99420. if (overlap6 > depth2) {
  99421. depth = overlap6;
  99422. depth2 = overlap6;
  99423. minIndex = 5;
  99424. right = right6;
  99425. }
  99426. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99427. depth = overlap7;
  99428. depth2 = overlap7 - 0.01;
  99429. minIndex = 6;
  99430. right = right7;
  99431. }
  99432. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99433. depth = overlap8;
  99434. depth2 = overlap8 - 0.01;
  99435. minIndex = 7;
  99436. right = right8;
  99437. }
  99438. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99439. depth = overlap9;
  99440. depth2 = overlap9 - 0.01;
  99441. minIndex = 8;
  99442. right = right9;
  99443. }
  99444. if (overlapa - 0.01 > depth2 && !invalida) {
  99445. depth = overlapa;
  99446. depth2 = overlapa - 0.01;
  99447. minIndex = 9;
  99448. right = righta;
  99449. }
  99450. if (overlapb - 0.01 > depth2 && !invalidb) {
  99451. depth = overlapb;
  99452. depth2 = overlapb - 0.01;
  99453. minIndex = 10;
  99454. right = rightb;
  99455. }
  99456. if (overlapc - 0.01 > depth2 && !invalidc) {
  99457. depth = overlapc;
  99458. depth2 = overlapc - 0.01;
  99459. minIndex = 11;
  99460. right = rightc;
  99461. }
  99462. if (overlapd - 0.01 > depth2 && !invalidd) {
  99463. depth = overlapd;
  99464. depth2 = overlapd - 0.01;
  99465. minIndex = 12;
  99466. right = rightd;
  99467. }
  99468. if (overlape - 0.01 > depth2 && !invalide) {
  99469. depth = overlape;
  99470. depth2 = overlape - 0.01;
  99471. minIndex = 13;
  99472. right = righte;
  99473. }
  99474. if (overlapf - 0.01 > depth2 && !invalidf) {
  99475. depth = overlapf;
  99476. minIndex = 14;
  99477. right = rightf;
  99478. }
  99479. // normal
  99480. var nx = 0;
  99481. var ny = 0;
  99482. var nz = 0;
  99483. // edge line or face side normal
  99484. var n1x = 0;
  99485. var n1y = 0;
  99486. var n1z = 0;
  99487. var n2x = 0;
  99488. var n2y = 0;
  99489. var n2z = 0;
  99490. // center of current face
  99491. var cx = 0;
  99492. var cy = 0;
  99493. var cz = 0;
  99494. // face side
  99495. var s1x = 0;
  99496. var s1y = 0;
  99497. var s1z = 0;
  99498. var s2x = 0;
  99499. var s2y = 0;
  99500. var s2z = 0;
  99501. // swap b1 b2
  99502. var swap = false;
  99503. //_______________________________________
  99504. if (minIndex == 0) {// b1.x * b2
  99505. if (right) {
  99506. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99507. nx = a1x; ny = a1y; nz = a1z;
  99508. } else {
  99509. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99510. nx = -a1x; ny = -a1y; nz = -a1z;
  99511. }
  99512. s1x = d2x; s1y = d2y; s1z = d2z;
  99513. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99514. s2x = d3x; s2y = d3y; s2z = d3z;
  99515. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99516. }
  99517. else if (minIndex == 1) {// b1.y * b2
  99518. if (right) {
  99519. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99520. nx = a2x; ny = a2y; nz = a2z;
  99521. } else {
  99522. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99523. nx = -a2x; ny = -a2y; nz = -a2z;
  99524. }
  99525. s1x = d1x; s1y = d1y; s1z = d1z;
  99526. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99527. s2x = d3x; s2y = d3y; s2z = d3z;
  99528. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99529. }
  99530. else if (minIndex == 2) {// b1.z * b2
  99531. if (right) {
  99532. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99533. nx = a3x; ny = a3y; nz = a3z;
  99534. } else {
  99535. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99536. nx = -a3x; ny = -a3y; nz = -a3z;
  99537. }
  99538. s1x = d1x; s1y = d1y; s1z = d1z;
  99539. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99540. s2x = d2x; s2y = d2y; s2z = d2z;
  99541. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99542. }
  99543. else if (minIndex == 3) {// b2.x * b1
  99544. swap = true;
  99545. if (!right) {
  99546. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99547. nx = a4x; ny = a4y; nz = a4z;
  99548. } else {
  99549. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99550. nx = -a4x; ny = -a4y; nz = -a4z;
  99551. }
  99552. s1x = d5x; s1y = d5y; s1z = d5z;
  99553. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99554. s2x = d6x; s2y = d6y; s2z = d6z;
  99555. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99556. }
  99557. else if (minIndex == 4) {// b2.y * b1
  99558. swap = true;
  99559. if (!right) {
  99560. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99561. nx = a5x; ny = a5y; nz = a5z;
  99562. } else {
  99563. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99564. nx = -a5x; ny = -a5y; nz = -a5z;
  99565. }
  99566. s1x = d4x; s1y = d4y; s1z = d4z;
  99567. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99568. s2x = d6x; s2y = d6y; s2z = d6z;
  99569. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99570. }
  99571. else if (minIndex == 5) {// b2.z * b1
  99572. swap = true;
  99573. if (!right) {
  99574. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99575. nx = a6x; ny = a6y; nz = a6z;
  99576. } else {
  99577. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99578. nx = -a6x; ny = -a6y; nz = -a6z;
  99579. }
  99580. s1x = d4x; s1y = d4y; s1z = d4z;
  99581. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99582. s2x = d5x; s2y = d5y; s2z = d5z;
  99583. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99584. }
  99585. else if (minIndex == 6) {// b1.x * b2.x
  99586. nx = a7x; ny = a7y; nz = a7z;
  99587. n1x = a1x; n1y = a1y; n1z = a1z;
  99588. n2x = a4x; n2y = a4y; n2z = a4z;
  99589. }
  99590. else if (minIndex == 7) {// b1.x * b2.y
  99591. nx = a8x; ny = a8y; nz = a8z;
  99592. n1x = a1x; n1y = a1y; n1z = a1z;
  99593. n2x = a5x; n2y = a5y; n2z = a5z;
  99594. }
  99595. else if (minIndex == 8) {// b1.x * b2.z
  99596. nx = a9x; ny = a9y; nz = a9z;
  99597. n1x = a1x; n1y = a1y; n1z = a1z;
  99598. n2x = a6x; n2y = a6y; n2z = a6z;
  99599. }
  99600. else if (minIndex == 9) {// b1.y * b2.x
  99601. nx = aax; ny = aay; nz = aaz;
  99602. n1x = a2x; n1y = a2y; n1z = a2z;
  99603. n2x = a4x; n2y = a4y; n2z = a4z
  99604. }
  99605. else if (minIndex == 10) {// b1.y * b2.y
  99606. nx = abx; ny = aby; nz = abz;
  99607. n1x = a2x; n1y = a2y; n1z = a2z;
  99608. n2x = a5x; n2y = a5y; n2z = a5z;
  99609. }
  99610. else if (minIndex == 11) {// b1.y * b2.z
  99611. nx = acx; ny = acy; nz = acz;
  99612. n1x = a2x; n1y = a2y; n1z = a2z;
  99613. n2x = a6x; n2y = a6y; n2z = a6z;
  99614. }
  99615. else if (minIndex == 12) {// b1.z * b2.x
  99616. nx = adx; ny = ady; nz = adz;
  99617. n1x = a3x; n1y = a3y; n1z = a3z;
  99618. n2x = a4x; n2y = a4y; n2z = a4z;
  99619. }
  99620. else if (minIndex == 13) {// b1.z * b2.y
  99621. nx = aex; ny = aey; nz = aez;
  99622. n1x = a3x; n1y = a3y; n1z = a3z;
  99623. n2x = a5x; n2y = a5y; n2z = a5z;
  99624. }
  99625. else if (minIndex == 14) {// b1.z * b2.z
  99626. nx = afx; ny = afy; nz = afz;
  99627. n1x = a3x; n1y = a3y; n1z = a3z;
  99628. n2x = a6x; n2y = a6y; n2z = a6z;
  99629. }
  99630. //__________________________________________
  99631. var v;
  99632. if (minIndex > 5) {
  99633. if (!right) {
  99634. nx = -nx; ny = -ny; nz = -nz;
  99635. }
  99636. var distance;
  99637. var maxDistance;
  99638. var vx;
  99639. var vy;
  99640. var vz;
  99641. var v1x;
  99642. var v1y;
  99643. var v1z;
  99644. var v2x;
  99645. var v2y;
  99646. var v2z;
  99647. //vertex1;
  99648. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99649. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99650. //vertex2;
  99651. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99652. distance = nx * vx + ny * vy + nz * vz;
  99653. if (distance > maxDistance) {
  99654. maxDistance = distance;
  99655. v1x = vx; v1y = vy; v1z = vz;
  99656. }
  99657. //vertex3;
  99658. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99659. distance = nx * vx + ny * vy + nz * vz;
  99660. if (distance > maxDistance) {
  99661. maxDistance = distance;
  99662. v1x = vx; v1y = vy; v1z = vz;
  99663. }
  99664. //vertex4;
  99665. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99666. distance = nx * vx + ny * vy + nz * vz;
  99667. if (distance > maxDistance) {
  99668. maxDistance = distance;
  99669. v1x = vx; v1y = vy; v1z = vz;
  99670. }
  99671. //vertex5;
  99672. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99673. distance = nx * vx + ny * vy + nz * vz;
  99674. if (distance > maxDistance) {
  99675. maxDistance = distance;
  99676. v1x = vx; v1y = vy; v1z = vz;
  99677. }
  99678. //vertex6;
  99679. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99680. distance = nx * vx + ny * vy + nz * vz;
  99681. if (distance > maxDistance) {
  99682. maxDistance = distance;
  99683. v1x = vx; v1y = vy; v1z = vz;
  99684. }
  99685. //vertex7;
  99686. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99687. distance = nx * vx + ny * vy + nz * vz;
  99688. if (distance > maxDistance) {
  99689. maxDistance = distance;
  99690. v1x = vx; v1y = vy; v1z = vz;
  99691. }
  99692. //vertex8;
  99693. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99694. distance = nx * vx + ny * vy + nz * vz;
  99695. if (distance > maxDistance) {
  99696. maxDistance = distance;
  99697. v1x = vx; v1y = vy; v1z = vz;
  99698. }
  99699. //vertex1;
  99700. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99701. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99702. //vertex2;
  99703. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99704. distance = nx * vx + ny * vy + nz * vz;
  99705. if (distance < maxDistance) {
  99706. maxDistance = distance;
  99707. v2x = vx; v2y = vy; v2z = vz;
  99708. }
  99709. //vertex3;
  99710. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99711. distance = nx * vx + ny * vy + nz * vz;
  99712. if (distance < maxDistance) {
  99713. maxDistance = distance;
  99714. v2x = vx; v2y = vy; v2z = vz;
  99715. }
  99716. //vertex4;
  99717. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99718. distance = nx * vx + ny * vy + nz * vz;
  99719. if (distance < maxDistance) {
  99720. maxDistance = distance;
  99721. v2x = vx; v2y = vy; v2z = vz;
  99722. }
  99723. //vertex5;
  99724. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99725. distance = nx * vx + ny * vy + nz * vz;
  99726. if (distance < maxDistance) {
  99727. maxDistance = distance;
  99728. v2x = vx; v2y = vy; v2z = vz;
  99729. }
  99730. //vertex6;
  99731. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99732. distance = nx * vx + ny * vy + nz * vz;
  99733. if (distance < maxDistance) {
  99734. maxDistance = distance;
  99735. v2x = vx; v2y = vy; v2z = vz;
  99736. }
  99737. //vertex7;
  99738. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99739. distance = nx * vx + ny * vy + nz * vz;
  99740. if (distance < maxDistance) {
  99741. maxDistance = distance;
  99742. v2x = vx; v2y = vy; v2z = vz;
  99743. }
  99744. //vertex8;
  99745. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99746. distance = nx * vx + ny * vy + nz * vz;
  99747. if (distance < maxDistance) {
  99748. maxDistance = distance;
  99749. v2x = vx; v2y = vy; v2z = vz;
  99750. }
  99751. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99752. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99753. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99754. 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);
  99755. return;
  99756. }
  99757. // now detect face-face collision...
  99758. // target quad
  99759. var q1x;
  99760. var q1y;
  99761. var q1z;
  99762. var q2x;
  99763. var q2y;
  99764. var q2z;
  99765. var q3x;
  99766. var q3y;
  99767. var q3z;
  99768. var q4x;
  99769. var q4y;
  99770. var q4z;
  99771. // search support face and vertex
  99772. var minDot = 1;
  99773. var dot = 0;
  99774. var minDotIndex = 0;
  99775. if (swap) {
  99776. dot = a1x * nx + a1y * ny + a1z * nz;
  99777. if (dot < minDot) {
  99778. minDot = dot;
  99779. minDotIndex = 0;
  99780. }
  99781. if (-dot < minDot) {
  99782. minDot = -dot;
  99783. minDotIndex = 1;
  99784. }
  99785. dot = a2x * nx + a2y * ny + a2z * nz;
  99786. if (dot < minDot) {
  99787. minDot = dot;
  99788. minDotIndex = 2;
  99789. }
  99790. if (-dot < minDot) {
  99791. minDot = -dot;
  99792. minDotIndex = 3;
  99793. }
  99794. dot = a3x * nx + a3y * ny + a3z * nz;
  99795. if (dot < minDot) {
  99796. minDot = dot;
  99797. minDotIndex = 4;
  99798. }
  99799. if (-dot < minDot) {
  99800. minDot = -dot;
  99801. minDotIndex = 5;
  99802. }
  99803. if (minDotIndex == 0) {// x+ face
  99804. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99805. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99806. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99807. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99808. }
  99809. else if (minDotIndex == 1) {// x- face
  99810. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99811. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99812. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99813. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99814. }
  99815. else if (minDotIndex == 2) {// y+ face
  99816. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99817. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99818. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99819. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99820. }
  99821. else if (minDotIndex == 3) {// y- face
  99822. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99823. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99824. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99825. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99826. }
  99827. else if (minDotIndex == 4) {// z+ face
  99828. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99829. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99830. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99831. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99832. }
  99833. else if (minDotIndex == 5) {// z- face
  99834. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99835. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99836. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99837. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99838. }
  99839. } else {
  99840. dot = a4x * nx + a4y * ny + a4z * nz;
  99841. if (dot < minDot) {
  99842. minDot = dot;
  99843. minDotIndex = 0;
  99844. }
  99845. if (-dot < minDot) {
  99846. minDot = -dot;
  99847. minDotIndex = 1;
  99848. }
  99849. dot = a5x * nx + a5y * ny + a5z * nz;
  99850. if (dot < minDot) {
  99851. minDot = dot;
  99852. minDotIndex = 2;
  99853. }
  99854. if (-dot < minDot) {
  99855. minDot = -dot;
  99856. minDotIndex = 3;
  99857. }
  99858. dot = a6x * nx + a6y * ny + a6z * nz;
  99859. if (dot < minDot) {
  99860. minDot = dot;
  99861. minDotIndex = 4;
  99862. }
  99863. if (-dot < minDot) {
  99864. minDot = -dot;
  99865. minDotIndex = 5;
  99866. }
  99867. //______________________________________________________
  99868. if (minDotIndex == 0) {// x+ face
  99869. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  99870. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  99871. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  99872. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  99873. }
  99874. else if (minDotIndex == 1) {// x- face
  99875. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  99876. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  99877. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  99878. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  99879. }
  99880. else if (minDotIndex == 2) {// y+ face
  99881. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99882. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  99883. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  99884. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99885. }
  99886. else if (minDotIndex == 3) {// y- face
  99887. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  99888. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99889. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99890. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  99891. }
  99892. else if (minDotIndex == 4) {// z+ face
  99893. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99894. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  99895. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99896. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  99897. }
  99898. else if (minDotIndex == 5) {// z- face
  99899. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  99900. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99901. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  99902. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99903. }
  99904. }
  99905. // clip vertices
  99906. var numClipVertices;
  99907. var numAddedClipVertices;
  99908. var index;
  99909. var x1;
  99910. var y1;
  99911. var z1;
  99912. var x2;
  99913. var y2;
  99914. var z2;
  99915. this.clipVertices1[0] = q1x;
  99916. this.clipVertices1[1] = q1y;
  99917. this.clipVertices1[2] = q1z;
  99918. this.clipVertices1[3] = q2x;
  99919. this.clipVertices1[4] = q2y;
  99920. this.clipVertices1[5] = q2z;
  99921. this.clipVertices1[6] = q3x;
  99922. this.clipVertices1[7] = q3y;
  99923. this.clipVertices1[8] = q3z;
  99924. this.clipVertices1[9] = q4x;
  99925. this.clipVertices1[10] = q4y;
  99926. this.clipVertices1[11] = q4z;
  99927. numAddedClipVertices = 0;
  99928. x1 = this.clipVertices1[9];
  99929. y1 = this.clipVertices1[10];
  99930. z1 = this.clipVertices1[11];
  99931. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  99932. //var i = 4;
  99933. //while(i--){
  99934. for (var i = 0; i < 4; i++) {
  99935. index = i * 3;
  99936. x2 = this.clipVertices1[index];
  99937. y2 = this.clipVertices1[index + 1];
  99938. z2 = this.clipVertices1[index + 2];
  99939. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  99940. if (dot1 > 0) {
  99941. if (dot2 > 0) {
  99942. index = numAddedClipVertices * 3;
  99943. numAddedClipVertices++;
  99944. this.clipVertices2[index] = x2;
  99945. this.clipVertices2[index + 1] = y2;
  99946. this.clipVertices2[index + 2] = z2;
  99947. } else {
  99948. index = numAddedClipVertices * 3;
  99949. numAddedClipVertices++;
  99950. t = dot1 / (dot1 - dot2);
  99951. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99952. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99953. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99954. }
  99955. } else {
  99956. if (dot2 > 0) {
  99957. index = numAddedClipVertices * 3;
  99958. numAddedClipVertices++;
  99959. t = dot1 / (dot1 - dot2);
  99960. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99961. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99962. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99963. index = numAddedClipVertices * 3;
  99964. numAddedClipVertices++;
  99965. this.clipVertices2[index] = x2;
  99966. this.clipVertices2[index + 1] = y2;
  99967. this.clipVertices2[index + 2] = z2;
  99968. }
  99969. }
  99970. x1 = x2;
  99971. y1 = y2;
  99972. z1 = z2;
  99973. dot1 = dot2;
  99974. }
  99975. numClipVertices = numAddedClipVertices;
  99976. if (numClipVertices == 0) return;
  99977. numAddedClipVertices = 0;
  99978. index = (numClipVertices - 1) * 3;
  99979. x1 = this.clipVertices2[index];
  99980. y1 = this.clipVertices2[index + 1];
  99981. z1 = this.clipVertices2[index + 2];
  99982. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  99983. //i = numClipVertices;
  99984. //while(i--){
  99985. for (i = 0; i < numClipVertices; i++) {
  99986. index = i * 3;
  99987. x2 = this.clipVertices2[index];
  99988. y2 = this.clipVertices2[index + 1];
  99989. z2 = this.clipVertices2[index + 2];
  99990. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  99991. if (dot1 > 0) {
  99992. if (dot2 > 0) {
  99993. index = numAddedClipVertices * 3;
  99994. numAddedClipVertices++;
  99995. this.clipVertices1[index] = x2;
  99996. this.clipVertices1[index + 1] = y2;
  99997. this.clipVertices1[index + 2] = z2;
  99998. } else {
  99999. index = numAddedClipVertices * 3;
  100000. numAddedClipVertices++;
  100001. t = dot1 / (dot1 - dot2);
  100002. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100003. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100004. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100005. }
  100006. } else {
  100007. if (dot2 > 0) {
  100008. index = numAddedClipVertices * 3;
  100009. numAddedClipVertices++;
  100010. t = dot1 / (dot1 - dot2);
  100011. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100012. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100013. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100014. index = numAddedClipVertices * 3;
  100015. numAddedClipVertices++;
  100016. this.clipVertices1[index] = x2;
  100017. this.clipVertices1[index + 1] = y2;
  100018. this.clipVertices1[index + 2] = z2;
  100019. }
  100020. }
  100021. x1 = x2;
  100022. y1 = y2;
  100023. z1 = z2;
  100024. dot1 = dot2;
  100025. }
  100026. numClipVertices = numAddedClipVertices;
  100027. if (numClipVertices == 0) return;
  100028. numAddedClipVertices = 0;
  100029. index = (numClipVertices - 1) * 3;
  100030. x1 = this.clipVertices1[index];
  100031. y1 = this.clipVertices1[index + 1];
  100032. z1 = this.clipVertices1[index + 2];
  100033. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100034. //i = numClipVertices;
  100035. //while(i--){
  100036. for (i = 0; i < numClipVertices; i++) {
  100037. index = i * 3;
  100038. x2 = this.clipVertices1[index];
  100039. y2 = this.clipVertices1[index + 1];
  100040. z2 = this.clipVertices1[index + 2];
  100041. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100042. if (dot1 > 0) {
  100043. if (dot2 > 0) {
  100044. index = numAddedClipVertices * 3;
  100045. numAddedClipVertices++;
  100046. this.clipVertices2[index] = x2;
  100047. this.clipVertices2[index + 1] = y2;
  100048. this.clipVertices2[index + 2] = z2;
  100049. } else {
  100050. index = numAddedClipVertices * 3;
  100051. numAddedClipVertices++;
  100052. t = dot1 / (dot1 - dot2);
  100053. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100054. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100055. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100056. }
  100057. } else {
  100058. if (dot2 > 0) {
  100059. index = numAddedClipVertices * 3;
  100060. numAddedClipVertices++;
  100061. t = dot1 / (dot1 - dot2);
  100062. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100063. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100064. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100065. index = numAddedClipVertices * 3;
  100066. numAddedClipVertices++;
  100067. this.clipVertices2[index] = x2;
  100068. this.clipVertices2[index + 1] = y2;
  100069. this.clipVertices2[index + 2] = z2;
  100070. }
  100071. }
  100072. x1 = x2;
  100073. y1 = y2;
  100074. z1 = z2;
  100075. dot1 = dot2;
  100076. }
  100077. numClipVertices = numAddedClipVertices;
  100078. if (numClipVertices == 0) return;
  100079. numAddedClipVertices = 0;
  100080. index = (numClipVertices - 1) * 3;
  100081. x1 = this.clipVertices2[index];
  100082. y1 = this.clipVertices2[index + 1];
  100083. z1 = this.clipVertices2[index + 2];
  100084. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100085. //i = numClipVertices;
  100086. //while(i--){
  100087. for (i = 0; i < numClipVertices; i++) {
  100088. index = i * 3;
  100089. x2 = this.clipVertices2[index];
  100090. y2 = this.clipVertices2[index + 1];
  100091. z2 = this.clipVertices2[index + 2];
  100092. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100093. if (dot1 > 0) {
  100094. if (dot2 > 0) {
  100095. index = numAddedClipVertices * 3;
  100096. numAddedClipVertices++;
  100097. this.clipVertices1[index] = x2;
  100098. this.clipVertices1[index + 1] = y2;
  100099. this.clipVertices1[index + 2] = z2;
  100100. } else {
  100101. index = numAddedClipVertices * 3;
  100102. numAddedClipVertices++;
  100103. t = dot1 / (dot1 - dot2);
  100104. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100105. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100106. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100107. }
  100108. } else {
  100109. if (dot2 > 0) {
  100110. index = numAddedClipVertices * 3;
  100111. numAddedClipVertices++;
  100112. t = dot1 / (dot1 - dot2);
  100113. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100114. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100115. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100116. index = numAddedClipVertices * 3;
  100117. numAddedClipVertices++;
  100118. this.clipVertices1[index] = x2;
  100119. this.clipVertices1[index + 1] = y2;
  100120. this.clipVertices1[index + 2] = z2;
  100121. }
  100122. }
  100123. x1 = x2;
  100124. y1 = y2;
  100125. z1 = z2;
  100126. dot1 = dot2;
  100127. }
  100128. numClipVertices = numAddedClipVertices;
  100129. if (swap) {
  100130. var tb = b1;
  100131. b1 = b2;
  100132. b2 = tb;
  100133. }
  100134. if (numClipVertices == 0) return;
  100135. var flipped = b1 != shape1;
  100136. if (numClipVertices > 4) {
  100137. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100138. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100139. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100140. n1x = q1x - x1;
  100141. n1y = q1y - y1;
  100142. n1z = q1z - z1;
  100143. n2x = q2x - x1;
  100144. n2y = q2y - y1;
  100145. n2z = q2z - z1;
  100146. var index1 = 0;
  100147. var index2 = 0;
  100148. var index3 = 0;
  100149. var index4 = 0;
  100150. var maxDot = -this.INF;
  100151. minDot = this.INF;
  100152. //i = numClipVertices;
  100153. //while(i--){
  100154. for (i = 0; i < numClipVertices; i++) {
  100155. this.used[i] = false;
  100156. index = i * 3;
  100157. x1 = this.clipVertices1[index];
  100158. y1 = this.clipVertices1[index + 1];
  100159. z1 = this.clipVertices1[index + 2];
  100160. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100161. if (dot < minDot) {
  100162. minDot = dot;
  100163. index1 = i;
  100164. }
  100165. if (dot > maxDot) {
  100166. maxDot = dot;
  100167. index3 = i;
  100168. }
  100169. }
  100170. this.used[index1] = true;
  100171. this.used[index3] = true;
  100172. maxDot = -this.INF;
  100173. minDot = this.INF;
  100174. //i = numClipVertices;
  100175. //while(i--){
  100176. for (i = 0; i < numClipVertices; i++) {
  100177. if (this.used[i]) continue;
  100178. index = i * 3;
  100179. x1 = this.clipVertices1[index];
  100180. y1 = this.clipVertices1[index + 1];
  100181. z1 = this.clipVertices1[index + 2];
  100182. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100183. if (dot < minDot) {
  100184. minDot = dot;
  100185. index2 = i;
  100186. }
  100187. if (dot > maxDot) {
  100188. maxDot = dot;
  100189. index4 = i;
  100190. }
  100191. }
  100192. index = index1 * 3;
  100193. x1 = this.clipVertices1[index];
  100194. y1 = this.clipVertices1[index + 1];
  100195. z1 = this.clipVertices1[index + 2];
  100196. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100197. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100198. index = index2 * 3;
  100199. x1 = this.clipVertices1[index];
  100200. y1 = this.clipVertices1[index + 1];
  100201. z1 = this.clipVertices1[index + 2];
  100202. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100203. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100204. index = index3 * 3;
  100205. x1 = this.clipVertices1[index];
  100206. y1 = this.clipVertices1[index + 1];
  100207. z1 = this.clipVertices1[index + 2];
  100208. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100209. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100210. index = index4 * 3;
  100211. x1 = this.clipVertices1[index];
  100212. y1 = this.clipVertices1[index + 1];
  100213. z1 = this.clipVertices1[index + 2];
  100214. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100215. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100216. } else {
  100217. //i = numClipVertices;
  100218. //while(i--){
  100219. for (i = 0; i < numClipVertices; i++) {
  100220. index = i * 3;
  100221. x1 = this.clipVertices1[index];
  100222. y1 = this.clipVertices1[index + 1];
  100223. z1 = this.clipVertices1[index + 2];
  100224. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100225. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100226. }
  100227. }
  100228. };
  100229. /**
  100230. * A collision detector which detects collisions between sphere and box.
  100231. * @author saharan
  100232. */
  100233. OIMO.SphereBoxCollisionDetector = function (flip) {
  100234. OIMO.CollisionDetector.call(this);
  100235. this.flip = flip;
  100236. };
  100237. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100238. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100239. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100240. var s;
  100241. var b;
  100242. if (this.flip) {
  100243. s = (shape2);
  100244. b = (shape1);
  100245. } else {
  100246. s = (shape1);
  100247. b = (shape2);
  100248. }
  100249. var D = b.dimentions;
  100250. var ps = s.position;
  100251. var psx = ps.x;
  100252. var psy = ps.y;
  100253. var psz = ps.z;
  100254. var pb = b.position;
  100255. var pbx = pb.x;
  100256. var pby = pb.y;
  100257. var pbz = pb.z;
  100258. var rad = s.radius;
  100259. var hw = b.halfWidth;
  100260. var hh = b.halfHeight;
  100261. var hd = b.halfDepth;
  100262. var dx = psx - pbx;
  100263. var dy = psy - pby;
  100264. var dz = psz - pbz;
  100265. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100266. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100267. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100268. var cx;
  100269. var cy;
  100270. var cz;
  100271. var len;
  100272. var invLen;
  100273. var overlap = 0;
  100274. if (sx > hw) {
  100275. sx = hw;
  100276. } else if (sx < -hw) {
  100277. sx = -hw;
  100278. } else {
  100279. overlap = 1;
  100280. }
  100281. if (sy > hh) {
  100282. sy = hh;
  100283. } else if (sy < -hh) {
  100284. sy = -hh;
  100285. } else {
  100286. overlap |= 2;
  100287. }
  100288. if (sz > hd) {
  100289. sz = hd;
  100290. } else if (sz < -hd) {
  100291. sz = -hd;
  100292. } else {
  100293. overlap |= 4;
  100294. }
  100295. if (overlap == 7) {
  100296. // center of sphere is in the box
  100297. if (sx < 0) {
  100298. dx = hw + sx;
  100299. } else {
  100300. dx = hw - sx;
  100301. }
  100302. if (sy < 0) {
  100303. dy = hh + sy;
  100304. } else {
  100305. dy = hh - sy;
  100306. }
  100307. if (sz < 0) {
  100308. dz = hd + sz;
  100309. } else {
  100310. dz = hd - sz;
  100311. }
  100312. if (dx < dy) {
  100313. if (dx < dz) {
  100314. len = dx - hw;
  100315. if (sx < 0) {
  100316. sx = -hw;
  100317. dx = D[0];
  100318. dy = D[1];
  100319. dz = D[2];
  100320. } else {
  100321. sx = hw;
  100322. dx = -D[0];
  100323. dy = -D[1];
  100324. dz = -D[2];
  100325. }
  100326. } else {
  100327. len = dz - hd;
  100328. if (sz < 0) {
  100329. sz = -hd;
  100330. dx = D[6];
  100331. dy = D[7];
  100332. dz = D[8];
  100333. } else {
  100334. sz = hd;
  100335. dx = -D[6];
  100336. dy = -D[7];
  100337. dz = -D[8];
  100338. }
  100339. }
  100340. } else {
  100341. if (dy < dz) {
  100342. len = dy - hh;
  100343. if (sy < 0) {
  100344. sy = -hh;
  100345. dx = D[3];
  100346. dy = D[4];
  100347. dz = D[5];
  100348. } else {
  100349. sy = hh;
  100350. dx = -D[3];
  100351. dy = -D[4];
  100352. dz = -D[5];
  100353. }
  100354. } else {
  100355. len = dz - hd;
  100356. if (sz < 0) {
  100357. sz = -hd;
  100358. dx = D[6];
  100359. dy = D[7];
  100360. dz = D[8];
  100361. } else {
  100362. sz = hd;
  100363. dx = -D[6];
  100364. dy = -D[7];
  100365. dz = -D[8];
  100366. }
  100367. }
  100368. }
  100369. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100370. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100371. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100372. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100373. } else {
  100374. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100375. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100376. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100377. dx = cx - ps.x;
  100378. dy = cy - ps.y;
  100379. dz = cz - ps.z;
  100380. len = dx * dx + dy * dy + dz * dz;
  100381. if (len > 0 && len < rad * rad) {
  100382. len = OIMO.sqrt(len);
  100383. invLen = 1 / len;
  100384. dx *= invLen;
  100385. dy *= invLen;
  100386. dz *= invLen;
  100387. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100388. }
  100389. }
  100390. };
  100391. /**
  100392. * A collision detector which detects collisions between two spheres.
  100393. * @author saharan
  100394. */
  100395. OIMO.SphereSphereCollisionDetector = function () {
  100396. OIMO.CollisionDetector.call(this);
  100397. };
  100398. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100399. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100400. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100401. var s1 = shape1;
  100402. var s2 = shape2;
  100403. var p1 = s1.position;
  100404. var p2 = s2.position;
  100405. var dx = p2.x - p1.x;
  100406. var dy = p2.y - p1.y;
  100407. var dz = p2.z - p1.z;
  100408. var len = dx * dx + dy * dy + dz * dz;
  100409. var r1 = s1.radius;
  100410. var r2 = s2.radius;
  100411. var rad = r1 + r2;
  100412. if (len > 0 && len < rad * rad) {
  100413. len = OIMO.sqrt(len);
  100414. var invLen = 1 / len;
  100415. dx *= invLen;
  100416. dy *= invLen;
  100417. dz *= invLen;
  100418. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100419. }
  100420. };
  100421. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100422. OIMO.CollisionDetector.call(this);
  100423. this.flip = flip;
  100424. };
  100425. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100426. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100427. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100428. var t1x;
  100429. var t1y;
  100430. var t1z;
  100431. var t2x;
  100432. var t2y;
  100433. var t2z;
  100434. var sup = new OIMO.Vec3();
  100435. var len;
  100436. var p1x;
  100437. var p1y;
  100438. var p1z;
  100439. var p2x;
  100440. var p2y;
  100441. var p2z;
  100442. var v01x = c1.position.x;
  100443. var v01y = c1.position.y;
  100444. var v01z = c1.position.z;
  100445. var v02x = c2.position.x;
  100446. var v02y = c2.position.y;
  100447. var v02z = c2.position.z;
  100448. var v0x = v02x - v01x;
  100449. var v0y = v02y - v01y;
  100450. var v0z = v02z - v01z;
  100451. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100452. var nx = -v0x;
  100453. var ny = -v0y;
  100454. var nz = -v0z;
  100455. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100456. var v11x = sup.x;
  100457. var v11y = sup.y;
  100458. var v11z = sup.z;
  100459. this.supportPointC(c2, nx, ny, nz, sup);
  100460. var v12x = sup.x;
  100461. var v12y = sup.y;
  100462. var v12z = sup.z;
  100463. var v1x = v12x - v11x;
  100464. var v1y = v12y - v11y;
  100465. var v1z = v12z - v11z;
  100466. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100467. return false;
  100468. }
  100469. nx = v1y * v0z - v1z * v0y;
  100470. ny = v1z * v0x - v1x * v0z;
  100471. nz = v1x * v0y - v1y * v0x;
  100472. if (nx * nx + ny * ny + nz * nz == 0) {
  100473. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100474. sep.normalize(sep);
  100475. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100476. return true;
  100477. }
  100478. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100479. var v21x = sup.x;
  100480. var v21y = sup.y;
  100481. var v21z = sup.z;
  100482. this.supportPointC(c2, nx, ny, nz, sup);
  100483. var v22x = sup.x;
  100484. var v22y = sup.y;
  100485. var v22z = sup.z;
  100486. var v2x = v22x - v21x;
  100487. var v2y = v22y - v21y;
  100488. var v2z = v22z - v21z;
  100489. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100490. return false;
  100491. }
  100492. t1x = v1x - v0x;
  100493. t1y = v1y - v0y;
  100494. t1z = v1z - v0z;
  100495. t2x = v2x - v0x;
  100496. t2y = v2y - v0y;
  100497. t2z = v2z - v0z;
  100498. nx = t1y * t2z - t1z * t2y;
  100499. ny = t1z * t2x - t1x * t2z;
  100500. nz = t1x * t2y - t1y * t2x;
  100501. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100502. t1x = v1x;
  100503. t1y = v1y;
  100504. t1z = v1z;
  100505. v1x = v2x;
  100506. v1y = v2y;
  100507. v1z = v2z;
  100508. v2x = t1x;
  100509. v2y = t1y;
  100510. v2z = t1z;
  100511. t1x = v11x;
  100512. t1y = v11y;
  100513. t1z = v11z;
  100514. v11x = v21x;
  100515. v11y = v21y;
  100516. v11z = v21z;
  100517. v21x = t1x;
  100518. v21y = t1y;
  100519. v21z = t1z;
  100520. t1x = v12x;
  100521. t1y = v12y;
  100522. t1z = v12z;
  100523. v12x = v22x;
  100524. v12y = v22y;
  100525. v12z = v22z;
  100526. v22x = t1x;
  100527. v22y = t1y;
  100528. v22z = t1z;
  100529. nx = -nx;
  100530. ny = -ny;
  100531. nz = -nz;
  100532. }
  100533. var iterations = 0;
  100534. while (true) {
  100535. if (++iterations > 100) {
  100536. return false;
  100537. }
  100538. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100539. var v31x = sup.x;
  100540. var v31y = sup.y;
  100541. var v31z = sup.z;
  100542. this.supportPointC(c2, nx, ny, nz, sup);
  100543. var v32x = sup.x;
  100544. var v32y = sup.y;
  100545. var v32z = sup.z;
  100546. var v3x = v32x - v31x;
  100547. var v3y = v32y - v31y;
  100548. var v3z = v32z - v31z;
  100549. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100550. return false;
  100551. }
  100552. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100553. v2x = v3x;
  100554. v2y = v3y;
  100555. v2z = v3z;
  100556. v21x = v31x;
  100557. v21y = v31y;
  100558. v21z = v31z;
  100559. v22x = v32x;
  100560. v22y = v32y;
  100561. v22z = v32z;
  100562. t1x = v1x - v0x;
  100563. t1y = v1y - v0y;
  100564. t1z = v1z - v0z;
  100565. t2x = v3x - v0x;
  100566. t2y = v3y - v0y;
  100567. t2z = v3z - v0z;
  100568. nx = t1y * t2z - t1z * t2y;
  100569. ny = t1z * t2x - t1x * t2z;
  100570. nz = t1x * t2y - t1y * t2x;
  100571. continue;
  100572. }
  100573. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100574. v1x = v3x;
  100575. v1y = v3y;
  100576. v1z = v3z;
  100577. v11x = v31x;
  100578. v11y = v31y;
  100579. v11z = v31z;
  100580. v12x = v32x;
  100581. v12y = v32y;
  100582. v12z = v32z;
  100583. t1x = v3x - v0x;
  100584. t1y = v3y - v0y;
  100585. t1z = v3z - v0z;
  100586. t2x = v2x - v0x;
  100587. t2y = v2y - v0y;
  100588. t2z = v2z - v0z;
  100589. nx = t1y * t2z - t1z * t2y;
  100590. ny = t1z * t2x - t1x * t2z;
  100591. nz = t1x * t2y - t1y * t2x;
  100592. continue;
  100593. }
  100594. var hit = false;
  100595. while (true) {
  100596. t1x = v2x - v1x;
  100597. t1y = v2y - v1y;
  100598. t1z = v2z - v1z;
  100599. t2x = v3x - v1x;
  100600. t2y = v3y - v1y;
  100601. t2z = v3z - v1z;
  100602. nx = t1y * t2z - t1z * t2y;
  100603. ny = t1z * t2x - t1x * t2z;
  100604. nz = t1x * t2y - t1y * t2x;
  100605. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100606. nx *= len;
  100607. ny *= len;
  100608. nz *= len;
  100609. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100610. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100611. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100612. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100613. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100614. var sum = b0 + b1 + b2 + b3;
  100615. if (sum <= 0) {
  100616. b0 = 0;
  100617. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100618. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100619. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100620. sum = b1 + b2 + b3;
  100621. }
  100622. var inv = 1 / sum;
  100623. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100624. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100625. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100626. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100627. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100628. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100629. hit = true;
  100630. }
  100631. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100632. var v41x = sup.x;
  100633. var v41y = sup.y;
  100634. var v41z = sup.z;
  100635. this.supportPointC(c2, nx, ny, nz, sup);
  100636. var v42x = sup.x;
  100637. var v42y = sup.y;
  100638. var v42z = sup.z;
  100639. var v4x = v42x - v41x;
  100640. var v4y = v42y - v41y;
  100641. var v4z = v42z - v41z;
  100642. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100643. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100644. if (hit) {
  100645. sep.init(-nx, -ny, -nz);
  100646. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100647. dep.x = separation;
  100648. return true;
  100649. }
  100650. return false;
  100651. }
  100652. if (
  100653. (v4y * v1z - v4z * v1y) * v0x +
  100654. (v4z * v1x - v4x * v1z) * v0y +
  100655. (v4x * v1y - v4y * v1x) * v0z < 0
  100656. ) {
  100657. if (
  100658. (v4y * v2z - v4z * v2y) * v0x +
  100659. (v4z * v2x - v4x * v2z) * v0y +
  100660. (v4x * v2y - v4y * v2x) * v0z < 0
  100661. ) {
  100662. v1x = v4x;
  100663. v1y = v4y;
  100664. v1z = v4z;
  100665. v11x = v41x;
  100666. v11y = v41y;
  100667. v11z = v41z;
  100668. v12x = v42x;
  100669. v12y = v42y;
  100670. v12z = v42z;
  100671. } else {
  100672. v3x = v4x;
  100673. v3y = v4y;
  100674. v3z = v4z;
  100675. v31x = v41x;
  100676. v31y = v41y;
  100677. v31z = v41z;
  100678. v32x = v42x;
  100679. v32y = v42y;
  100680. v32z = v42z;
  100681. }
  100682. } else {
  100683. if (
  100684. (v4y * v3z - v4z * v3y) * v0x +
  100685. (v4z * v3x - v4x * v3z) * v0y +
  100686. (v4x * v3y - v4y * v3x) * v0z < 0
  100687. ) {
  100688. v2x = v4x;
  100689. v2y = v4y;
  100690. v2z = v4z;
  100691. v21x = v41x;
  100692. v21y = v41y;
  100693. v21z = v41z;
  100694. v22x = v42x;
  100695. v22y = v42y;
  100696. v22z = v42z;
  100697. } else {
  100698. v1x = v4x;
  100699. v1y = v4y;
  100700. v1z = v4z;
  100701. v11x = v41x;
  100702. v11y = v41y;
  100703. v11z = v41z;
  100704. v12x = v42x;
  100705. v12y = v42y;
  100706. v12z = v42z;
  100707. }
  100708. }
  100709. }
  100710. }
  100711. //return false;
  100712. };
  100713. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100714. var rot = c.rotation.elements;
  100715. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100716. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100717. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100718. var w = c.halfWidth;
  100719. var h = c.halfHeight;
  100720. var d = c.halfDepth;
  100721. var ox;
  100722. var oy;
  100723. var oz;
  100724. if (ldx < 0) ox = -w;
  100725. else ox = w;
  100726. if (ldy < 0) oy = -h;
  100727. else oy = h;
  100728. if (ldz < 0) oz = -d;
  100729. else oz = d;
  100730. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100731. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100732. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100733. out.init(ldx, ldy, ldz);
  100734. };
  100735. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100736. var rot = c.rotation.elements;
  100737. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100738. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100739. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100740. var radx = ldx;
  100741. var radz = ldz;
  100742. var len = radx * radx + radz * radz;
  100743. var rad = c.radius;
  100744. var hh = c.halfHeight;
  100745. var ox;
  100746. var oy;
  100747. var oz;
  100748. if (len == 0) {
  100749. if (ldy < 0) {
  100750. ox = rad;
  100751. oy = -hh;
  100752. oz = 0;
  100753. } else {
  100754. ox = rad;
  100755. oy = hh;
  100756. oz = 0;
  100757. }
  100758. } else {
  100759. len = c.radius / OIMO.sqrt(len);
  100760. if (ldy < 0) {
  100761. ox = radx * len;
  100762. oy = -hh;
  100763. oz = radz * len;
  100764. } else {
  100765. ox = radx * len;
  100766. oy = hh;
  100767. oz = radz * len;
  100768. }
  100769. }
  100770. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100771. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100772. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100773. out.init(ldx, ldy, ldz);
  100774. };
  100775. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100776. var b;
  100777. var c;
  100778. if (this.flip) {
  100779. b = shape2;
  100780. c = shape1;
  100781. } else {
  100782. b = shape1;
  100783. c = shape2;
  100784. }
  100785. var sep = new OIMO.Vec3();
  100786. var pos = new OIMO.Vec3();
  100787. var dep = new OIMO.Vec3();
  100788. var co;
  100789. if (!this.getSep(b, c, sep, pos, dep)) return;
  100790. var pbx = b.position.x;
  100791. var pby = b.position.y;
  100792. var pbz = b.position.z;
  100793. var pcx = c.position.x;
  100794. var pcy = c.position.y;
  100795. var pcz = c.position.z;
  100796. var bw = b.halfWidth;
  100797. var bh = b.halfHeight;
  100798. var bd = b.halfDepth;
  100799. var ch = c.halfHeight;
  100800. var r = c.radius;
  100801. var D = b.dimentions;
  100802. var nwx = D[0];//b.normalDirectionWidth.x;
  100803. var nwy = D[1];//b.normalDirectionWidth.y;
  100804. var nwz = D[2];//b.normalDirectionWidth.z;
  100805. var nhx = D[3];//b.normalDirectionHeight.x;
  100806. var nhy = D[4];//b.normalDirectionHeight.y;
  100807. var nhz = D[5];//b.normalDirectionHeight.z;
  100808. var ndx = D[6];//b.normalDirectionDepth.x;
  100809. var ndy = D[7];//b.normalDirectionDepth.y;
  100810. var ndz = D[8];//b.normalDirectionDepth.z;
  100811. var dwx = D[9];//b.halfDirectionWidth.x;
  100812. var dwy = D[10];//b.halfDirectionWidth.y;
  100813. var dwz = D[11];//b.halfDirectionWidth.z;
  100814. var dhx = D[12];//b.halfDirectionHeight.x;
  100815. var dhy = D[13];//b.halfDirectionHeight.y;
  100816. var dhz = D[14];//b.halfDirectionHeight.z;
  100817. var ddx = D[15];//b.halfDirectionDepth.x;
  100818. var ddy = D[16];//b.halfDirectionDepth.y;
  100819. var ddz = D[17];//b.halfDirectionDepth.z;
  100820. var ncx = c.normalDirection.x;
  100821. var ncy = c.normalDirection.y;
  100822. var ncz = c.normalDirection.z;
  100823. var dcx = c.halfDirection.x;
  100824. var dcy = c.halfDirection.y;
  100825. var dcz = c.halfDirection.z;
  100826. var nx = sep.x;
  100827. var ny = sep.y;
  100828. var nz = sep.z;
  100829. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100830. var doth = nx * nhx + ny * nhy + nz * nhz;
  100831. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100832. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100833. var right1 = dotw > 0;
  100834. var right2 = doth > 0;
  100835. var right3 = dotd > 0;
  100836. var right4 = dotc > 0;
  100837. if (!right1) dotw = -dotw;
  100838. if (!right2) doth = -doth;
  100839. if (!right3) dotd = -dotd;
  100840. if (!right4) dotc = -dotc;
  100841. var state = 0;
  100842. if (dotc > 0.999) {
  100843. if (dotw > 0.999) {
  100844. if (dotw > dotc) state = 1;
  100845. else state = 4;
  100846. } else if (doth > 0.999) {
  100847. if (doth > dotc) state = 2;
  100848. else state = 4;
  100849. } else if (dotd > 0.999) {
  100850. if (dotd > dotc) state = 3;
  100851. else state = 4;
  100852. } else state = 4;
  100853. } else {
  100854. if (dotw > 0.999) state = 1;
  100855. else if (doth > 0.999) state = 2;
  100856. else if (dotd > 0.999) state = 3;
  100857. }
  100858. var cbx;
  100859. var cby;
  100860. var cbz;
  100861. var ccx;
  100862. var ccy;
  100863. var ccz;
  100864. var r00;
  100865. var r01;
  100866. var r02;
  100867. var r10;
  100868. var r11;
  100869. var r12;
  100870. var r20;
  100871. var r21;
  100872. var r22;
  100873. var px;
  100874. var py;
  100875. var pz;
  100876. var pd;
  100877. var dot;
  100878. var len;
  100879. var tx;
  100880. var ty;
  100881. var tz;
  100882. var td;
  100883. var dx;
  100884. var dy;
  100885. var dz;
  100886. var d1x;
  100887. var d1y;
  100888. var d1z;
  100889. var d2x;
  100890. var d2y;
  100891. var d2z;
  100892. var sx;
  100893. var sy;
  100894. var sz;
  100895. var sd;
  100896. var ex;
  100897. var ey;
  100898. var ez;
  100899. var ed;
  100900. var dot1;
  100901. var dot2;
  100902. var t1;
  100903. var t2;
  100904. var dir1x;
  100905. var dir1y;
  100906. var dir1z;
  100907. var dir2x;
  100908. var dir2y;
  100909. var dir2z;
  100910. var dir1l;
  100911. var dir2l;
  100912. if (state == 0) {
  100913. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  100914. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  100915. } else if (state == 4) {
  100916. if (right4) {
  100917. ccx = pcx - dcx;
  100918. ccy = pcy - dcy;
  100919. ccz = pcz - dcz;
  100920. nx = -ncx;
  100921. ny = -ncy;
  100922. nz = -ncz;
  100923. } else {
  100924. ccx = pcx + dcx;
  100925. ccy = pcy + dcy;
  100926. ccz = pcz + dcz;
  100927. nx = ncx;
  100928. ny = ncy;
  100929. nz = ncz;
  100930. }
  100931. var v1x;
  100932. var v1y;
  100933. var v1z;
  100934. var v2x;
  100935. var v2y;
  100936. var v2z;
  100937. var v3x;
  100938. var v3y;
  100939. var v3z;
  100940. var v4x;
  100941. var v4y;
  100942. var v4z;
  100943. dot = 1;
  100944. state = 0;
  100945. dot1 = nwx * nx + nwy * ny + nwz * nz;
  100946. if (dot1 < dot) {
  100947. dot = dot1;
  100948. state = 0;
  100949. }
  100950. if (-dot1 < dot) {
  100951. dot = -dot1;
  100952. state = 1;
  100953. }
  100954. dot1 = nhx * nx + nhy * ny + nhz * nz;
  100955. if (dot1 < dot) {
  100956. dot = dot1;
  100957. state = 2;
  100958. }
  100959. if (-dot1 < dot) {
  100960. dot = -dot1;
  100961. state = 3;
  100962. }
  100963. dot1 = ndx * nx + ndy * ny + ndz * nz;
  100964. if (dot1 < dot) {
  100965. dot = dot1;
  100966. state = 4;
  100967. }
  100968. if (-dot1 < dot) {
  100969. dot = -dot1;
  100970. state = 5;
  100971. }
  100972. var v = b.elements;
  100973. switch (state) {
  100974. case 0:
  100975. //v=b.vertex1;
  100976. v1x = v[0];//v.x;
  100977. v1y = v[1];//v.y;
  100978. v1z = v[2];//v.z;
  100979. //v=b.vertex3;
  100980. v2x = v[6];//v.x;
  100981. v2y = v[7];//v.y;
  100982. v2z = v[8];//v.z;
  100983. //v=b.vertex4;
  100984. v3x = v[9];//v.x;
  100985. v3y = v[10];//v.y;
  100986. v3z = v[11];//v.z;
  100987. //v=b.vertex2;
  100988. v4x = v[3];//v.x;
  100989. v4y = v[4];//v.y;
  100990. v4z = v[5];//v.z;
  100991. break;
  100992. case 1:
  100993. //v=b.vertex6;
  100994. v1x = v[15];//v.x;
  100995. v1y = v[16];//v.y;
  100996. v1z = v[17];//v.z;
  100997. //v=b.vertex8;
  100998. v2x = v[21];//v.x;
  100999. v2y = v[22];//v.y;
  101000. v2z = v[23];//v.z;
  101001. //v=b.vertex7;
  101002. v3x = v[18];//v.x;
  101003. v3y = v[19];//v.y;
  101004. v3z = v[20];//v.z;
  101005. //v=b.vertex5;
  101006. v4x = v[12];//v.x;
  101007. v4y = v[13];//v.y;
  101008. v4z = v[14];//v.z;
  101009. break;
  101010. case 2:
  101011. //v=b.vertex5;
  101012. v1x = v[12];//v.x;
  101013. v1y = v[13];//v.y;
  101014. v1z = v[14];//v.z;
  101015. //v=b.vertex1;
  101016. v2x = v[0];//v.x;
  101017. v2y = v[1];//v.y;
  101018. v2z = v[2];//v.z;
  101019. //v=b.vertex2;
  101020. v3x = v[3];//v.x;
  101021. v3y = v[4];//v.y;
  101022. v3z = v[5];//v.z;
  101023. //v=b.vertex6;
  101024. v4x = v[15];//v.x;
  101025. v4y = v[16];//v.y;
  101026. v4z = v[17];//v.z;
  101027. break;
  101028. case 3:
  101029. //v=b.vertex8;
  101030. v1x = v[21];//v.x;
  101031. v1y = v[22];//v.y;
  101032. v1z = v[23];//v.z;
  101033. //v=b.vertex4;
  101034. v2x = v[9];//v.x;
  101035. v2y = v[10];//v.y;
  101036. v2z = v[11];//v.z;
  101037. //v=b.vertex3;
  101038. v3x = v[6];//v.x;
  101039. v3y = v[7];//v.y;
  101040. v3z = v[8];//v.z;
  101041. //v=b.vertex7;
  101042. v4x = v[18];//v.x;
  101043. v4y = v[19];//v.y;
  101044. v4z = v[20];//v.z;
  101045. break;
  101046. case 4:
  101047. //v=b.vertex5;
  101048. v1x = v[12];//v.x;
  101049. v1y = v[13];//v.y;
  101050. v1z = v[14];//v.z;
  101051. //v=b.vertex7;
  101052. v2x = v[18];//v.x;
  101053. v2y = v[19];//v.y;
  101054. v2z = v[20];//v.z;
  101055. //v=b.vertex3;
  101056. v3x = v[6];//v.x;
  101057. v3y = v[7];//v.y;
  101058. v3z = v[8];//v.z;
  101059. //v=b.vertex1;
  101060. v4x = v[0];//v.x;
  101061. v4y = v[1];//v.y;
  101062. v4z = v[2];//v.z;
  101063. break;
  101064. case 5:
  101065. //v=b.vertex2;
  101066. v1x = v[3];//v.x;
  101067. v1y = v[4];//v.y;
  101068. v1z = v[5];//v.z;
  101069. //v=b.vertex4;
  101070. v2x = v[9];//v.x;
  101071. v2y = v[10];//v.y;
  101072. v2z = v[11];//v.z;
  101073. //v=b.vertex8;
  101074. v3x = v[21];//v.x;
  101075. v3y = v[22];//v.y;
  101076. v3z = v[23];//v.z;
  101077. //v=b.vertex6;
  101078. v4x = v[15];//v.x;
  101079. v4y = v[16];//v.y;
  101080. v4z = v[17];//v.z;
  101081. break;
  101082. }
  101083. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101084. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101085. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101086. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101087. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101088. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101089. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101090. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101091. } else {
  101092. switch (state) {
  101093. case 1:
  101094. if (right1) {
  101095. cbx = pbx + dwx;
  101096. cby = pby + dwy;
  101097. cbz = pbz + dwz;
  101098. nx = nwx;
  101099. ny = nwy;
  101100. nz = nwz;
  101101. } else {
  101102. cbx = pbx - dwx;
  101103. cby = pby - dwy;
  101104. cbz = pbz - dwz;
  101105. nx = -nwx;
  101106. ny = -nwy;
  101107. nz = -nwz;
  101108. }
  101109. dir1x = nhx;
  101110. dir1y = nhy;
  101111. dir1z = nhz;
  101112. dir1l = bh;
  101113. dir2x = ndx;
  101114. dir2y = ndy;
  101115. dir2z = ndz;
  101116. dir2l = bd;
  101117. break;
  101118. case 2:
  101119. if (right2) {
  101120. cbx = pbx + dhx;
  101121. cby = pby + dhy;
  101122. cbz = pbz + dhz;
  101123. nx = nhx;
  101124. ny = nhy;
  101125. nz = nhz;
  101126. } else {
  101127. cbx = pbx - dhx;
  101128. cby = pby - dhy;
  101129. cbz = pbz - dhz;
  101130. nx = -nhx;
  101131. ny = -nhy;
  101132. nz = -nhz;
  101133. }
  101134. dir1x = nwx;
  101135. dir1y = nwy;
  101136. dir1z = nwz;
  101137. dir1l = bw;
  101138. dir2x = ndx;
  101139. dir2y = ndy;
  101140. dir2z = ndz;
  101141. dir2l = bd;
  101142. break;
  101143. case 3:
  101144. if (right3) {
  101145. cbx = pbx + ddx;
  101146. cby = pby + ddy;
  101147. cbz = pbz + ddz;
  101148. nx = ndx;
  101149. ny = ndy;
  101150. nz = ndz;
  101151. } else {
  101152. cbx = pbx - ddx;
  101153. cby = pby - ddy;
  101154. cbz = pbz - ddz;
  101155. nx = -ndx;
  101156. ny = -ndy;
  101157. nz = -ndz;
  101158. }
  101159. dir1x = nwx;
  101160. dir1y = nwy;
  101161. dir1z = nwz;
  101162. dir1l = bw;
  101163. dir2x = nhx;
  101164. dir2y = nhy;
  101165. dir2z = nhz;
  101166. dir2l = bh;
  101167. break;
  101168. }
  101169. dot = nx * ncx + ny * ncy + nz * ncz;
  101170. if (dot < 0) len = ch;
  101171. else len = -ch;
  101172. ccx = pcx + len * ncx;
  101173. ccy = pcy + len * ncy;
  101174. ccz = pcz + len * ncz;
  101175. if (dotc >= 0.999999) {
  101176. tx = -ny;
  101177. ty = nz;
  101178. tz = nx;
  101179. } else {
  101180. tx = nx;
  101181. ty = ny;
  101182. tz = nz;
  101183. }
  101184. len = tx * ncx + ty * ncy + tz * ncz;
  101185. dx = len * ncx - tx;
  101186. dy = len * ncy - ty;
  101187. dz = len * ncz - tz;
  101188. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101189. if (len == 0) return;
  101190. len = r / len;
  101191. dx *= len;
  101192. dy *= len;
  101193. dz *= len;
  101194. tx = ccx + dx;
  101195. ty = ccy + dy;
  101196. tz = ccz + dz;
  101197. if (dot < -0.96 || dot > 0.96) {
  101198. r00 = ncx * ncx * 1.5 - 0.5;
  101199. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101200. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101201. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101202. r11 = ncy * ncy * 1.5 - 0.5;
  101203. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101204. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101205. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101206. r22 = ncz * ncz * 1.5 - 0.5;
  101207. px = tx;
  101208. py = ty;
  101209. pz = tz;
  101210. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101211. tx = px - pd * nx - cbx;
  101212. ty = py - pd * ny - cby;
  101213. tz = pz - pd * nz - cbz;
  101214. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101215. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101216. if (sd < -dir1l) sd = -dir1l;
  101217. else if (sd > dir1l) sd = dir1l;
  101218. if (ed < -dir2l) ed = -dir2l;
  101219. else if (ed > dir2l) ed = dir2l;
  101220. tx = sd * dir1x + ed * dir2x;
  101221. ty = sd * dir1y + ed * dir2y;
  101222. tz = sd * dir1z + ed * dir2z;
  101223. px = cbx + tx;
  101224. py = cby + ty;
  101225. pz = cbz + tz;
  101226. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101227. px = dx * r00 + dy * r01 + dz * r02;
  101228. py = dx * r10 + dy * r11 + dz * r12;
  101229. pz = dx * r20 + dy * r21 + dz * r22;
  101230. px = (dx = px) + ccx;
  101231. py = (dy = py) + ccy;
  101232. pz = (dz = pz) + ccz;
  101233. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101234. if (pd <= 0) {
  101235. tx = px - pd * nx - cbx;
  101236. ty = py - pd * ny - cby;
  101237. tz = pz - pd * nz - cbz;
  101238. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101239. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101240. if (sd < -dir1l) sd = -dir1l;
  101241. else if (sd > dir1l) sd = dir1l;
  101242. if (ed < -dir2l) ed = -dir2l;
  101243. else if (ed > dir2l) ed = dir2l;
  101244. tx = sd * dir1x + ed * dir2x;
  101245. ty = sd * dir1y + ed * dir2y;
  101246. tz = sd * dir1z + ed * dir2z;
  101247. px = cbx + tx;
  101248. py = cby + ty;
  101249. pz = cbz + tz;
  101250. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101251. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101252. }
  101253. px = dx * r00 + dy * r01 + dz * r02;
  101254. py = dx * r10 + dy * r11 + dz * r12;
  101255. pz = dx * r20 + dy * r21 + dz * r22;
  101256. px = (dx = px) + ccx;
  101257. py = (dy = py) + ccy;
  101258. pz = (dz = pz) + ccz;
  101259. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101260. if (pd <= 0) {
  101261. tx = px - pd * nx - cbx;
  101262. ty = py - pd * ny - cby;
  101263. tz = pz - pd * nz - cbz;
  101264. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101265. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101266. if (sd < -dir1l) sd = -dir1l;
  101267. else if (sd > dir1l) sd = dir1l;
  101268. if (ed < -dir2l) ed = -dir2l;
  101269. else if (ed > dir2l) ed = dir2l;
  101270. tx = sd * dir1x + ed * dir2x;
  101271. ty = sd * dir1y + ed * dir2y;
  101272. tz = sd * dir1z + ed * dir2z;
  101273. px = cbx + tx;
  101274. py = cby + ty;
  101275. pz = cbz + tz;
  101276. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101277. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101278. }
  101279. } else {
  101280. sx = tx;
  101281. sy = ty;
  101282. sz = tz;
  101283. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101284. sx -= sd * nx;
  101285. sy -= sd * ny;
  101286. sz -= sd * nz;
  101287. if (dot > 0) {
  101288. ex = tx + dcx * 2;
  101289. ey = ty + dcy * 2;
  101290. ez = tz + dcz * 2;
  101291. } else {
  101292. ex = tx - dcx * 2;
  101293. ey = ty - dcy * 2;
  101294. ez = tz - dcz * 2;
  101295. }
  101296. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101297. ex -= ed * nx;
  101298. ey -= ed * ny;
  101299. ez -= ed * nz;
  101300. d1x = sx - cbx;
  101301. d1y = sy - cby;
  101302. d1z = sz - cbz;
  101303. d2x = ex - cbx;
  101304. d2y = ey - cby;
  101305. d2z = ez - cbz;
  101306. tx = ex - sx;
  101307. ty = ey - sy;
  101308. tz = ez - sz;
  101309. td = ed - sd;
  101310. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101311. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101312. dot1 = dotw - dir1l;
  101313. dot2 = doth - dir1l;
  101314. if (dot1 > 0) {
  101315. if (dot2 > 0) return;
  101316. t1 = dot1 / (dot1 - dot2);
  101317. sx = sx + tx * t1;
  101318. sy = sy + ty * t1;
  101319. sz = sz + tz * t1;
  101320. sd = sd + td * t1;
  101321. d1x = sx - cbx;
  101322. d1y = sy - cby;
  101323. d1z = sz - cbz;
  101324. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101325. tx = ex - sx;
  101326. ty = ey - sy;
  101327. tz = ez - sz;
  101328. td = ed - sd;
  101329. } else if (dot2 > 0) {
  101330. t1 = dot1 / (dot1 - dot2);
  101331. ex = sx + tx * t1;
  101332. ey = sy + ty * t1;
  101333. ez = sz + tz * t1;
  101334. ed = sd + td * t1;
  101335. d2x = ex - cbx;
  101336. d2y = ey - cby;
  101337. d2z = ez - cbz;
  101338. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101339. tx = ex - sx;
  101340. ty = ey - sy;
  101341. tz = ez - sz;
  101342. td = ed - sd;
  101343. }
  101344. dot1 = dotw + dir1l;
  101345. dot2 = doth + dir1l;
  101346. if (dot1 < 0) {
  101347. if (dot2 < 0) return;
  101348. t1 = dot1 / (dot1 - dot2);
  101349. sx = sx + tx * t1;
  101350. sy = sy + ty * t1;
  101351. sz = sz + tz * t1;
  101352. sd = sd + td * t1;
  101353. d1x = sx - cbx;
  101354. d1y = sy - cby;
  101355. d1z = sz - cbz;
  101356. tx = ex - sx;
  101357. ty = ey - sy;
  101358. tz = ez - sz;
  101359. td = ed - sd;
  101360. } else if (dot2 < 0) {
  101361. t1 = dot1 / (dot1 - dot2);
  101362. ex = sx + tx * t1;
  101363. ey = sy + ty * t1;
  101364. ez = sz + tz * t1;
  101365. ed = sd + td * t1;
  101366. d2x = ex - cbx;
  101367. d2y = ey - cby;
  101368. d2z = ez - cbz;
  101369. tx = ex - sx;
  101370. ty = ey - sy;
  101371. tz = ez - sz;
  101372. td = ed - sd;
  101373. }
  101374. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101375. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101376. dot1 = dotw - dir2l;
  101377. dot2 = doth - dir2l;
  101378. if (dot1 > 0) {
  101379. if (dot2 > 0) return;
  101380. t1 = dot1 / (dot1 - dot2);
  101381. sx = sx + tx * t1;
  101382. sy = sy + ty * t1;
  101383. sz = sz + tz * t1;
  101384. sd = sd + td * t1;
  101385. d1x = sx - cbx;
  101386. d1y = sy - cby;
  101387. d1z = sz - cbz;
  101388. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101389. tx = ex - sx;
  101390. ty = ey - sy;
  101391. tz = ez - sz;
  101392. td = ed - sd;
  101393. } else if (dot2 > 0) {
  101394. t1 = dot1 / (dot1 - dot2);
  101395. ex = sx + tx * t1;
  101396. ey = sy + ty * t1;
  101397. ez = sz + tz * t1;
  101398. ed = sd + td * t1;
  101399. d2x = ex - cbx;
  101400. d2y = ey - cby;
  101401. d2z = ez - cbz;
  101402. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101403. tx = ex - sx;
  101404. ty = ey - sy;
  101405. tz = ez - sz;
  101406. td = ed - sd;
  101407. }
  101408. dot1 = dotw + dir2l;
  101409. dot2 = doth + dir2l;
  101410. if (dot1 < 0) {
  101411. if (dot2 < 0) return;
  101412. t1 = dot1 / (dot1 - dot2);
  101413. sx = sx + tx * t1;
  101414. sy = sy + ty * t1;
  101415. sz = sz + tz * t1;
  101416. sd = sd + td * t1;
  101417. } else if (dot2 < 0) {
  101418. t1 = dot1 / (dot1 - dot2);
  101419. ex = sx + tx * t1;
  101420. ey = sy + ty * t1;
  101421. ez = sz + tz * t1;
  101422. ed = sd + td * t1;
  101423. }
  101424. if (sd < 0) {
  101425. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101426. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101427. }
  101428. if (ed < 0) {
  101429. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101430. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101431. }
  101432. }
  101433. }
  101434. };
  101435. OIMO.CylinderCylinderCollisionDetector = function () {
  101436. OIMO.CollisionDetector.call(this);
  101437. };
  101438. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101439. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101440. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101441. var t1x;
  101442. var t1y;
  101443. var t1z;
  101444. var t2x;
  101445. var t2y;
  101446. var t2z;
  101447. var sup = new OIMO.Vec3();
  101448. var len;
  101449. var p1x;
  101450. var p1y;
  101451. var p1z;
  101452. var p2x;
  101453. var p2y;
  101454. var p2z;
  101455. var v01x = c1.position.x;
  101456. var v01y = c1.position.y;
  101457. var v01z = c1.position.z;
  101458. var v02x = c2.position.x;
  101459. var v02y = c2.position.y;
  101460. var v02z = c2.position.z;
  101461. var v0x = v02x - v01x;
  101462. var v0y = v02y - v01y;
  101463. var v0z = v02z - v01z;
  101464. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101465. var nx = -v0x;
  101466. var ny = -v0y;
  101467. var nz = -v0z;
  101468. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101469. var v11x = sup.x;
  101470. var v11y = sup.y;
  101471. var v11z = sup.z;
  101472. this.supportPoint(c2, nx, ny, nz, sup);
  101473. var v12x = sup.x;
  101474. var v12y = sup.y;
  101475. var v12z = sup.z;
  101476. var v1x = v12x - v11x;
  101477. var v1y = v12y - v11y;
  101478. var v1z = v12z - v11z;
  101479. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101480. return false;
  101481. }
  101482. nx = v1y * v0z - v1z * v0y;
  101483. ny = v1z * v0x - v1x * v0z;
  101484. nz = v1x * v0y - v1y * v0x;
  101485. if (nx * nx + ny * ny + nz * nz == 0) {
  101486. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101487. sep.normalize(sep);
  101488. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101489. return true;
  101490. }
  101491. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101492. var v21x = sup.x;
  101493. var v21y = sup.y;
  101494. var v21z = sup.z;
  101495. this.supportPoint(c2, nx, ny, nz, sup);
  101496. var v22x = sup.x;
  101497. var v22y = sup.y;
  101498. var v22z = sup.z;
  101499. var v2x = v22x - v21x;
  101500. var v2y = v22y - v21y;
  101501. var v2z = v22z - v21z;
  101502. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101503. return false;
  101504. }
  101505. t1x = v1x - v0x;
  101506. t1y = v1y - v0y;
  101507. t1z = v1z - v0z;
  101508. t2x = v2x - v0x;
  101509. t2y = v2y - v0y;
  101510. t2z = v2z - v0z;
  101511. nx = t1y * t2z - t1z * t2y;
  101512. ny = t1z * t2x - t1x * t2z;
  101513. nz = t1x * t2y - t1y * t2x;
  101514. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101515. t1x = v1x;
  101516. t1y = v1y;
  101517. t1z = v1z;
  101518. v1x = v2x;
  101519. v1y = v2y;
  101520. v1z = v2z;
  101521. v2x = t1x;
  101522. v2y = t1y;
  101523. v2z = t1z;
  101524. t1x = v11x;
  101525. t1y = v11y;
  101526. t1z = v11z;
  101527. v11x = v21x;
  101528. v11y = v21y;
  101529. v11z = v21z;
  101530. v21x = t1x;
  101531. v21y = t1y;
  101532. v21z = t1z;
  101533. t1x = v12x;
  101534. t1y = v12y;
  101535. t1z = v12z;
  101536. v12x = v22x;
  101537. v12y = v22y;
  101538. v12z = v22z;
  101539. v22x = t1x;
  101540. v22y = t1y;
  101541. v22z = t1z;
  101542. nx = -nx;
  101543. ny = -ny;
  101544. nz = -nz;
  101545. }
  101546. var iterations = 0;
  101547. while (true) {
  101548. if (++iterations > 100) {
  101549. return false;
  101550. }
  101551. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101552. var v31x = sup.x;
  101553. var v31y = sup.y;
  101554. var v31z = sup.z;
  101555. this.supportPoint(c2, nx, ny, nz, sup);
  101556. var v32x = sup.x;
  101557. var v32y = sup.y;
  101558. var v32z = sup.z;
  101559. var v3x = v32x - v31x;
  101560. var v3y = v32y - v31y;
  101561. var v3z = v32z - v31z;
  101562. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101563. return false;
  101564. }
  101565. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101566. v2x = v3x;
  101567. v2y = v3y;
  101568. v2z = v3z;
  101569. v21x = v31x;
  101570. v21y = v31y;
  101571. v21z = v31z;
  101572. v22x = v32x;
  101573. v22y = v32y;
  101574. v22z = v32z;
  101575. t1x = v1x - v0x;
  101576. t1y = v1y - v0y;
  101577. t1z = v1z - v0z;
  101578. t2x = v3x - v0x;
  101579. t2y = v3y - v0y;
  101580. t2z = v3z - v0z;
  101581. nx = t1y * t2z - t1z * t2y;
  101582. ny = t1z * t2x - t1x * t2z;
  101583. nz = t1x * t2y - t1y * t2x;
  101584. continue;
  101585. }
  101586. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101587. v1x = v3x;
  101588. v1y = v3y;
  101589. v1z = v3z;
  101590. v11x = v31x;
  101591. v11y = v31y;
  101592. v11z = v31z;
  101593. v12x = v32x;
  101594. v12y = v32y;
  101595. v12z = v32z;
  101596. t1x = v3x - v0x;
  101597. t1y = v3y - v0y;
  101598. t1z = v3z - v0z;
  101599. t2x = v2x - v0x;
  101600. t2y = v2y - v0y;
  101601. t2z = v2z - v0z;
  101602. nx = t1y * t2z - t1z * t2y;
  101603. ny = t1z * t2x - t1x * t2z;
  101604. nz = t1x * t2y - t1y * t2x;
  101605. continue;
  101606. }
  101607. var hit = false;
  101608. while (true) {
  101609. t1x = v2x - v1x;
  101610. t1y = v2y - v1y;
  101611. t1z = v2z - v1z;
  101612. t2x = v3x - v1x;
  101613. t2y = v3y - v1y;
  101614. t2z = v3z - v1z;
  101615. nx = t1y * t2z - t1z * t2y;
  101616. ny = t1z * t2x - t1x * t2z;
  101617. nz = t1x * t2y - t1y * t2x;
  101618. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101619. nx *= len;
  101620. ny *= len;
  101621. nz *= len;
  101622. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101623. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101624. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101625. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101626. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101627. var sum = b0 + b1 + b2 + b3;
  101628. if (sum <= 0) {
  101629. b0 = 0;
  101630. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101631. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101632. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101633. sum = b1 + b2 + b3;
  101634. }
  101635. var inv = 1 / sum;
  101636. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101637. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101638. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101639. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101640. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101641. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101642. hit = true;
  101643. }
  101644. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101645. var v41x = sup.x;
  101646. var v41y = sup.y;
  101647. var v41z = sup.z;
  101648. this.supportPoint(c2, nx, ny, nz, sup);
  101649. var v42x = sup.x;
  101650. var v42y = sup.y;
  101651. var v42z = sup.z;
  101652. var v4x = v42x - v41x;
  101653. var v4y = v42y - v41y;
  101654. var v4z = v42z - v41z;
  101655. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101656. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101657. if (hit) {
  101658. sep.init(-nx, -ny, -nz);
  101659. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101660. dep.x = separation;
  101661. return true;
  101662. }
  101663. return false;
  101664. }
  101665. if (
  101666. (v4y * v1z - v4z * v1y) * v0x +
  101667. (v4z * v1x - v4x * v1z) * v0y +
  101668. (v4x * v1y - v4y * v1x) * v0z < 0
  101669. ) {
  101670. if (
  101671. (v4y * v2z - v4z * v2y) * v0x +
  101672. (v4z * v2x - v4x * v2z) * v0y +
  101673. (v4x * v2y - v4y * v2x) * v0z < 0
  101674. ) {
  101675. v1x = v4x;
  101676. v1y = v4y;
  101677. v1z = v4z;
  101678. v11x = v41x;
  101679. v11y = v41y;
  101680. v11z = v41z;
  101681. v12x = v42x;
  101682. v12y = v42y;
  101683. v12z = v42z;
  101684. } else {
  101685. v3x = v4x;
  101686. v3y = v4y;
  101687. v3z = v4z;
  101688. v31x = v41x;
  101689. v31y = v41y;
  101690. v31z = v41z;
  101691. v32x = v42x;
  101692. v32y = v42y;
  101693. v32z = v42z;
  101694. }
  101695. } else {
  101696. if (
  101697. (v4y * v3z - v4z * v3y) * v0x +
  101698. (v4z * v3x - v4x * v3z) * v0y +
  101699. (v4x * v3y - v4y * v3x) * v0z < 0
  101700. ) {
  101701. v2x = v4x;
  101702. v2y = v4y;
  101703. v2z = v4z;
  101704. v21x = v41x;
  101705. v21y = v41y;
  101706. v21z = v41z;
  101707. v22x = v42x;
  101708. v22y = v42y;
  101709. v22z = v42z;
  101710. } else {
  101711. v1x = v4x;
  101712. v1y = v4y;
  101713. v1z = v4z;
  101714. v11x = v41x;
  101715. v11y = v41y;
  101716. v11z = v41z;
  101717. v12x = v42x;
  101718. v12y = v42y;
  101719. v12z = v42z;
  101720. }
  101721. }
  101722. }
  101723. }
  101724. //return false;
  101725. };
  101726. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101727. var rot = c.rotation.elements;
  101728. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101729. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101730. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101731. var radx = ldx;
  101732. var radz = ldz;
  101733. var len = radx * radx + radz * radz;
  101734. var rad = c.radius;
  101735. var hh = c.halfHeight;
  101736. var ox;
  101737. var oy;
  101738. var oz;
  101739. if (len == 0) {
  101740. if (ldy < 0) {
  101741. ox = rad;
  101742. oy = -hh;
  101743. oz = 0;
  101744. } else {
  101745. ox = rad;
  101746. oy = hh;
  101747. oz = 0;
  101748. }
  101749. } else {
  101750. len = c.radius / OIMO.sqrt(len);
  101751. if (ldy < 0) {
  101752. ox = radx * len;
  101753. oy = -hh;
  101754. oz = radz * len;
  101755. } else {
  101756. ox = radx * len;
  101757. oy = hh;
  101758. oz = radz * len;
  101759. }
  101760. }
  101761. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101762. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101763. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101764. out.init(ldx, ldy, ldz);
  101765. };
  101766. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101767. var c1;
  101768. var c2;
  101769. if (shape1.id < shape2.id) {
  101770. c1 = shape1;
  101771. c2 = shape2;
  101772. } else {
  101773. c1 = shape2;
  101774. c2 = shape1;
  101775. }
  101776. var p1 = c1.position;
  101777. var p2 = c2.position;
  101778. var p1x = p1.x;
  101779. var p1y = p1.y;
  101780. var p1z = p1.z;
  101781. var p2x = p2.x;
  101782. var p2y = p2.y;
  101783. var p2z = p2.z;
  101784. var h1 = c1.halfHeight;
  101785. var h2 = c2.halfHeight;
  101786. var n1 = c1.normalDirection;
  101787. var n2 = c2.normalDirection;
  101788. var d1 = c1.halfDirection;
  101789. var d2 = c2.halfDirection;
  101790. var r1 = c1.radius;
  101791. var r2 = c2.radius;
  101792. var n1x = n1.x;
  101793. var n1y = n1.y;
  101794. var n1z = n1.z;
  101795. var n2x = n2.x;
  101796. var n2y = n2.y;
  101797. var n2z = n2.z;
  101798. var d1x = d1.x;
  101799. var d1y = d1.y;
  101800. var d1z = d1.z;
  101801. var d2x = d2.x;
  101802. var d2y = d2.y;
  101803. var d2z = d2.z;
  101804. var dx = p1x - p2x;
  101805. var dy = p1y - p2y;
  101806. var dz = p1z - p2z;
  101807. var len;
  101808. var len1;
  101809. var len2;
  101810. var c;
  101811. var c1x;
  101812. var c1y;
  101813. var c1z;
  101814. var c2x;
  101815. var c2y;
  101816. var c2z;
  101817. var tx;
  101818. var ty;
  101819. var tz;
  101820. var sx;
  101821. var sy;
  101822. var sz;
  101823. var ex;
  101824. var ey;
  101825. var ez;
  101826. var depth1;
  101827. var depth2;
  101828. var dot;
  101829. var t1;
  101830. var t2;
  101831. var sep = new OIMO.Vec3();
  101832. var pos = new OIMO.Vec3();
  101833. var dep = new OIMO.Vec3();
  101834. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101835. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101836. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101837. var right1 = dot1 > 0;
  101838. var right2 = dot2 > 0;
  101839. if (!right1) dot1 = -dot1;
  101840. if (!right2) dot2 = -dot2;
  101841. var state = 0;
  101842. if (dot1 > 0.999 || dot2 > 0.999) {
  101843. if (dot1 > dot2) state = 1;
  101844. else state = 2;
  101845. }
  101846. var nx;
  101847. var ny;
  101848. var nz;
  101849. var depth = dep.x;
  101850. var r00;
  101851. var r01;
  101852. var r02;
  101853. var r10;
  101854. var r11;
  101855. var r12;
  101856. var r20;
  101857. var r21;
  101858. var r22;
  101859. var px;
  101860. var py;
  101861. var pz;
  101862. var pd;
  101863. var a;
  101864. var b;
  101865. var e;
  101866. var f;
  101867. nx = sep.x;
  101868. ny = sep.y;
  101869. nz = sep.z;
  101870. switch (state) {
  101871. case 0:
  101872. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  101873. break;
  101874. case 1:
  101875. if (right1) {
  101876. c1x = p1x + d1x;
  101877. c1y = p1y + d1y;
  101878. c1z = p1z + d1z;
  101879. nx = n1x;
  101880. ny = n1y;
  101881. nz = n1z;
  101882. } else {
  101883. c1x = p1x - d1x;
  101884. c1y = p1y - d1y;
  101885. c1z = p1z - d1z;
  101886. nx = -n1x;
  101887. ny = -n1y;
  101888. nz = -n1z;
  101889. }
  101890. dot = nx * n2x + ny * n2y + nz * n2z;
  101891. if (dot < 0) len = h2;
  101892. else len = -h2;
  101893. c2x = p2x + len * n2x;
  101894. c2y = p2y + len * n2y;
  101895. c2z = p2z + len * n2z;
  101896. if (dot2 >= 0.999999) {
  101897. tx = -ny;
  101898. ty = nz;
  101899. tz = nx;
  101900. } else {
  101901. tx = nx;
  101902. ty = ny;
  101903. tz = nz;
  101904. }
  101905. len = tx * n2x + ty * n2y + tz * n2z;
  101906. dx = len * n2x - tx;
  101907. dy = len * n2y - ty;
  101908. dz = len * n2z - tz;
  101909. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101910. if (len == 0) break;
  101911. len = r2 / len;
  101912. dx *= len;
  101913. dy *= len;
  101914. dz *= len;
  101915. tx = c2x + dx;
  101916. ty = c2y + dy;
  101917. tz = c2z + dz;
  101918. if (dot < -0.96 || dot > 0.96) {
  101919. r00 = n2x * n2x * 1.5 - 0.5;
  101920. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  101921. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  101922. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  101923. r11 = n2y * n2y * 1.5 - 0.5;
  101924. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  101925. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  101926. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  101927. r22 = n2z * n2z * 1.5 - 0.5;
  101928. px = tx;
  101929. py = ty;
  101930. pz = tz;
  101931. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101932. tx = px - pd * nx - c1x;
  101933. ty = py - pd * ny - c1y;
  101934. tz = pz - pd * nz - c1z;
  101935. len = tx * tx + ty * ty + tz * tz;
  101936. if (len > r1 * r1) {
  101937. len = r1 / OIMO.sqrt(len);
  101938. tx *= len;
  101939. ty *= len;
  101940. tz *= len;
  101941. }
  101942. px = c1x + tx;
  101943. py = c1y + ty;
  101944. pz = c1z + tz;
  101945. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101946. px = dx * r00 + dy * r01 + dz * r02;
  101947. py = dx * r10 + dy * r11 + dz * r12;
  101948. pz = dx * r20 + dy * r21 + dz * r22;
  101949. px = (dx = px) + c2x;
  101950. py = (dy = py) + c2y;
  101951. pz = (dz = pz) + c2z;
  101952. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101953. if (pd <= 0) {
  101954. tx = px - pd * nx - c1x;
  101955. ty = py - pd * ny - c1y;
  101956. tz = pz - pd * nz - c1z;
  101957. len = tx * tx + ty * ty + tz * tz;
  101958. if (len > r1 * r1) {
  101959. len = r1 / OIMO.sqrt(len);
  101960. tx *= len;
  101961. ty *= len;
  101962. tz *= len;
  101963. }
  101964. px = c1x + tx;
  101965. py = c1y + ty;
  101966. pz = c1z + tz;
  101967. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101968. }
  101969. px = dx * r00 + dy * r01 + dz * r02;
  101970. py = dx * r10 + dy * r11 + dz * r12;
  101971. pz = dx * r20 + dy * r21 + dz * r22;
  101972. px = (dx = px) + c2x;
  101973. py = (dy = py) + c2y;
  101974. pz = (dz = pz) + c2z;
  101975. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101976. if (pd <= 0) {
  101977. tx = px - pd * nx - c1x;
  101978. ty = py - pd * ny - c1y;
  101979. tz = pz - pd * nz - c1z;
  101980. len = tx * tx + ty * ty + tz * tz;
  101981. if (len > r1 * r1) {
  101982. len = r1 / OIMO.sqrt(len);
  101983. tx *= len;
  101984. ty *= len;
  101985. tz *= len;
  101986. }
  101987. px = c1x + tx;
  101988. py = c1y + ty;
  101989. pz = c1z + tz;
  101990. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101991. }
  101992. } else {
  101993. sx = tx;
  101994. sy = ty;
  101995. sz = tz;
  101996. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  101997. sx -= depth1 * nx;
  101998. sy -= depth1 * ny;
  101999. sz -= depth1 * nz;
  102000. if (dot > 0) {
  102001. ex = tx + n2x * h2 * 2;
  102002. ey = ty + n2y * h2 * 2;
  102003. ez = tz + n2z * h2 * 2;
  102004. } else {
  102005. ex = tx - n2x * h2 * 2;
  102006. ey = ty - n2y * h2 * 2;
  102007. ez = tz - n2z * h2 * 2;
  102008. }
  102009. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102010. ex -= depth2 * nx;
  102011. ey -= depth2 * ny;
  102012. ez -= depth2 * nz;
  102013. dx = c1x - sx;
  102014. dy = c1y - sy;
  102015. dz = c1z - sz;
  102016. tx = ex - sx;
  102017. ty = ey - sy;
  102018. tz = ez - sz;
  102019. a = dx * dx + dy * dy + dz * dz;
  102020. b = dx * tx + dy * ty + dz * tz;
  102021. e = tx * tx + ty * ty + tz * tz;
  102022. f = b * b - e * (a - r1 * r1);
  102023. if (f < 0) break;
  102024. f = OIMO.sqrt(f);
  102025. t1 = (b + f) / e;
  102026. t2 = (b - f) / e;
  102027. if (t2 < t1) {
  102028. len = t1;
  102029. t1 = t2;
  102030. t2 = len;
  102031. }
  102032. if (t2 > 1) t2 = 1;
  102033. if (t1 < 0) t1 = 0;
  102034. tx = sx + (ex - sx) * t1;
  102035. ty = sy + (ey - sy) * t1;
  102036. tz = sz + (ez - sz) * t1;
  102037. ex = sx + (ex - sx) * t2;
  102038. ey = sy + (ey - sy) * t2;
  102039. ez = sz + (ez - sz) * t2;
  102040. sx = tx;
  102041. sy = ty;
  102042. sz = tz;
  102043. len = depth1 + (depth2 - depth1) * t1;
  102044. depth2 = depth1 + (depth2 - depth1) * t2;
  102045. depth1 = len;
  102046. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102047. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102048. }
  102049. break;
  102050. case 2:
  102051. if (right2) {
  102052. c2x = p2x - d2x;
  102053. c2y = p2y - d2y;
  102054. c2z = p2z - d2z;
  102055. nx = -n2x;
  102056. ny = -n2y;
  102057. nz = -n2z;
  102058. } else {
  102059. c2x = p2x + d2x;
  102060. c2y = p2y + d2y;
  102061. c2z = p2z + d2z;
  102062. nx = n2x;
  102063. ny = n2y;
  102064. nz = n2z;
  102065. }
  102066. dot = nx * n1x + ny * n1y + nz * n1z;
  102067. if (dot < 0) len = h1;
  102068. else len = -h1;
  102069. c1x = p1x + len * n1x;
  102070. c1y = p1y + len * n1y;
  102071. c1z = p1z + len * n1z;
  102072. if (dot1 >= 0.999999) {
  102073. tx = -ny;
  102074. ty = nz;
  102075. tz = nx;
  102076. } else {
  102077. tx = nx;
  102078. ty = ny;
  102079. tz = nz;
  102080. }
  102081. len = tx * n1x + ty * n1y + tz * n1z;
  102082. dx = len * n1x - tx;
  102083. dy = len * n1y - ty;
  102084. dz = len * n1z - tz;
  102085. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102086. if (len == 0) break;
  102087. len = r1 / len;
  102088. dx *= len;
  102089. dy *= len;
  102090. dz *= len;
  102091. tx = c1x + dx;
  102092. ty = c1y + dy;
  102093. tz = c1z + dz;
  102094. if (dot < -0.96 || dot > 0.96) {
  102095. r00 = n1x * n1x * 1.5 - 0.5;
  102096. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102097. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102098. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102099. r11 = n1y * n1y * 1.5 - 0.5;
  102100. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102101. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102102. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102103. r22 = n1z * n1z * 1.5 - 0.5;
  102104. px = tx;
  102105. py = ty;
  102106. pz = tz;
  102107. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102108. tx = px - pd * nx - c2x;
  102109. ty = py - pd * ny - c2y;
  102110. tz = pz - pd * nz - c2z;
  102111. len = tx * tx + ty * ty + tz * tz;
  102112. if (len > r2 * r2) {
  102113. len = r2 / OIMO.sqrt(len);
  102114. tx *= len;
  102115. ty *= len;
  102116. tz *= len;
  102117. }
  102118. px = c2x + tx;
  102119. py = c2y + ty;
  102120. pz = c2z + tz;
  102121. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102122. px = dx * r00 + dy * r01 + dz * r02;
  102123. py = dx * r10 + dy * r11 + dz * r12;
  102124. pz = dx * r20 + dy * r21 + dz * r22;
  102125. px = (dx = px) + c1x;
  102126. py = (dy = py) + c1y;
  102127. pz = (dz = pz) + c1z;
  102128. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102129. if (pd <= 0) {
  102130. tx = px - pd * nx - c2x;
  102131. ty = py - pd * ny - c2y;
  102132. tz = pz - pd * nz - c2z;
  102133. len = tx * tx + ty * ty + tz * tz;
  102134. if (len > r2 * r2) {
  102135. len = r2 / OIMO.sqrt(len);
  102136. tx *= len;
  102137. ty *= len;
  102138. tz *= len;
  102139. }
  102140. px = c2x + tx;
  102141. py = c2y + ty;
  102142. pz = c2z + tz;
  102143. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102144. }
  102145. px = dx * r00 + dy * r01 + dz * r02;
  102146. py = dx * r10 + dy * r11 + dz * r12;
  102147. pz = dx * r20 + dy * r21 + dz * r22;
  102148. px = (dx = px) + c1x;
  102149. py = (dy = py) + c1y;
  102150. pz = (dz = pz) + c1z;
  102151. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102152. if (pd <= 0) {
  102153. tx = px - pd * nx - c2x;
  102154. ty = py - pd * ny - c2y;
  102155. tz = pz - pd * nz - c2z;
  102156. len = tx * tx + ty * ty + tz * tz;
  102157. if (len > r2 * r2) {
  102158. len = r2 / OIMO.sqrt(len);
  102159. tx *= len;
  102160. ty *= len;
  102161. tz *= len;
  102162. }
  102163. px = c2x + tx;
  102164. py = c2y + ty;
  102165. pz = c2z + tz;
  102166. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102167. }
  102168. } else {
  102169. sx = tx;
  102170. sy = ty;
  102171. sz = tz;
  102172. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102173. sx -= depth1 * nx;
  102174. sy -= depth1 * ny;
  102175. sz -= depth1 * nz;
  102176. if (dot > 0) {
  102177. ex = tx + n1x * h1 * 2;
  102178. ey = ty + n1y * h1 * 2;
  102179. ez = tz + n1z * h1 * 2;
  102180. } else {
  102181. ex = tx - n1x * h1 * 2;
  102182. ey = ty - n1y * h1 * 2;
  102183. ez = tz - n1z * h1 * 2;
  102184. }
  102185. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102186. ex -= depth2 * nx;
  102187. ey -= depth2 * ny;
  102188. ez -= depth2 * nz;
  102189. dx = c2x - sx;
  102190. dy = c2y - sy;
  102191. dz = c2z - sz;
  102192. tx = ex - sx;
  102193. ty = ey - sy;
  102194. tz = ez - sz;
  102195. a = dx * dx + dy * dy + dz * dz;
  102196. b = dx * tx + dy * ty + dz * tz;
  102197. e = tx * tx + ty * ty + tz * tz;
  102198. f = b * b - e * (a - r2 * r2);
  102199. if (f < 0) break;
  102200. f = OIMO.sqrt(f);
  102201. t1 = (b + f) / e;
  102202. t2 = (b - f) / e;
  102203. if (t2 < t1) {
  102204. len = t1;
  102205. t1 = t2;
  102206. t2 = len;
  102207. }
  102208. if (t2 > 1) t2 = 1;
  102209. if (t1 < 0) t1 = 0;
  102210. tx = sx + (ex - sx) * t1;
  102211. ty = sy + (ey - sy) * t1;
  102212. tz = sz + (ez - sz) * t1;
  102213. ex = sx + (ex - sx) * t2;
  102214. ey = sy + (ey - sy) * t2;
  102215. ez = sz + (ez - sz) * t2;
  102216. sx = tx;
  102217. sy = ty;
  102218. sz = tz;
  102219. len = depth1 + (depth2 - depth1) * t1;
  102220. depth2 = depth1 + (depth2 - depth1) * t2;
  102221. depth1 = len;
  102222. if (depth1 < 0) {
  102223. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102224. }
  102225. if (depth2 < 0) {
  102226. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102227. }
  102228. }
  102229. break;
  102230. }
  102231. };
  102232. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102233. OIMO.CollisionDetector.call(this);
  102234. this.flip = flip;
  102235. };
  102236. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102237. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102238. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102239. var s;
  102240. var c;
  102241. if (this.flip) {
  102242. s = shape2;
  102243. c = shape1;
  102244. } else {
  102245. s = shape1;
  102246. c = shape2;
  102247. }
  102248. var ps = s.position;
  102249. var psx = ps.x;
  102250. var psy = ps.y;
  102251. var psz = ps.z;
  102252. var pc = c.position;
  102253. var pcx = pc.x;
  102254. var pcy = pc.y;
  102255. var pcz = pc.z;
  102256. var dirx = c.normalDirection.x;
  102257. var diry = c.normalDirection.y;
  102258. var dirz = c.normalDirection.z;
  102259. var rads = s.radius;
  102260. var radc = c.radius;
  102261. var rad2 = rads + radc;
  102262. var halfh = c.halfHeight;
  102263. var dx = psx - pcx;
  102264. var dy = psy - pcy;
  102265. var dz = psz - pcz;
  102266. var dot = dx * dirx + dy * diry + dz * dirz;
  102267. if (dot < -halfh - rads || dot > halfh + rads) return;
  102268. var cx = pcx + dot * dirx;
  102269. var cy = pcy + dot * diry;
  102270. var cz = pcz + dot * dirz;
  102271. var d2x = psx - cx;
  102272. var d2y = psy - cy;
  102273. var d2z = psz - cz;
  102274. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102275. if (len > rad2 * rad2) return;
  102276. if (len > radc * radc) {
  102277. len = radc / OIMO.sqrt(len);
  102278. d2x *= len;
  102279. d2y *= len;
  102280. d2z *= len;
  102281. }
  102282. if (dot < -halfh) dot = -halfh;
  102283. else if (dot > halfh) dot = halfh;
  102284. cx = pcx + dot * dirx + d2x;
  102285. cy = pcy + dot * diry + d2y;
  102286. cz = pcz + dot * dirz + d2z;
  102287. dx = cx - psx;
  102288. dy = cy - psy;
  102289. dz = cz - psz;
  102290. len = dx * dx + dy * dy + dz * dz;
  102291. var invLen;
  102292. if (len > 0 && len < rads * rads) {
  102293. len = OIMO.sqrt(len);
  102294. invLen = 1 / len;
  102295. dx *= invLen;
  102296. dy *= invLen;
  102297. dz *= invLen;
  102298. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102299. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102300. }
  102301. };
  102302. /**
  102303. * Class for checking collisions between 2 tetras,
  102304. * a shape that is made with 4 vertices and 4 faces
  102305. * arranged in triangles. With this algorigthm, soft
  102306. * body physics are possible and easier to implement.
  102307. * @author xprogram
  102308. */
  102309. OIMO.TetraTetraCollisionDetector = function () {
  102310. OIMO.CollisionDetector.call(this);
  102311. };
  102312. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102313. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102314. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102315. /*
  102316. * What we are doing:
  102317. * Each tetra is represented by four 3D triangles. The only
  102318. * quick way of finding if another tetra is within the other
  102319. * tetra is to see if a single vertex is within the triangles
  102320. * of the other tetra. So, for example, a tetra is represented
  102321. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102322. * There is another tetra with a vertex A which was detected for
  102323. * collision by the broadphase. Now, if the point A is between ALL
  102324. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102325. * is valid and we can pass point A to the manifold. Since the only
  102326. * points on the tetra are the 4 vertices, collision detection is
  102327. * not so complex. However, it can be time-consuming because we
  102328. * need to split the 3D triangles into three 2D triangles each for
  102329. * collision detection.
  102330. */
  102331. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102332. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102333. // fs is undeclared
  102334. var fs = fs1;
  102335. for (i = 0; i < 4; i++) {
  102336. vec = vs1[i];
  102337. for (j = 0; j < 4; j++) {
  102338. j1 = vs2[fs[i].a];
  102339. j2 = vs2[fs[i].b];
  102340. j3 = vs2[fs[i].c];
  102341. if (
  102342. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102343. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102344. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102345. )
  102346. ts++;
  102347. if (ts === 4) // Only add point if it is inside all 4 triangles
  102348. manifold.addPoint(vec);
  102349. }
  102350. }
  102351. };
  102352. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102353. function tricheck(p, p0, p1, p2) {
  102354. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102355. var sg = A < 0 ? -1 : 1;
  102356. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102357. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102358. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102359. }
  102360. function pt(x, y) { return { x: x, y: y }; }
  102361. /**
  102362. * An axis-aligned bounding box.
  102363. * @author saharan
  102364. * @author lo-th
  102365. */
  102366. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102367. this.elements = new OIMO_ARRAY_TYPE(6);
  102368. var te = this.elements;
  102369. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102370. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102371. };
  102372. OIMO.AABB.prototype = {
  102373. constructor: OIMO.AABB,
  102374. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102375. var te = this.elements;
  102376. te[0] = minX; te[3] = maxX;
  102377. te[1] = minY; te[4] = maxY;
  102378. te[2] = minZ; te[5] = maxZ;
  102379. return this;
  102380. },
  102381. intersectTest: function (aabb) {
  102382. var te = this.elements;
  102383. var ue = aabb.elements;
  102384. 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];
  102385. },
  102386. intersectTestTwo: function (aabb) {
  102387. var te = this.elements;
  102388. var ue = aabb.elements;
  102389. 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];
  102390. },
  102391. clone: function () {
  102392. return new this.constructor().fromArray(this.elements);
  102393. },
  102394. copy: function (aabb, margin) {
  102395. var m = margin || 0;
  102396. var me = aabb.elements;
  102397. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102398. return this;
  102399. },
  102400. fromArray: function (array) {
  102401. this.elements.set(array);
  102402. return this;
  102403. },
  102404. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102405. combine: function (aabb1, aabb2) {
  102406. var a = aabb1.elements;
  102407. var b = aabb2.elements;
  102408. var te = this.elements;
  102409. te[0] = a[0] < b[0] ? a[0] : b[0];
  102410. te[1] = a[1] < b[1] ? a[1] : b[1];
  102411. te[2] = a[2] < b[2] ? a[2] : b[2];
  102412. te[3] = a[3] > b[3] ? a[3] : b[3];
  102413. te[4] = a[4] > b[4] ? a[4] : b[4];
  102414. te[5] = a[5] > b[5] ? a[5] : b[5];
  102415. return this;
  102416. },
  102417. // Get the surface area.
  102418. surfaceArea: function () {
  102419. var te = this.elements;
  102420. var a = te[3] - te[0];
  102421. var h = te[4] - te[1];
  102422. var d = te[5] - te[2];
  102423. return 2 * (a * (h + d) + h * d);
  102424. },
  102425. // Get whether the AABB intersects with the point or not.
  102426. intersectsWithPoint: function (x, y, z) {
  102427. var te = this.elements;
  102428. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102429. },
  102430. /**
  102431. * Set the AABB from an array
  102432. * of vertices. From THREE.
  102433. * @author mrdoob
  102434. * @author xprogram
  102435. */
  102436. setFromPoints: function (arr) {
  102437. this.makeEmpty();
  102438. for (var i = 0; i < arr.length; i++) {
  102439. this.expandByPoint(arr[i]);
  102440. }
  102441. },
  102442. makeEmpty: function () {
  102443. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102444. },
  102445. expandByPoint: function (pt) {
  102446. var te = this.elements;
  102447. this.set(
  102448. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102449. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102450. );
  102451. }
  102452. };
  102453. /**
  102454. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102455. */
  102456. OIMO.Proxy = function (shape) {
  102457. // The parent shape.
  102458. this.shape = shape;
  102459. // The axis-aligned bounding box.
  102460. this.aabb = shape.aabb;
  102461. };
  102462. OIMO.Proxy.prototype = {
  102463. constructor: OIMO.Proxy,
  102464. // Update the proxy.
  102465. update: function () {
  102466. OIMO.Error("Proxy", "Inheritance error.");
  102467. }
  102468. };
  102469. /**
  102470. * A basic implementation of proxies.
  102471. * @author saharan
  102472. */
  102473. OIMO.BasicProxy = function (shape) {
  102474. OIMO.Proxy.call(this, shape);
  102475. this.id = OIMO.proxyID++;
  102476. };
  102477. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102478. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102479. OIMO.BasicProxy.prototype.update = function () {
  102480. };
  102481. /**
  102482. * The broad-phase is used for collecting all possible pairs for collision.
  102483. */
  102484. OIMO.BroadPhase = function () {
  102485. this.types = OIMO.BR_NULL;
  102486. this.numPairChecks = 0;
  102487. this.numPairs = 0;
  102488. this.pairs = [];
  102489. };
  102490. OIMO.BroadPhase.prototype = {
  102491. constructor: OIMO.BroadPhase,
  102492. /**
  102493. * Create a new proxy.
  102494. * @param shape
  102495. * @return
  102496. */
  102497. createProxy: function (shape) {
  102498. OIMO.Error("BroadPhase", "Inheritance error.");
  102499. },
  102500. /**
  102501. * Add the proxy into the broad-phase.
  102502. * @param proxy
  102503. */
  102504. addProxy: function (proxy) {
  102505. OIMO.Error("BroadPhase", "Inheritance error.");
  102506. },
  102507. /**
  102508. * Remove the proxy from the broad-phase.
  102509. * @param proxy
  102510. */
  102511. removeProxy: function (proxy) {
  102512. OIMO.Error("BroadPhase", "Inheritance error.");
  102513. },
  102514. /**
  102515. * Returns whether the pair is available or not.
  102516. * @param s1
  102517. * @param s2
  102518. * @return
  102519. */
  102520. isAvailablePair: function (s1, s2) {
  102521. var b1 = s1.parent;
  102522. var b2 = s2.parent;
  102523. if (b1 == b2 || // same parents
  102524. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102525. (s1.belongsTo & s2.collidesWith) == 0 ||
  102526. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102527. ) { return false; }
  102528. var js;
  102529. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102530. else js = b2.jointLink;
  102531. while (js !== null) {
  102532. var joint = js.joint;
  102533. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102534. js = js.next;
  102535. }
  102536. return true;
  102537. },
  102538. // Detect overlapping pairs.
  102539. detectPairs: function () {
  102540. // clear old
  102541. this.pairs = [];
  102542. this.numPairs = 0;
  102543. this.numPairChecks = 0;
  102544. this.collectPairs();
  102545. },
  102546. collectPairs: function () {
  102547. OIMO.Error("BroadPhase", "Inheritance error.");
  102548. },
  102549. addPair: function (s1, s2) {
  102550. var pair = new OIMO.Pair(s1, s2);
  102551. this.pairs.push(pair);
  102552. this.numPairs++;
  102553. }
  102554. };
  102555. /**
  102556. * A broad-phase algorithm with brute-force search.
  102557. * This always checks for all possible pairs.
  102558. */
  102559. OIMO.BruteForceBroadPhase = function () {
  102560. OIMO.BroadPhase.call(this);
  102561. this.types = OIMO.BR_BRUTE_FORCE;;
  102562. //this.numProxies=0;
  102563. ///this.maxProxies = 256;
  102564. this.proxies = [];
  102565. //this.proxies.length = 256;
  102566. };
  102567. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102568. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102569. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102570. return new OIMO.BasicProxy(shape);
  102571. };
  102572. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102573. /*if(this.numProxies==this.maxProxies){
  102574. //this.maxProxies<<=1;
  102575. this.maxProxies*=2;
  102576. var newProxies=[];
  102577. newProxies.length = this.maxProxies;
  102578. var i = this.numProxies;
  102579. while(i--){
  102580. //for(var i=0, l=this.numProxies;i<l;i++){
  102581. newProxies[i]=this.proxies[i];
  102582. }
  102583. this.proxies=newProxies;
  102584. }*/
  102585. //this.proxies[this.numProxies++] = proxy;
  102586. this.proxies.push(proxy);
  102587. //this.numProxies++;
  102588. };
  102589. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102590. var n = this.proxies.indexOf(proxy);
  102591. if (n > -1) {
  102592. this.proxies.splice(n, 1);
  102593. //this.numProxies--;
  102594. }
  102595. /*var i = this.numProxies;
  102596. while(i--){
  102597. //for(var i=0, l=this.numProxies;i<l;i++){
  102598. if(this.proxies[i] == proxy){
  102599. this.proxies[i] = this.proxies[--this.numProxies];
  102600. this.proxies[this.numProxies] = null;
  102601. return;
  102602. }
  102603. }*/
  102604. };
  102605. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102606. var i = 0, j, p1, p2;
  102607. var px = this.proxies;
  102608. var l = px.length;//this.numProxies;
  102609. //var ar1 = [];
  102610. //var ar2 = [];
  102611. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102612. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102613. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102614. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102615. this.numPairChecks = l * (l - 1) >> 1;
  102616. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102617. while (i < l) {
  102618. p1 = px[i++];
  102619. j = i + 1;
  102620. while (j < l) {
  102621. p2 = px[j++];
  102622. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102623. this.addPair(p1.shape, p2.shape);
  102624. }
  102625. }
  102626. };
  102627. /**
  102628. * A pair of shapes that may collide.
  102629. * @author saharan
  102630. */
  102631. OIMO.Pair = function (s1, s2) {
  102632. // The first shape.
  102633. this.shape1 = s1 || null;
  102634. // The second shape.
  102635. this.shape2 = s2 || null;
  102636. };
  102637. /**
  102638. * A projection axis for sweep and prune broad-phase.
  102639. * @author saharan
  102640. */
  102641. OIMO.SAPAxis = function () {
  102642. this.numElements = 0;
  102643. this.bufferSize = 256;
  102644. this.elements = [];
  102645. this.elements.length = this.bufferSize;
  102646. this.stack = new OIMO_ARRAY_TYPE(64);
  102647. };
  102648. OIMO.SAPAxis.prototype = {
  102649. constructor: OIMO.SAPAxis,
  102650. addElements: function (min, max) {
  102651. if (this.numElements + 2 >= this.bufferSize) {
  102652. //this.bufferSize<<=1;
  102653. this.bufferSize *= 2;
  102654. var newElements = [];
  102655. var i = this.numElements;
  102656. while (i--) {
  102657. //for(var i=0, l=this.numElements; i<l; i++){
  102658. newElements[i] = this.elements[i];
  102659. }
  102660. }
  102661. this.elements[this.numElements++] = min;
  102662. this.elements[this.numElements++] = max;
  102663. },
  102664. removeElements: function (min, max) {
  102665. var minIndex = -1;
  102666. var maxIndex = -1;
  102667. for (var i = 0, l = this.numElements; i < l; i++) {
  102668. var e = this.elements[i];
  102669. if (e == min || e == max) {
  102670. if (minIndex == -1) {
  102671. minIndex = i;
  102672. } else {
  102673. maxIndex = i;
  102674. break;
  102675. }
  102676. }
  102677. }
  102678. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102679. this.elements[i - 1] = this.elements[i];
  102680. }
  102681. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102682. this.elements[i - 2] = this.elements[i];
  102683. }
  102684. this.elements[--this.numElements] = null;
  102685. this.elements[--this.numElements] = null;
  102686. },
  102687. sort: function () {
  102688. var count = 0;
  102689. var threshold = 1;
  102690. while ((this.numElements >> threshold) != 0) threshold++;
  102691. threshold = threshold * this.numElements >> 2;
  102692. count = 0;
  102693. var giveup = false;
  102694. var elements = this.elements;
  102695. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102696. var tmp = elements[i];
  102697. var pivot = tmp.value;
  102698. var tmp2 = elements[i - 1];
  102699. if (tmp2.value > pivot) {
  102700. var j = i;
  102701. do {
  102702. elements[j] = tmp2;
  102703. if (--j == 0) break;
  102704. tmp2 = elements[j - 1];
  102705. } while (tmp2.value > pivot);
  102706. elements[j] = tmp;
  102707. count += i - j;
  102708. if (count > threshold) {
  102709. giveup = true; // stop and use quick sort
  102710. break;
  102711. }
  102712. }
  102713. }
  102714. if (!giveup) return;
  102715. count = 2; var stack = this.stack;
  102716. stack[0] = 0;
  102717. stack[1] = this.numElements - 1;
  102718. while (count > 0) {
  102719. var right = stack[--count];
  102720. var left = stack[--count];
  102721. var diff = right - left;
  102722. if (diff > 16) { // quick sort
  102723. //var mid=left+(diff>>1);
  102724. var mid = left + (OIMO.floor(diff * 0.5));
  102725. tmp = elements[mid];
  102726. elements[mid] = elements[right];
  102727. elements[right] = tmp;
  102728. pivot = tmp.value;
  102729. i = left - 1;
  102730. j = right;
  102731. while (true) {
  102732. var ei;
  102733. var ej;
  102734. do { ei = elements[++i]; } while (ei.value < pivot);
  102735. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102736. if (i >= j) break;
  102737. elements[i] = ej;
  102738. elements[j] = ei;
  102739. }
  102740. elements[right] = elements[i];
  102741. elements[i] = tmp;
  102742. if (i - left > right - i) {
  102743. stack[count++] = left;
  102744. stack[count++] = i - 1;
  102745. stack[count++] = i + 1;
  102746. stack[count++] = right;
  102747. } else {
  102748. stack[count++] = i + 1;
  102749. stack[count++] = right;
  102750. stack[count++] = left;
  102751. stack[count++] = i - 1;
  102752. }
  102753. } else {
  102754. for (i = left + 1; i <= right; i++) {
  102755. tmp = elements[i];
  102756. pivot = tmp.value;
  102757. tmp2 = elements[i - 1];
  102758. if (tmp2.value > pivot) {
  102759. j = i;
  102760. do {
  102761. elements[j] = tmp2;
  102762. if (--j == 0) break;
  102763. tmp2 = elements[j - 1];
  102764. } while (tmp2.value > pivot);
  102765. elements[j] = tmp;
  102766. }
  102767. }
  102768. }
  102769. }
  102770. },
  102771. calculateTestCount: function () {
  102772. var num = 1;
  102773. var sum = 0;
  102774. for (var i = 1, l = this.numElements; i < l; i++) {
  102775. if (this.elements[i].max) {
  102776. num--;
  102777. } else {
  102778. sum += num;
  102779. num++;
  102780. }
  102781. }
  102782. return sum;
  102783. }
  102784. }
  102785. /**
  102786. * A broad-phase collision detection algorithm using sweep and prune.
  102787. * @author saharan
  102788. * @author lo-th
  102789. */
  102790. OIMO.SAPBroadPhase = function () {
  102791. OIMO.BroadPhase.call(this);
  102792. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102793. this.numElementsD = 0;
  102794. this.numElementsS = 0;
  102795. // dynamic proxies
  102796. this.axesD = [
  102797. new OIMO.SAPAxis(),
  102798. new OIMO.SAPAxis(),
  102799. new OIMO.SAPAxis()
  102800. ];
  102801. // static or sleeping proxies
  102802. this.axesS = [
  102803. new OIMO.SAPAxis(),
  102804. new OIMO.SAPAxis(),
  102805. new OIMO.SAPAxis()
  102806. ];
  102807. this.index1 = 0;
  102808. this.index2 = 1;
  102809. };
  102810. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102811. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102812. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102813. return new OIMO.SAPProxy(this, shape);
  102814. };
  102815. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102816. var p = proxy;
  102817. if (p.isDynamic()) {
  102818. this.axesD[0].addElements(p.min[0], p.max[0]);
  102819. this.axesD[1].addElements(p.min[1], p.max[1]);
  102820. this.axesD[2].addElements(p.min[2], p.max[2]);
  102821. p.belongsTo = 1;
  102822. this.numElementsD += 2;
  102823. } else {
  102824. this.axesS[0].addElements(p.min[0], p.max[0]);
  102825. this.axesS[1].addElements(p.min[1], p.max[1]);
  102826. this.axesS[2].addElements(p.min[2], p.max[2]);
  102827. p.belongsTo = 2;
  102828. this.numElementsS += 2;
  102829. }
  102830. };
  102831. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102832. var p = proxy;
  102833. if (p.belongsTo == 0) return;
  102834. /*else if ( p.belongsTo == 1 ) {
  102835. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102836. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102837. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102838. this.numElementsD -= 2;
  102839. } else if ( p.belongsTo == 2 ) {
  102840. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102841. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102842. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102843. this.numElementsS -= 2;
  102844. }*/
  102845. switch (p.belongsTo) {
  102846. case 1:
  102847. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102848. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102849. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102850. this.numElementsD -= 2;
  102851. break;
  102852. case 2:
  102853. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102854. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102855. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102856. this.numElementsS -= 2;
  102857. break;
  102858. }
  102859. p.belongsTo = 0;
  102860. };
  102861. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102862. if (this.numElementsD == 0) return;
  102863. var axis1 = this.axesD[this.index1];
  102864. var axis2 = this.axesD[this.index2];
  102865. axis1.sort();
  102866. axis2.sort();
  102867. var count1 = axis1.calculateTestCount();
  102868. var count2 = axis2.calculateTestCount();
  102869. var elementsD;
  102870. var elementsS;
  102871. if (count1 <= count2) {// select the best axis
  102872. axis2 = this.axesS[this.index1];
  102873. axis2.sort();
  102874. elementsD = axis1.elements;
  102875. elementsS = axis2.elements;
  102876. } else {
  102877. axis1 = this.axesS[this.index2];
  102878. axis1.sort();
  102879. elementsD = axis2.elements;
  102880. elementsS = axis1.elements;
  102881. this.index1 ^= this.index2;
  102882. this.index2 ^= this.index1;
  102883. this.index1 ^= this.index2;
  102884. }
  102885. var activeD;
  102886. var activeS;
  102887. var p = 0;
  102888. var q = 0;
  102889. while (p < this.numElementsD) {
  102890. var e1;
  102891. var dyn;
  102892. if (q == this.numElementsS) {
  102893. e1 = elementsD[p];
  102894. dyn = true;
  102895. p++;
  102896. } else {
  102897. var d = elementsD[p];
  102898. var s = elementsS[q];
  102899. if (d.value < s.value) {
  102900. e1 = d;
  102901. dyn = true;
  102902. p++;
  102903. } else {
  102904. e1 = s;
  102905. dyn = false;
  102906. q++;
  102907. }
  102908. }
  102909. if (!e1.max) {
  102910. var s1 = e1.proxy.shape;
  102911. var min1 = e1.min1.value;
  102912. var max1 = e1.max1.value;
  102913. var min2 = e1.min2.value;
  102914. var max2 = e1.max2.value;
  102915. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  102916. var s2 = e2.proxy.shape;
  102917. this.numPairChecks++;
  102918. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102919. this.addPair(s1, s2);
  102920. }
  102921. if (dyn) {
  102922. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  102923. s2 = e2.proxy.shape;
  102924. this.numPairChecks++;
  102925. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102926. this.addPair(s1, s2);
  102927. }
  102928. e1.pair = activeD;
  102929. activeD = e1;
  102930. } else {
  102931. e1.pair = activeS;
  102932. activeS = e1;
  102933. }
  102934. } else {
  102935. var min = e1.pair;
  102936. if (dyn) {
  102937. if (min == activeD) {
  102938. activeD = activeD.pair;
  102939. continue;
  102940. } else {
  102941. e1 = activeD;
  102942. }
  102943. } else {
  102944. if (min == activeS) {
  102945. activeS = activeS.pair;
  102946. continue;
  102947. } else {
  102948. e1 = activeS;
  102949. }
  102950. }
  102951. do {
  102952. e2 = e1.pair;
  102953. if (e2 == min) {
  102954. e1.pair = e2.pair;
  102955. break;
  102956. }
  102957. e1 = e2;
  102958. } while (e1 != null);
  102959. }
  102960. }
  102961. this.index2 = (this.index1 | this.index2) ^ 3;
  102962. };
  102963. /**
  102964. * An element of proxies.
  102965. * @author saharan
  102966. */
  102967. OIMO.SAPElement = function (proxy, max) {
  102968. // The parent proxy
  102969. this.proxy = proxy;
  102970. // The pair element.
  102971. this.pair = null;
  102972. // The minimum element on other axis.
  102973. this.min1 = null;
  102974. // The maximum element on other axis.
  102975. this.max1 = null;
  102976. // The minimum element on other axis.
  102977. this.min2 = null;
  102978. // The maximum element on other axis.
  102979. this.max2 = null;
  102980. // Whether the element has maximum value or not.
  102981. this.max = max;
  102982. // The value of the element.
  102983. this.value = 0;
  102984. };
  102985. /**
  102986. * A proxy for sweep and prune broad-phase.
  102987. * @author saharan
  102988. * @author lo-th
  102989. */
  102990. OIMO.SAPProxy = function (sap, shape) {
  102991. OIMO.Proxy.call(this, shape);
  102992. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  102993. this.belongsTo = 0;
  102994. // The maximum elements on each axis.
  102995. this.max = [];
  102996. // The minimum elements on each axis.
  102997. this.min = [];
  102998. this.sap = sap;
  102999. this.min[0] = new OIMO.SAPElement(this, false);
  103000. this.max[0] = new OIMO.SAPElement(this, true);
  103001. this.min[1] = new OIMO.SAPElement(this, false);
  103002. this.max[1] = new OIMO.SAPElement(this, true);
  103003. this.min[2] = new OIMO.SAPElement(this, false);
  103004. this.max[2] = new OIMO.SAPElement(this, true);
  103005. this.max[0].pair = this.min[0];
  103006. this.max[1].pair = this.min[1];
  103007. this.max[2].pair = this.min[2];
  103008. this.min[0].min1 = this.min[1];
  103009. this.min[0].max1 = this.max[1];
  103010. this.min[0].min2 = this.min[2];
  103011. this.min[0].max2 = this.max[2];
  103012. this.min[1].min1 = this.min[0];
  103013. this.min[1].max1 = this.max[0];
  103014. this.min[1].min2 = this.min[2];
  103015. this.min[1].max2 = this.max[2];
  103016. this.min[2].min1 = this.min[0];
  103017. this.min[2].max1 = this.max[0];
  103018. this.min[2].min2 = this.min[1];
  103019. this.min[2].max2 = this.max[1];
  103020. };
  103021. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103022. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103023. // Returns whether the proxy is dynamic or not.
  103024. OIMO.SAPProxy.prototype.isDynamic = function () {
  103025. var body = this.shape.parent;
  103026. return body.isDynamic && !body.sleeping;
  103027. };
  103028. OIMO.SAPProxy.prototype.update = function () {
  103029. var te = this.aabb.elements;
  103030. this.min[0].value = te[0];
  103031. this.min[1].value = te[1];
  103032. this.min[2].value = te[2];
  103033. this.max[0].value = te[3];
  103034. this.max[1].value = te[4];
  103035. this.max[2].value = te[5];
  103036. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103037. this.sap.removeProxy(this);
  103038. this.sap.addProxy(this);
  103039. }
  103040. };
  103041. /**
  103042. * A dynamic bounding volume tree for the broad-phase algorithm.
  103043. * @author saharan
  103044. * @author lo-th
  103045. */
  103046. OIMO.DBVT = function () {
  103047. // The root of the tree.
  103048. this.root = null;
  103049. this.freeNodes = [];
  103050. this.freeNodes.length = 16384;
  103051. this.numFreeNodes = 0;
  103052. this.aabb = new OIMO.AABB();
  103053. };
  103054. OIMO.DBVT.prototype = {
  103055. constructor: OIMO.DBVT,
  103056. /**
  103057. * Move a leaf.
  103058. * @param leaf
  103059. */
  103060. moveLeaf: function (leaf) {
  103061. this.deleteLeaf(leaf);
  103062. this.insertLeaf(leaf);
  103063. },
  103064. /**
  103065. * Insert a leaf to the tree.
  103066. * @param node
  103067. */
  103068. insertLeaf: function (leaf) {
  103069. if (this.root == null) {
  103070. this.root = leaf;
  103071. return;
  103072. }
  103073. var lb = leaf.aabb;
  103074. var sibling = this.root;
  103075. var oldArea;
  103076. var newArea;
  103077. while (sibling.proxy == null) { // descend the node to search the best pair
  103078. var c1 = sibling.child1;
  103079. var c2 = sibling.child2;
  103080. var b = sibling.aabb;
  103081. var c1b = c1.aabb;
  103082. var c2b = c2.aabb;
  103083. oldArea = b.surfaceArea();
  103084. this.aabb.combine(lb, b);
  103085. newArea = this.aabb.surfaceArea();
  103086. var creatingCost = newArea * 2;
  103087. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103088. var discendingCost1 = incrementalCost;
  103089. this.aabb.combine(lb, c1b);
  103090. if (c1.proxy != null) {
  103091. // leaf cost = area(combined aabb)
  103092. discendingCost1 += this.aabb.surfaceArea();
  103093. } else {
  103094. // node cost = area(combined aabb) - area(old aabb)
  103095. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103096. }
  103097. var discendingCost2 = incrementalCost;
  103098. this.aabb.combine(lb, c2b);
  103099. if (c2.proxy != null) {
  103100. // leaf cost = area(combined aabb)
  103101. discendingCost2 += this.aabb.surfaceArea();
  103102. } else {
  103103. // node cost = area(combined aabb) - area(old aabb)
  103104. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103105. }
  103106. if (discendingCost1 < discendingCost2) {
  103107. if (creatingCost < discendingCost1) {
  103108. break;// stop descending
  103109. } else {
  103110. sibling = c1;// descend into first child
  103111. }
  103112. } else {
  103113. if (creatingCost < discendingCost2) {
  103114. break;// stop descending
  103115. } else {
  103116. sibling = c2;// descend into second child
  103117. }
  103118. }
  103119. }
  103120. var oldParent = sibling.parent;
  103121. var newParent;
  103122. if (this.numFreeNodes > 0) {
  103123. newParent = this.freeNodes[--this.numFreeNodes];
  103124. } else {
  103125. newParent = new OIMO.DBVTNode();
  103126. }
  103127. newParent.parent = oldParent;
  103128. newParent.child1 = leaf;
  103129. newParent.child2 = sibling;
  103130. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103131. newParent.height = sibling.height + 1;
  103132. sibling.parent = newParent;
  103133. leaf.parent = newParent;
  103134. if (sibling == this.root) {
  103135. // replace root
  103136. this.root = newParent;
  103137. } else {
  103138. // replace child
  103139. if (oldParent.child1 == sibling) {
  103140. oldParent.child1 = newParent;
  103141. } else {
  103142. oldParent.child2 = newParent;
  103143. }
  103144. }
  103145. // update whole tree
  103146. do {
  103147. newParent = this.balance(newParent);
  103148. this.fix(newParent);
  103149. newParent = newParent.parent;
  103150. } while (newParent != null);
  103151. },
  103152. getBalance: function (node) {
  103153. if (node.proxy != null) return 0;
  103154. return node.child1.height - node.child2.height;
  103155. },
  103156. /*print:function(node,indent,text){
  103157. var hasChild=node.proxy==null;
  103158. if(hasChild)text=this.print(node.child1,indent+1,text);
  103159. for(var i=indent*2;i>=0;i--){
  103160. text+=" ";
  103161. }
  103162. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103163. if(hasChild)text=this.print(node.child2,indent+1,text);
  103164. return text;
  103165. },*/
  103166. /**
  103167. * Delete a leaf from the tree.
  103168. * @param node
  103169. */
  103170. deleteLeaf: function (leaf) {
  103171. if (leaf == this.root) {
  103172. this.root = null;
  103173. return;
  103174. }
  103175. var parent = leaf.parent;
  103176. var sibling;
  103177. if (parent.child1 == leaf) {
  103178. sibling = parent.child2;
  103179. } else {
  103180. sibling = parent.child1;
  103181. }
  103182. if (parent == this.root) {
  103183. this.root = sibling;
  103184. sibling.parent = null;
  103185. return;
  103186. }
  103187. var grandParent = parent.parent;
  103188. sibling.parent = grandParent;
  103189. if (grandParent.child1 == parent) {
  103190. grandParent.child1 = sibling;
  103191. } else {
  103192. grandParent.child2 = sibling;
  103193. }
  103194. if (this.numFreeNodes < 16384) {
  103195. this.freeNodes[this.numFreeNodes++] = parent;
  103196. }
  103197. do {
  103198. grandParent = this.balance(grandParent);
  103199. this.fix(grandParent);
  103200. grandParent = grandParent.parent;
  103201. } while (grandParent != null);
  103202. },
  103203. balance: function (node) {
  103204. var nh = node.height;
  103205. if (nh < 2) {
  103206. return node;
  103207. }
  103208. var p = node.parent;
  103209. var l = node.child1;
  103210. var r = node.child2;
  103211. var lh = l.height;
  103212. var rh = r.height;
  103213. var balance = lh - rh;
  103214. var t;// for bit operation
  103215. // [ N ]
  103216. // / \
  103217. // [ L ] [ R ]
  103218. // / \ / \
  103219. // [L-L] [L-R] [R-L] [R-R]
  103220. // Is the tree balanced?
  103221. if (balance > 1) {
  103222. var ll = l.child1;
  103223. var lr = l.child2;
  103224. var llh = ll.height;
  103225. var lrh = lr.height;
  103226. // Is L-L higher than L-R?
  103227. if (llh > lrh) {
  103228. // set N to L-R
  103229. l.child2 = node;
  103230. node.parent = l;
  103231. // [ L ]
  103232. // / \
  103233. // [L-L] [ N ]
  103234. // / \ / \
  103235. // [...] [...] [ L ] [ R ]
  103236. // set L-R
  103237. node.child1 = lr;
  103238. lr.parent = node;
  103239. // [ L ]
  103240. // / \
  103241. // [L-L] [ N ]
  103242. // / \ / \
  103243. // [...] [...] [L-R] [ R ]
  103244. // fix bounds and heights
  103245. node.aabb.combine(lr.aabb, r.aabb);
  103246. t = lrh - rh;
  103247. node.height = lrh - (t & t >> 31) + 1;
  103248. l.aabb.combine(ll.aabb, node.aabb);
  103249. t = llh - nh;
  103250. l.height = llh - (t & t >> 31) + 1;
  103251. } else {
  103252. // set N to L-L
  103253. l.child1 = node;
  103254. node.parent = l;
  103255. // [ L ]
  103256. // / \
  103257. // [ N ] [L-R]
  103258. // / \ / \
  103259. // [ L ] [ R ] [...] [...]
  103260. // set L-L
  103261. node.child1 = ll;
  103262. ll.parent = node;
  103263. // [ L ]
  103264. // / \
  103265. // [ N ] [L-R]
  103266. // / \ / \
  103267. // [L-L] [ R ] [...] [...]
  103268. // fix bounds and heights
  103269. node.aabb.combine(ll.aabb, r.aabb);
  103270. t = llh - rh;
  103271. node.height = llh - (t & t >> 31) + 1;
  103272. l.aabb.combine(node.aabb, lr.aabb);
  103273. t = nh - lrh;
  103274. l.height = nh - (t & t >> 31) + 1;
  103275. }
  103276. // set new parent of L
  103277. if (p != null) {
  103278. if (p.child1 == node) {
  103279. p.child1 = l;
  103280. } else {
  103281. p.child2 = l;
  103282. }
  103283. } else {
  103284. this.root = l;
  103285. }
  103286. l.parent = p;
  103287. return l;
  103288. } else if (balance < -1) {
  103289. var rl = r.child1;
  103290. var rr = r.child2;
  103291. var rlh = rl.height;
  103292. var rrh = rr.height;
  103293. // Is R-L higher than R-R?
  103294. if (rlh > rrh) {
  103295. // set N to R-R
  103296. r.child2 = node;
  103297. node.parent = r;
  103298. // [ R ]
  103299. // / \
  103300. // [R-L] [ N ]
  103301. // / \ / \
  103302. // [...] [...] [ L ] [ R ]
  103303. // set R-R
  103304. node.child2 = rr;
  103305. rr.parent = node;
  103306. // [ R ]
  103307. // / \
  103308. // [R-L] [ N ]
  103309. // / \ / \
  103310. // [...] [...] [ L ] [R-R]
  103311. // fix bounds and heights
  103312. node.aabb.combine(l.aabb, rr.aabb);
  103313. t = lh - rrh;
  103314. node.height = lh - (t & t >> 31) + 1;
  103315. r.aabb.combine(rl.aabb, node.aabb);
  103316. t = rlh - nh;
  103317. r.height = rlh - (t & t >> 31) + 1;
  103318. } else {
  103319. // set N to R-L
  103320. r.child1 = node;
  103321. node.parent = r;
  103322. // [ R ]
  103323. // / \
  103324. // [ N ] [R-R]
  103325. // / \ / \
  103326. // [ L ] [ R ] [...] [...]
  103327. // set R-L
  103328. node.child2 = rl;
  103329. rl.parent = node;
  103330. // [ R ]
  103331. // / \
  103332. // [ N ] [R-R]
  103333. // / \ / \
  103334. // [ L ] [R-L] [...] [...]
  103335. // fix bounds and heights
  103336. node.aabb.combine(l.aabb, rl.aabb);
  103337. t = lh - rlh;
  103338. node.height = lh - (t & t >> 31) + 1;
  103339. r.aabb.combine(node.aabb, rr.aabb);
  103340. t = nh - rrh;
  103341. r.height = nh - (t & t >> 31) + 1;
  103342. }
  103343. // set new parent of R
  103344. if (p != null) {
  103345. if (p.child1 == node) {
  103346. p.child1 = r;
  103347. } else {
  103348. p.child2 = r;
  103349. }
  103350. } else {
  103351. this.root = r;
  103352. }
  103353. r.parent = p;
  103354. return r;
  103355. }
  103356. return node;
  103357. },
  103358. fix: function (node) {
  103359. var c1 = node.child1;
  103360. var c2 = node.child2;
  103361. node.aabb.combine(c1.aabb, c2.aabb);
  103362. //var h1 = c1.height;
  103363. //var h2 = c2.height;
  103364. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103365. /*if( h1 < h2 ) {
  103366. node.height = h2+1;
  103367. }else{
  103368. node.height = h1+1;
  103369. }*/
  103370. }
  103371. }
  103372. /**
  103373. * A broad-phase algorithm using dynamic bounding volume tree.
  103374. * @author saharan
  103375. * @author lo-th
  103376. */
  103377. OIMO.DBVTBroadPhase = function () {
  103378. OIMO.BroadPhase.call(this);
  103379. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103380. this.tree = new OIMO.DBVT();
  103381. this.stack = [];
  103382. this.leaves = [];
  103383. this.numLeaves = 0;
  103384. };
  103385. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103386. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103387. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103388. return new OIMO.DBVTProxy(shape);
  103389. };
  103390. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103391. this.tree.insertLeaf(proxy.leaf);
  103392. this.leaves.push(proxy.leaf);
  103393. this.numLeaves++;
  103394. };
  103395. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103396. this.tree.deleteLeaf(proxy.leaf);
  103397. var n = this.leaves.indexOf(proxy.leaf);
  103398. if (n > -1) {
  103399. this.leaves.splice(n, 1);
  103400. this.numLeaves--;
  103401. }
  103402. };
  103403. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103404. if (this.numLeaves < 2) return;
  103405. var leaf, margin = 0.1, i = this.numLeaves;
  103406. while (i--) {
  103407. leaf = this.leaves[i];
  103408. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103409. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103410. this.tree.deleteLeaf(leaf);
  103411. this.tree.insertLeaf(leaf);
  103412. this.collide(leaf, this.tree.root);
  103413. }
  103414. }
  103415. };
  103416. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103417. var stackCount = 2;
  103418. var s1, s2, n1, n2, l1, l2;
  103419. this.stack[0] = node1;
  103420. this.stack[1] = node2;
  103421. while (stackCount > 0) {
  103422. n1 = this.stack[--stackCount];
  103423. n2 = this.stack[--stackCount];
  103424. l1 = n1.proxy != null;
  103425. l2 = n2.proxy != null;
  103426. this.numPairChecks++;
  103427. if (l1 && l2) {
  103428. s1 = n1.proxy.shape;
  103429. s2 = n2.proxy.shape;
  103430. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103431. this.addPair(s1, s2);
  103432. } else {
  103433. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103434. /*if(stackCount+4>=this.maxStack){// expand the stack
  103435. //this.maxStack<<=1;
  103436. this.maxStack*=2;
  103437. var newStack = [];// vector
  103438. newStack.length = this.maxStack;
  103439. for(var i=0;i<stackCount;i++){
  103440. newStack[i] = this.stack[i];
  103441. }
  103442. this.stack = newStack;
  103443. }*/
  103444. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103445. this.stack[stackCount++] = n1.child1;
  103446. this.stack[stackCount++] = n2;
  103447. this.stack[stackCount++] = n1.child2;
  103448. this.stack[stackCount++] = n2;
  103449. } else {
  103450. this.stack[stackCount++] = n1;
  103451. this.stack[stackCount++] = n2.child1;
  103452. this.stack[stackCount++] = n1;
  103453. this.stack[stackCount++] = n2.child2;
  103454. }
  103455. }
  103456. }
  103457. };
  103458. /**
  103459. * A node of the dynamic bounding volume tree.
  103460. * @author saharan
  103461. */
  103462. OIMO.DBVTNode = function () {
  103463. // The first child node of this node.
  103464. this.child1 = null;
  103465. // The second child node of this node.
  103466. this.child2 = null;
  103467. // The parent node of this tree.
  103468. this.parent = null;
  103469. // The proxy of this node. This has no value if this node is not leaf.
  103470. this.proxy = null;
  103471. // The maximum distance from leaf nodes.
  103472. this.height = 0;
  103473. // The AABB of this node.
  103474. this.aabb = new OIMO.AABB();
  103475. };
  103476. /**
  103477. * A proxy for dynamic bounding volume tree broad-phase.
  103478. * @author saharan
  103479. */
  103480. OIMO.DBVTProxy = function (shape) {
  103481. OIMO.Proxy.call(this, shape);
  103482. // The leaf of the proxy.
  103483. this.leaf = new OIMO.DBVTNode();
  103484. this.leaf.proxy = this;
  103485. };
  103486. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103487. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103488. OIMO.DBVTProxy.prototype.update = function () {
  103489. };
  103490. OIMO.World.prototype.add = function (obj) {
  103491. obj = obj || {};
  103492. var type = obj.type || "box";
  103493. if (typeof type === 'string') type = [type];// single shape
  103494. if (type[0].substring(0, 5) == 'joint') { // is joint
  103495. if (type[0] === 'joint') type[0] = 'jointHinge';
  103496. var axe1 = obj.axe1 || [1, 0, 0];
  103497. var axe2 = obj.axe2 || [1, 0, 0];
  103498. var pos1 = obj.pos1 || [0, 0, 0];
  103499. var pos2 = obj.pos2 || [0, 0, 0];
  103500. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103501. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103502. var min, max;
  103503. if (type[0] === "jointDistance") {
  103504. min = obj.min || 0;
  103505. max = obj.max || 10;
  103506. min = min * OIMO.INV_SCALE;
  103507. max = max * OIMO.INV_SCALE;
  103508. } else {
  103509. min = obj.min || 57.29578;
  103510. max = obj.max || 0;
  103511. min = min * OIMO.degtorad;
  103512. max = max * OIMO.degtorad;
  103513. }
  103514. var limit = obj.limit || null;
  103515. var spring = obj.spring || null;
  103516. var motor = obj.motor || null;
  103517. // joint setting
  103518. var jc = new OIMO.JointConfig();
  103519. jc.allowCollision = obj.collision || false;;
  103520. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103521. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103522. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103523. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103524. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103525. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103526. jc.body1 = obj.body1;
  103527. jc.body2 = obj.body2;
  103528. var joint;
  103529. switch (type[0]) {
  103530. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103531. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103532. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103533. break;
  103534. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103535. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103536. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103537. break;
  103538. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103539. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103540. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103541. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103542. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103543. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103544. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103545. break;
  103546. }
  103547. joint.name = obj.name || '';
  103548. // finaly add to physics world
  103549. this.addJoint(joint);
  103550. return joint;
  103551. } else { // is body
  103552. // I'm dynamique or not
  103553. var move = obj.move || false;
  103554. // I can sleep or not
  103555. var noSleep = obj.noSleep || false;
  103556. // My start position
  103557. var p = obj.pos || [0, 0, 0];
  103558. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103559. // My size
  103560. var s = obj.size || [1, 1, 1];
  103561. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103562. // My rotation in degre
  103563. var rot = obj.rot || [0, 0, 0];
  103564. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103565. var r = [];
  103566. for (var i = 0; i < rot.length / 3; i++) {
  103567. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103568. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103569. }
  103570. // My physics setting
  103571. var sc = new OIMO.ShapeConfig();
  103572. if (obj.sc !== undefined) sc = obj.sc;
  103573. if (obj.config) {
  103574. // The density of the shape.
  103575. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103576. // The coefficient of friction of the shape.
  103577. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103578. // The coefficient of restitution of the shape.
  103579. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103580. // The bits of the collision groups to which the shape belongs.
  103581. sc.belongsTo = obj.config[3] || 1;
  103582. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103583. // The bits of the collision groups with which the shape collides.
  103584. sc.collidesWith = obj.config[4] || 0xffffffff;
  103585. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103586. }
  103587. // direct physics setting
  103588. if (obj.density !== undefined) sc.density = obj.density;
  103589. if (obj.friction !== undefined) sc.friction = obj.friction;
  103590. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103591. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103592. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103593. if (obj.massPos) {
  103594. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103595. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103596. }
  103597. if (obj.massRot) {
  103598. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103599. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103600. }
  103601. // My rigidbody
  103602. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103603. // My shapes
  103604. var shapes = [];
  103605. //if( typeof type === 'string' ) type = [type];// single shape
  103606. var n, n2;
  103607. for (var i = 0; i < type.length; i++) {
  103608. n = i * 3;
  103609. n2 = i * 4;
  103610. switch (type[i]) {
  103611. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103612. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103613. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103614. }
  103615. body.addShape(shapes[i]);
  103616. if (i > 0) {
  103617. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103618. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103619. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103620. }
  103621. }
  103622. // I'm static or i move
  103623. if (move) {
  103624. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103625. else body.setupMass(0x1, true);
  103626. if (noSleep) body.allowSleep = false;
  103627. else body.allowSleep = true;
  103628. } else {
  103629. body.setupMass(0x2);
  103630. }
  103631. body.name = obj.name || ' ';
  103632. // finaly add to physics world
  103633. this.addRigidBody(body);
  103634. return body;
  103635. }
  103636. }
  103637. //UMD simplified
  103638. var root = this;
  103639. if (!root['OIMO']) {
  103640. if (true)
  103641. module.exports = OIMO;
  103642. else if (typeof define === 'function' && define.amd)
  103643. define([], function () {
  103644. return OIMO;
  103645. });
  103646. else if (typeof exports === 'object')
  103647. exports["OIMO"] = OIMO;
  103648. else {
  103649. root["OIMO"] = OIMO;
  103650. }
  103651. }
  103652. /***/ }),
  103653. /* 19 */
  103654. /***/ (function(module, exports, __webpack_require__) {
  103655. "use strict";
  103656. Object.defineProperty(exports, "__esModule", { value: true });
  103657. var babylonjs_1 = __webpack_require__(0);
  103658. var helper_1 = __webpack_require__(2);
  103659. var TemplateManager = (function () {
  103660. function TemplateManager(containerElement) {
  103661. this.containerElement = containerElement;
  103662. this.templates = {};
  103663. this.onInit = new babylonjs_1.Observable();
  103664. this.onLoaded = new babylonjs_1.Observable();
  103665. this.onStateChange = new babylonjs_1.Observable();
  103666. this.onAllLoaded = new babylonjs_1.Observable();
  103667. this.onEventTriggered = new babylonjs_1.Observable();
  103668. this.eventManager = new eventManager_1.EventManager(this);
  103669. }
  103670. TemplateManager.prototype.initTemplate = function (templates) {
  103671. var _this = this;
  103672. var internalInit = function (dependencyMap, name, parentTemplate) {
  103673. var template = _this.templates[name];
  103674. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103675. return internalInit(dependencyMap[childName], childName, template);
  103676. });
  103677. var addToParent = function () {
  103678. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103679. template.appendTo(containingElement);
  103680. _this.checkLoadedState();
  103681. };
  103682. if (parentTemplate && !parentTemplate.parent) {
  103683. parentTemplate.onAppended.add(function () {
  103684. addToParent();
  103685. });
  103686. }
  103687. else {
  103688. addToParent();
  103689. }
  103690. return template;
  103691. };
  103692. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103693. if (_this.templates['main']) {
  103694. internalInit(htmlTree, 'main');
  103695. }
  103696. else {
  103697. _this.checkLoadedState();
  103698. }
  103699. return;
  103700. });
  103701. };
  103702. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103703. var _this = this;
  103704. var promises = Object.keys(templates).map(function (name) {
  103705. if (!templates[name])
  103706. return Promise.resolve(false);
  103707. var template = new Template(name, templates[name]);
  103708. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103709. _this.templates[name] = template;
  103710. return template.initPromise;
  103711. });
  103712. return Promise.all(promises).then(function () {
  103713. var templateStructure = {};
  103714. var buildTree = function (parentObject, name) {
  103715. _this.templates[name].isInHtmlTree = true;
  103716. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103717. childNodes.forEach(function (element) {
  103718. parentObject[element] = {};
  103719. buildTree(parentObject[element], element);
  103720. });
  103721. };
  103722. if (_this.templates['main']) {
  103723. buildTree(templateStructure, "main");
  103724. }
  103725. return templateStructure;
  103726. });
  103727. };
  103728. TemplateManager.prototype.getCanvas = function () {
  103729. return this.containerElement.querySelector('canvas');
  103730. };
  103731. TemplateManager.prototype.getTemplate = function (name) {
  103732. return this.templates[name];
  103733. };
  103734. TemplateManager.prototype.checkLoadedState = function () {
  103735. var _this = this;
  103736. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103737. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103738. });
  103739. if (done) {
  103740. this.onAllLoaded.notifyObservers(this);
  103741. }
  103742. };
  103743. TemplateManager.prototype.dispose = function () {
  103744. var _this = this;
  103745. Object.keys(this.templates).forEach(function (template) {
  103746. _this.templates[template].dispose();
  103747. });
  103748. this.onInit.clear();
  103749. this.onAllLoaded.clear();
  103750. this.onEventTriggered.clear();
  103751. this.onLoaded.clear();
  103752. this.onStateChange.clear();
  103753. };
  103754. return TemplateManager;
  103755. }());
  103756. exports.TemplateManager = TemplateManager;
  103757. var Handlebars = __webpack_require__(20);
  103758. var eventManager_1 = __webpack_require__(21);
  103759. Handlebars.registerHelper('eachInMap', function (map, block) {
  103760. var out = '';
  103761. Object.keys(map).map(function (prop) {
  103762. var data = map[prop];
  103763. if (typeof data === 'object') {
  103764. data.id = data.id || prop;
  103765. out += block.fn(data);
  103766. }
  103767. else {
  103768. out += block.fn({ id: prop, value: data });
  103769. }
  103770. });
  103771. return out;
  103772. });
  103773. var Template = (function () {
  103774. function Template(name, _configuration) {
  103775. var _this = this;
  103776. this.name = name;
  103777. this._configuration = _configuration;
  103778. this.onInit = new babylonjs_1.Observable();
  103779. this.onLoaded = new babylonjs_1.Observable();
  103780. this.onAppended = new babylonjs_1.Observable();
  103781. this.onStateChange = new babylonjs_1.Observable();
  103782. this.onEventTriggered = new babylonjs_1.Observable();
  103783. this.loadRequests = [];
  103784. this.isLoaded = false;
  103785. this.isShown = false;
  103786. this.isInHtmlTree = false;
  103787. this.onInit.notifyObservers(this);
  103788. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103789. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103790. if (htmlTemplate) {
  103791. _this.htmlTemplate = htmlTemplate;
  103792. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103793. var config = _this._configuration.params || {};
  103794. var rawHtml = compiledTemplate(config);
  103795. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103796. _this.isLoaded = true;
  103797. _this.isShown = true;
  103798. _this.onLoaded.notifyObservers(_this);
  103799. }
  103800. return _this;
  103801. });
  103802. }
  103803. Template.prototype.updateParams = function (params) {
  103804. this._configuration.params = params;
  103805. if (this.isLoaded) {
  103806. this.dispose();
  103807. }
  103808. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103809. var config = this._configuration.params || {};
  103810. var rawHtml = compiledTemplate(config);
  103811. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103812. if (this.parent) {
  103813. this.appendTo(this.parent, true);
  103814. }
  103815. };
  103816. Object.defineProperty(Template.prototype, "configuration", {
  103817. get: function () {
  103818. return this._configuration;
  103819. },
  103820. enumerable: true,
  103821. configurable: true
  103822. });
  103823. Template.prototype.getChildElements = function () {
  103824. var childrenArray = [];
  103825. var children = this.fragment.children;
  103826. if (!children) {
  103827. children = this.fragment.querySelectorAll('*');
  103828. }
  103829. for (var i = 0; i < children.length; ++i) {
  103830. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103831. }
  103832. return childrenArray;
  103833. };
  103834. Template.prototype.appendTo = function (parent, forceRemove) {
  103835. var _this = this;
  103836. if (this.parent) {
  103837. if (forceRemove) {
  103838. this.parent.removeChild(this.fragment);
  103839. }
  103840. else {
  103841. return;
  103842. }
  103843. }
  103844. this.parent = parent;
  103845. if (this._configuration.id) {
  103846. this.parent.id = this._configuration.id;
  103847. }
  103848. this.fragment = this.parent.appendChild(this.fragment);
  103849. setTimeout(function () {
  103850. _this.registerEvents();
  103851. _this.onAppended.notifyObservers(_this);
  103852. });
  103853. };
  103854. Template.prototype.show = function (visibilityFunction) {
  103855. var _this = this;
  103856. if (this.isHiding)
  103857. return Promise.resolve(this);
  103858. return Promise.resolve().then(function () {
  103859. _this.isShowing = true;
  103860. if (visibilityFunction) {
  103861. return visibilityFunction(_this);
  103862. }
  103863. else {
  103864. _this.parent.style.display = 'flex';
  103865. return _this;
  103866. }
  103867. }).then(function () {
  103868. _this.isShown = true;
  103869. _this.isShowing = false;
  103870. _this.onStateChange.notifyObservers(_this);
  103871. return _this;
  103872. });
  103873. };
  103874. Template.prototype.hide = function (visibilityFunction) {
  103875. var _this = this;
  103876. if (this.isShowing)
  103877. return Promise.resolve(this);
  103878. return Promise.resolve().then(function () {
  103879. _this.isHiding = true;
  103880. if (visibilityFunction) {
  103881. return visibilityFunction(_this);
  103882. }
  103883. else {
  103884. _this.parent.style.display = 'hide';
  103885. return _this;
  103886. }
  103887. }).then(function () {
  103888. _this.isShown = false;
  103889. _this.isHiding = false;
  103890. _this.onStateChange.notifyObservers(_this);
  103891. return _this;
  103892. });
  103893. };
  103894. Template.prototype.dispose = function () {
  103895. this.onAppended.clear();
  103896. this.onEventTriggered.clear();
  103897. this.onInit.clear();
  103898. this.onLoaded.clear();
  103899. this.onStateChange.clear();
  103900. this.isLoaded = false;
  103901. this.parent.removeChild(this.fragment);
  103902. this.loadRequests.forEach(function (request) {
  103903. request.abort();
  103904. });
  103905. };
  103906. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  103907. var _this = this;
  103908. if (!templateConfig) {
  103909. return Promise.reject('No templateConfig provided');
  103910. }
  103911. else if (templateConfig.html !== undefined) {
  103912. return Promise.resolve(templateConfig.html);
  103913. }
  103914. else {
  103915. var location_1 = getTemplateLocation(templateConfig);
  103916. if (helper_1.isUrl(location_1)) {
  103917. return new Promise(function (resolve, reject) {
  103918. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  103919. resolve(data);
  103920. }, undefined, undefined, false, function (request, error) {
  103921. reject(error);
  103922. });
  103923. _this.loadRequests.push(fileRequest);
  103924. });
  103925. }
  103926. else {
  103927. location_1 = location_1.replace('#', '');
  103928. var element = document.getElementById(location_1);
  103929. if (element) {
  103930. return Promise.resolve(element.innerHTML);
  103931. }
  103932. else {
  103933. return Promise.reject('Template ID not found');
  103934. }
  103935. }
  103936. }
  103937. };
  103938. Template.prototype.registerEvents = function () {
  103939. var _this = this;
  103940. this.registeredEvents = this.registeredEvents || [];
  103941. if (this.registeredEvents.length) {
  103942. this.registeredEvents.forEach(function (evt) {
  103943. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  103944. });
  103945. }
  103946. if (this._configuration.events) {
  103947. var _loop_1 = function (eventName) {
  103948. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  103949. var functionToFire_1 = function (selector, event) {
  103950. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  103951. };
  103952. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  103953. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  103954. }
  103955. else if (typeof this_1._configuration.events[eventName] === 'object') {
  103956. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  103957. var event_1 = this_1._configuration.events[eventName] || {};
  103958. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  103959. if (selector && selector.indexOf('#') !== 0) {
  103960. selector = '#' + selector;
  103961. }
  103962. var htmlElement = _this.parent.querySelector(selector);
  103963. if (htmlElement) {
  103964. var binding = functionToFire_1.bind(_this, selector);
  103965. htmlElement.addEventListener(eventName, binding, false);
  103966. _this.registeredEvents.push({
  103967. htmlElement: htmlElement,
  103968. eventName: eventName,
  103969. function: binding
  103970. });
  103971. }
  103972. });
  103973. }
  103974. }
  103975. };
  103976. var this_1 = this;
  103977. for (var eventName in this._configuration.events) {
  103978. _loop_1(eventName);
  103979. }
  103980. }
  103981. };
  103982. return Template;
  103983. }());
  103984. exports.Template = Template;
  103985. function getTemplateLocation(templateConfig) {
  103986. if (!templateConfig || typeof templateConfig === 'string') {
  103987. return templateConfig;
  103988. }
  103989. else {
  103990. return templateConfig.location;
  103991. }
  103992. }
  103993. exports.getTemplateLocation = getTemplateLocation;
  103994. /***/ }),
  103995. /* 20 */
  103996. /***/ (function(module, exports, __webpack_require__) {
  103997. /**!
  103998. @license
  103999. handlebars v4.0.11
  104000. Copyright (C) 2011-2017 by Yehuda Katz
  104001. Permission is hereby granted, free of charge, to any person obtaining a copy
  104002. of this software and associated documentation files (the "Software"), to deal
  104003. in the Software without restriction, including without limitation the rights
  104004. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104005. copies of the Software, and to permit persons to whom the Software is
  104006. furnished to do so, subject to the following conditions:
  104007. The above copyright notice and this permission notice shall be included in
  104008. all copies or substantial portions of the Software.
  104009. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104010. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104011. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104012. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104013. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104014. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104015. THE SOFTWARE.
  104016. */
  104017. !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],
  104018. 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){
  104019. 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"]}])});
  104020. /***/ }),
  104021. /* 21 */
  104022. /***/ (function(module, exports, __webpack_require__) {
  104023. "use strict";
  104024. Object.defineProperty(exports, "__esModule", { value: true });
  104025. var EventManager = (function () {
  104026. function EventManager(templateManager) {
  104027. var _this = this;
  104028. this.templateManager = templateManager;
  104029. this.callbacksContainer = {};
  104030. this.templateManager.onEventTriggered.add(function (eventData) {
  104031. _this.eventTriggered(eventData);
  104032. });
  104033. }
  104034. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104035. if (!this.callbacksContainer[templateName]) {
  104036. this.callbacksContainer[templateName] = [];
  104037. }
  104038. this.callbacksContainer[templateName].push({
  104039. eventType: eventType,
  104040. callback: callback
  104041. });
  104042. };
  104043. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104044. var callbackDefs = this.callbacksContainer[templateName] || [];
  104045. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104046. };
  104047. EventManager.prototype.eventTriggered = function (data) {
  104048. var templateName = data.template.name;
  104049. var eventType = data.event.type;
  104050. var selector = data.selector;
  104051. var callbackDefs = this.callbacksContainer[templateName] || [];
  104052. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104053. callbackDef.callback(data);
  104054. });
  104055. };
  104056. return EventManager;
  104057. }());
  104058. exports.EventManager = EventManager;
  104059. /***/ }),
  104060. /* 22 */
  104061. /***/ (function(module, exports, __webpack_require__) {
  104062. "use strict";
  104063. Object.defineProperty(exports, "__esModule", { value: true });
  104064. var mappers_1 = __webpack_require__(1);
  104065. var types_1 = __webpack_require__(23);
  104066. var deepmerge = __webpack_require__(13);
  104067. var babylonjs_1 = __webpack_require__(0);
  104068. var ConfigurationLoader = (function () {
  104069. function ConfigurationLoader() {
  104070. this.configurationCache = {};
  104071. this.loadRequests = [];
  104072. }
  104073. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104074. var _this = this;
  104075. if (initConfig === void 0) { initConfig = {}; }
  104076. var loadedConfig = deepmerge({}, initConfig);
  104077. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104078. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104079. if (loadedConfig.configuration) {
  104080. var mapperType_1 = "json";
  104081. return Promise.resolve().then(function () {
  104082. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104083. var url = '';
  104084. if (typeof loadedConfig.configuration === "string") {
  104085. url = loadedConfig.configuration;
  104086. }
  104087. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104088. url = loadedConfig.configuration.url;
  104089. var type = loadedConfig.configuration.mapper;
  104090. if (!type) {
  104091. type = loadedConfig.configuration.url.split('.').pop();
  104092. }
  104093. mapperType_1 = type || mapperType_1;
  104094. }
  104095. return _this.loadFile(url);
  104096. }
  104097. else {
  104098. if (typeof loadedConfig.configuration === "object") {
  104099. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104100. return loadedConfig.configuration.payload || {};
  104101. }
  104102. return {};
  104103. }
  104104. }).then(function (data) {
  104105. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104106. var parsed = mapper.map(data);
  104107. var merged = deepmerge(loadedConfig, parsed);
  104108. if (callback)
  104109. callback(merged);
  104110. return merged;
  104111. });
  104112. }
  104113. else {
  104114. if (callback)
  104115. callback(loadedConfig);
  104116. return Promise.resolve(loadedConfig);
  104117. }
  104118. };
  104119. ConfigurationLoader.prototype.dispose = function () {
  104120. this.loadRequests.forEach(function (request) {
  104121. request.abort();
  104122. });
  104123. };
  104124. ConfigurationLoader.prototype.loadFile = function (url) {
  104125. var _this = this;
  104126. var cacheReference = this.configurationCache;
  104127. if (cacheReference[url]) {
  104128. return Promise.resolve(cacheReference[url]);
  104129. }
  104130. return new Promise(function (resolve, reject) {
  104131. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104132. reject(error);
  104133. });
  104134. _this.loadRequests.push(fileRequest);
  104135. });
  104136. };
  104137. return ConfigurationLoader;
  104138. }());
  104139. exports.ConfigurationLoader = ConfigurationLoader;
  104140. exports.configurationLoader = new ConfigurationLoader();
  104141. exports.default = exports.configurationLoader;
  104142. /***/ }),
  104143. /* 23 */
  104144. /***/ (function(module, exports, __webpack_require__) {
  104145. "use strict";
  104146. Object.defineProperty(exports, "__esModule", { value: true });
  104147. var minimal_1 = __webpack_require__(24);
  104148. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104149. var default_1 = __webpack_require__(25);
  104150. exports.defaultConfiguration = default_1.defaultConfiguration;
  104151. var getConfigurationType = function (type) {
  104152. switch (type) {
  104153. case 'default':
  104154. return default_1.defaultConfiguration;
  104155. case 'minimal':
  104156. return minimal_1.minimalConfiguration;
  104157. case 'none':
  104158. return {};
  104159. default:
  104160. return default_1.defaultConfiguration;
  104161. }
  104162. };
  104163. exports.getConfigurationType = getConfigurationType;
  104164. /***/ }),
  104165. /* 24 */
  104166. /***/ (function(module, exports, __webpack_require__) {
  104167. "use strict";
  104168. Object.defineProperty(exports, "__esModule", { value: true });
  104169. exports.minimalConfiguration = {
  104170. version: "0.1",
  104171. templates: {
  104172. main: {
  104173. html: __webpack_require__(6)
  104174. },
  104175. loadingScreen: {
  104176. html: __webpack_require__(7),
  104177. params: {
  104178. backgroundColor: "#000000",
  104179. loadingImage: __webpack_require__(8)
  104180. }
  104181. },
  104182. viewer: {
  104183. html: __webpack_require__(9),
  104184. },
  104185. overlay: {
  104186. html: __webpack_require__(10),
  104187. params: {
  104188. closeImage: __webpack_require__(11),
  104189. closeText: 'Close'
  104190. }
  104191. },
  104192. error: {
  104193. html: __webpack_require__(12)
  104194. }
  104195. },
  104196. engine: {
  104197. antialiasing: true
  104198. }
  104199. };
  104200. /***/ }),
  104201. /* 25 */
  104202. /***/ (function(module, exports, __webpack_require__) {
  104203. "use strict";
  104204. Object.defineProperty(exports, "__esModule", { value: true });
  104205. exports.defaultConfiguration = {
  104206. version: "3.2.0-alpha4",
  104207. templates: {
  104208. main: {
  104209. html: __webpack_require__(6)
  104210. },
  104211. loadingScreen: {
  104212. html: __webpack_require__(7),
  104213. params: {
  104214. backgroundColor: "#000000",
  104215. loadingImage: __webpack_require__(8)
  104216. }
  104217. },
  104218. viewer: {
  104219. html: __webpack_require__(9),
  104220. events: {
  104221. pointerout: true,
  104222. pointerdown: true,
  104223. pointerup: true
  104224. }
  104225. },
  104226. navBar: {
  104227. html: __webpack_require__(26),
  104228. params: {
  104229. buttons: {
  104230. "fullscreen-button": {
  104231. altText: "Fullscreen",
  104232. image: __webpack_require__(27)
  104233. }
  104234. },
  104235. visibilityTimeout: 2000
  104236. },
  104237. events: {
  104238. pointerdown: { 'fullscreen-button': true },
  104239. pointerover: true
  104240. }
  104241. },
  104242. overlay: {
  104243. html: __webpack_require__(10),
  104244. params: {
  104245. closeImage: __webpack_require__(11),
  104246. closeText: 'Close'
  104247. }
  104248. },
  104249. help: {
  104250. html: __webpack_require__(28)
  104251. },
  104252. share: {
  104253. html: __webpack_require__(29)
  104254. },
  104255. error: {
  104256. html: __webpack_require__(12)
  104257. }
  104258. },
  104259. camera: {
  104260. behaviors: {
  104261. autoRotate: 0,
  104262. framing: {
  104263. type: 2,
  104264. zoomOnBoundingInfo: true,
  104265. zoomStopsAnimation: false
  104266. }
  104267. }
  104268. },
  104269. skybox: {
  104270. pbr: true,
  104271. blur: 0.7,
  104272. infiniteDIstance: false,
  104273. },
  104274. ground: true,
  104275. engine: {
  104276. antialiasing: true
  104277. },
  104278. scene: {
  104279. imageProcessingConfiguration: {
  104280. exposure: 1.4,
  104281. contrast: 1.66,
  104282. toneMappingEnabled: true
  104283. }
  104284. }
  104285. };
  104286. /***/ }),
  104287. /* 26 */
  104288. /***/ (function(module, exports) {
  104289. 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>";
  104290. /***/ }),
  104291. /* 27 */
  104292. /***/ (function(module, exports) {
  104293. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104294. /***/ }),
  104295. /* 28 */
  104296. /***/ (function(module, exports) {
  104297. module.exports = "HELP";
  104298. /***/ }),
  104299. /* 29 */
  104300. /***/ (function(module, exports) {
  104301. module.exports = "SHARE";
  104302. /***/ }),
  104303. /* 30 */
  104304. /***/ (function(module, exports, __webpack_require__) {
  104305. "use strict";
  104306. Object.defineProperty(exports, "__esModule", { value: true });
  104307. var babylonjs_1 = __webpack_require__(0);
  104308. var modelAnimation_1 = __webpack_require__(31);
  104309. var ViewerModel = (function () {
  104310. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104311. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104312. this._modelConfiguration = _modelConfiguration;
  104313. this._scene = _scene;
  104314. this.onLoadedObservable = new babylonjs_1.Observable();
  104315. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104316. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104317. this._animations = [];
  104318. if (!disableAutoLoad) {
  104319. this._initLoad();
  104320. }
  104321. }
  104322. ViewerModel.prototype.load = function () {
  104323. if (this.loader) {
  104324. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104325. }
  104326. else {
  104327. this._initLoad();
  104328. }
  104329. };
  104330. ViewerModel.prototype.getAnimationNames = function () {
  104331. return this._animations.map(function (a) { return a.name; });
  104332. };
  104333. ViewerModel.prototype._getAnimationByName = function (name) {
  104334. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104335. if (filtered.length === 1) {
  104336. return filtered[0];
  104337. }
  104338. else {
  104339. return null;
  104340. }
  104341. };
  104342. ViewerModel.prototype.playAnimation = function (name) {
  104343. var animation = this._getAnimationByName(name);
  104344. if (animation) {
  104345. if (this.currentAnimation) {
  104346. this.currentAnimation.stop();
  104347. }
  104348. this.currentAnimation = animation;
  104349. animation.start();
  104350. return animation;
  104351. }
  104352. else {
  104353. throw new Error("animation not found - " + name);
  104354. }
  104355. };
  104356. ViewerModel.prototype._initLoad = function () {
  104357. var _this = this;
  104358. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104359. return babylonjs_1.Tools.Error("No model URL to load.");
  104360. }
  104361. var parts = this._modelConfiguration.url.split('/');
  104362. var filename = parts.pop() || this._modelConfiguration.url;
  104363. var base = parts.length ? parts.join('/') + '/' : './';
  104364. var plugin = this._modelConfiguration.loader;
  104365. var animationsArray = this._scene.animationGroups.slice();
  104366. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104367. meshes.forEach(function (mesh) {
  104368. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104369. });
  104370. _this.meshes = meshes;
  104371. _this.particleSystems = particleSystems;
  104372. _this.skeletons = skeletons;
  104373. if (_this.loader.name === 'gltf') {
  104374. _this._scene.animationGroups.forEach(function (ag) {
  104375. if (animationsArray.indexOf(ag) === -1) {
  104376. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104377. }
  104378. });
  104379. }
  104380. else {
  104381. skeletons.forEach(function (skeleton, idx) {
  104382. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104383. skeleton.getAnimatables().forEach(function (a) {
  104384. if (a.animations[0]) {
  104385. ag.addTargetedAnimation(a.animations[0], a);
  104386. }
  104387. });
  104388. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104389. });
  104390. }
  104391. if (_this._modelConfiguration.animation) {
  104392. if (_this._modelConfiguration.animation.playOnce) {
  104393. _this._animations.forEach(function (a) {
  104394. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104395. });
  104396. }
  104397. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104398. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104399. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104400. _this.playAnimation(animationName);
  104401. }
  104402. }
  104403. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104404. }, function (progressEvent) {
  104405. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104406. }, function (e, m, exception) {
  104407. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104408. }, plugin);
  104409. this.loader['animationStartMode'] = 0;
  104410. };
  104411. ViewerModel.prototype.dispose = function () {
  104412. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104413. this.skeletons.forEach(function (s) { return s.dispose(); });
  104414. this._animations.forEach(function (ag) { return ag.dispose(); });
  104415. this.meshes.forEach(function (m) { return m.dispose(); });
  104416. };
  104417. return ViewerModel;
  104418. }());
  104419. exports.ViewerModel = ViewerModel;
  104420. /***/ }),
  104421. /* 31 */
  104422. /***/ (function(module, exports, __webpack_require__) {
  104423. "use strict";
  104424. Object.defineProperty(exports, "__esModule", { value: true });
  104425. var AnimationPlayMode;
  104426. (function (AnimationPlayMode) {
  104427. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104428. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104429. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104430. var AnimationState;
  104431. (function (AnimationState) {
  104432. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104433. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104434. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104435. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104436. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104437. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104438. var GroupModelAnimation = (function () {
  104439. function GroupModelAnimation(_animationGroup) {
  104440. var _this = this;
  104441. this._animationGroup = _animationGroup;
  104442. this._state = AnimationState.INIT;
  104443. this._playMode = AnimationPlayMode.LOOP;
  104444. this._animationGroup.onAnimationEndObservable.add(function () {
  104445. _this.stop();
  104446. _this._state = AnimationState.ENDED;
  104447. });
  104448. }
  104449. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104450. get: function () {
  104451. return this._animationGroup.name;
  104452. },
  104453. enumerable: true,
  104454. configurable: true
  104455. });
  104456. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104457. get: function () {
  104458. return this._state;
  104459. },
  104460. enumerable: true,
  104461. configurable: true
  104462. });
  104463. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104464. get: function () {
  104465. return this._animationGroup.speedRatio;
  104466. },
  104467. set: function (value) {
  104468. this._animationGroup.speedRatio = value;
  104469. },
  104470. enumerable: true,
  104471. configurable: true
  104472. });
  104473. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104474. get: function () {
  104475. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104476. var keys = ta.animation.getKeys();
  104477. return keys[keys.length - 1].frame;
  104478. });
  104479. return Math.max.apply(null, animationFrames);
  104480. },
  104481. enumerable: true,
  104482. configurable: true
  104483. });
  104484. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104485. get: function () {
  104486. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104487. var animatable = this._animationGroup.animatables[i];
  104488. var animations = animatable.getAnimations();
  104489. if (!animations || !animations.length) {
  104490. continue;
  104491. }
  104492. for (var idx = 0; idx < animations.length; ++idx) {
  104493. if (animations[idx].currentFrame) {
  104494. return animations[idx].currentFrame;
  104495. }
  104496. }
  104497. }
  104498. return 0;
  104499. },
  104500. enumerable: true,
  104501. configurable: true
  104502. });
  104503. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104504. get: function () {
  104505. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104506. var animatable = this._animationGroup.animatables[i];
  104507. var animations = animatable.getAnimations();
  104508. if (!animations || !animations.length) {
  104509. continue;
  104510. }
  104511. for (var idx = 0; idx < animations.length; ++idx) {
  104512. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104513. return animations[idx].animation.framePerSecond;
  104514. }
  104515. }
  104516. }
  104517. return 0;
  104518. },
  104519. enumerable: true,
  104520. configurable: true
  104521. });
  104522. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104523. get: function () {
  104524. return this._playMode;
  104525. },
  104526. set: function (value) {
  104527. if (value === this._playMode) {
  104528. return;
  104529. }
  104530. this._playMode = value;
  104531. if (this.state === AnimationState.PLAYING) {
  104532. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104533. }
  104534. else {
  104535. this._animationGroup.reset();
  104536. this._state = AnimationState.INIT;
  104537. }
  104538. },
  104539. enumerable: true,
  104540. configurable: true
  104541. });
  104542. GroupModelAnimation.prototype.reset = function () {
  104543. this._animationGroup.reset();
  104544. };
  104545. GroupModelAnimation.prototype.restart = function () {
  104546. this._animationGroup.restart();
  104547. };
  104548. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104549. this._animationGroup['_animatables'].forEach(function (a) {
  104550. a.goToFrame(frameNumber);
  104551. });
  104552. };
  104553. GroupModelAnimation.prototype.start = function () {
  104554. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104555. if (this._animationGroup.isStarted) {
  104556. this._state = AnimationState.PLAYING;
  104557. }
  104558. };
  104559. GroupModelAnimation.prototype.pause = function () {
  104560. this._animationGroup.pause();
  104561. this._state = AnimationState.PAUSED;
  104562. };
  104563. GroupModelAnimation.prototype.stop = function () {
  104564. this._animationGroup.stop();
  104565. if (!this._animationGroup.isStarted) {
  104566. this._state = AnimationState.STOPPED;
  104567. }
  104568. };
  104569. GroupModelAnimation.prototype.dispose = function () {
  104570. this._animationGroup.dispose();
  104571. };
  104572. return GroupModelAnimation;
  104573. }());
  104574. exports.GroupModelAnimation = GroupModelAnimation;
  104575. /***/ }),
  104576. /* 32 */
  104577. /***/ (function(module, exports, __webpack_require__) {
  104578. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  104579. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  104580. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  104581. 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;
  104582. return c > 3 && r && Object.defineProperty(target, key, r), r;
  104583. };
  104584. var __extends = (this && this.__extends) || (function () {
  104585. var extendStatics = Object.setPrototypeOf ||
  104586. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104587. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104588. return function (d, b) {
  104589. extendStatics(d, b);
  104590. function __() { this.constructor = d; }
  104591. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104592. };
  104593. })();
  104594. (function universalModuleDefinition(root, factory) {
  104595. if(true)
  104596. module.exports = factory(__webpack_require__(0));
  104597. else if(typeof define === 'function' && define.amd)
  104598. define("babylonjs-loaders", ["babylonjs"], factory);
  104599. else if(typeof exports === 'object')
  104600. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  104601. else {
  104602. root["BABYLON"] = factory(root["BABYLON"]);
  104603. }
  104604. })(this, function(BABYLON) {
  104605. var BABYLON;
  104606. (function (BABYLON) {
  104607. var STLFileLoader = /** @class */ (function () {
  104608. function STLFileLoader() {
  104609. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104610. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104611. 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;
  104612. 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;
  104613. this.name = "stl";
  104614. // force data to come in as an ArrayBuffer
  104615. // we'll convert to string if it looks like it's an ASCII .stl
  104616. this.extensions = {
  104617. ".stl": { isBinary: true },
  104618. };
  104619. }
  104620. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104621. var matches;
  104622. if (this.isBinary(data)) {
  104623. // binary .stl
  104624. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104625. this.parseBinary(babylonMesh, data);
  104626. if (meshes) {
  104627. meshes.push(babylonMesh);
  104628. }
  104629. return true;
  104630. }
  104631. // ASCII .stl
  104632. // convert to string
  104633. var array_buffer = new Uint8Array(data);
  104634. var str = '';
  104635. for (var i = 0; i < data.byteLength; i++) {
  104636. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104637. }
  104638. data = str;
  104639. while (matches = this.solidPattern.exec(data)) {
  104640. var meshName = matches[1];
  104641. var meshNameFromEnd = matches[3];
  104642. if (meshName != meshNameFromEnd) {
  104643. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104644. return false;
  104645. }
  104646. // check meshesNames
  104647. if (meshesNames && meshName) {
  104648. if (meshesNames instanceof Array) {
  104649. if (!meshesNames.indexOf(meshName)) {
  104650. continue;
  104651. }
  104652. }
  104653. else {
  104654. if (meshName !== meshesNames) {
  104655. continue;
  104656. }
  104657. }
  104658. }
  104659. // stl mesh name can be empty as well
  104660. meshName = meshName || "stlmesh";
  104661. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104662. this.parseASCII(babylonMesh, matches[2]);
  104663. if (meshes) {
  104664. meshes.push(babylonMesh);
  104665. }
  104666. }
  104667. return true;
  104668. };
  104669. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104670. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104671. if (result) {
  104672. scene.createDefaultCameraOrLight();
  104673. }
  104674. return result;
  104675. };
  104676. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104677. var container = new BABYLON.AssetContainer(scene);
  104678. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104679. container.removeAllFromScene();
  104680. return container;
  104681. };
  104682. STLFileLoader.prototype.isBinary = function (data) {
  104683. // check if file size is correct for binary stl
  104684. var faceSize, nFaces, reader;
  104685. reader = new DataView(data);
  104686. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104687. nFaces = reader.getUint32(80, true);
  104688. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104689. return true;
  104690. }
  104691. // check characters higher than ASCII to confirm binary
  104692. var fileLength = reader.byteLength;
  104693. for (var index = 0; index < fileLength; index++) {
  104694. if (reader.getUint8(index) > 127) {
  104695. return true;
  104696. }
  104697. }
  104698. return false;
  104699. };
  104700. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104701. var reader = new DataView(data);
  104702. var faces = reader.getUint32(80, true);
  104703. var dataOffset = 84;
  104704. var faceLength = 12 * 4 + 2;
  104705. var offset = 0;
  104706. var positions = new Float32Array(faces * 3 * 3);
  104707. var normals = new Float32Array(faces * 3 * 3);
  104708. var indices = new Uint32Array(faces * 3);
  104709. var indicesCount = 0;
  104710. for (var face = 0; face < faces; face++) {
  104711. var start = dataOffset + face * faceLength;
  104712. var normalX = reader.getFloat32(start, true);
  104713. var normalY = reader.getFloat32(start + 4, true);
  104714. var normalZ = reader.getFloat32(start + 8, true);
  104715. for (var i = 1; i <= 3; i++) {
  104716. var vertexstart = start + i * 12;
  104717. // ordering is intentional to match ascii import
  104718. positions[offset] = reader.getFloat32(vertexstart, true);
  104719. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104720. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104721. normals[offset] = normalX;
  104722. normals[offset + 2] = normalY;
  104723. normals[offset + 1] = normalZ;
  104724. offset += 3;
  104725. }
  104726. indices[indicesCount] = indicesCount++;
  104727. indices[indicesCount] = indicesCount++;
  104728. indices[indicesCount] = indicesCount++;
  104729. }
  104730. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104731. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104732. mesh.setIndices(indices);
  104733. mesh.computeWorldMatrix(true);
  104734. };
  104735. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104736. var positions = [];
  104737. var normals = [];
  104738. var indices = [];
  104739. var indicesCount = 0;
  104740. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104741. var matches;
  104742. while (matches = this.facetsPattern.exec(solidData)) {
  104743. var facet = matches[1];
  104744. //one normal per face
  104745. var normalMatches = this.normalPattern.exec(facet);
  104746. this.normalPattern.lastIndex = 0;
  104747. if (!normalMatches) {
  104748. continue;
  104749. }
  104750. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104751. var vertexMatch;
  104752. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104753. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104754. normals.push(normal[0], normal[1], normal[2]);
  104755. }
  104756. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104757. this.vertexPattern.lastIndex = 0;
  104758. }
  104759. this.facetsPattern.lastIndex = 0;
  104760. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104761. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104762. mesh.setIndices(indices);
  104763. mesh.computeWorldMatrix(true);
  104764. };
  104765. return STLFileLoader;
  104766. }());
  104767. BABYLON.STLFileLoader = STLFileLoader;
  104768. if (BABYLON.SceneLoader) {
  104769. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104770. }
  104771. })(BABYLON || (BABYLON = {}));
  104772. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104773. var BABYLON;
  104774. (function (BABYLON) {
  104775. /**
  104776. * Class reading and parsing the MTL file bundled with the obj file.
  104777. */
  104778. var MTLFileLoader = /** @class */ (function () {
  104779. function MTLFileLoader() {
  104780. // All material loaded from the mtl will be set here
  104781. this.materials = [];
  104782. }
  104783. /**
  104784. * This function will read the mtl file and create each material described inside
  104785. * This function could be improve by adding :
  104786. * -some component missing (Ni, Tf...)
  104787. * -including the specific options available
  104788. *
  104789. * @param scene
  104790. * @param data
  104791. * @param rootUrl
  104792. */
  104793. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104794. //Split the lines from the file
  104795. var lines = data.split('\n');
  104796. //Space char
  104797. var delimiter_pattern = /\s+/;
  104798. //Array with RGB colors
  104799. var color;
  104800. //New material
  104801. var material = null;
  104802. //Look at each line
  104803. for (var i = 0; i < lines.length; i++) {
  104804. var line = lines[i].trim();
  104805. // Blank line or comment
  104806. if (line.length === 0 || line.charAt(0) === '#') {
  104807. continue;
  104808. }
  104809. //Get the first parameter (keyword)
  104810. var pos = line.indexOf(' ');
  104811. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104812. key = key.toLowerCase();
  104813. //Get the data following the key
  104814. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104815. //This mtl keyword will create the new material
  104816. if (key === "newmtl") {
  104817. //Check if it is the first material.
  104818. // Materials specifications are described after this keyword.
  104819. if (material) {
  104820. //Add the previous material in the material array.
  104821. this.materials.push(material);
  104822. }
  104823. //Create a new material.
  104824. // value is the name of the material read in the mtl file
  104825. material = new BABYLON.StandardMaterial(value, scene);
  104826. }
  104827. else if (key === "kd" && material) {
  104828. // Diffuse color (color under white light) using RGB values
  104829. //value = "r g b"
  104830. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104831. //color = [r,g,b]
  104832. //Set tghe color into the material
  104833. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104834. }
  104835. else if (key === "ka" && material) {
  104836. // Ambient color (color under shadow) using RGB values
  104837. //value = "r g b"
  104838. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104839. //color = [r,g,b]
  104840. //Set tghe color into the material
  104841. material.ambientColor = BABYLON.Color3.FromArray(color);
  104842. }
  104843. else if (key === "ks" && material) {
  104844. // Specular color (color when light is reflected from shiny surface) using RGB values
  104845. //value = "r g b"
  104846. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104847. //color = [r,g,b]
  104848. //Set the color into the material
  104849. material.specularColor = BABYLON.Color3.FromArray(color);
  104850. }
  104851. else if (key === "ke" && material) {
  104852. // Emissive color using RGB values
  104853. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104854. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104855. }
  104856. else if (key === "ns" && material) {
  104857. //value = "Integer"
  104858. material.specularPower = parseFloat(value);
  104859. }
  104860. else if (key === "d" && material) {
  104861. //d is dissolve for current material. It mean alpha for BABYLON
  104862. material.alpha = parseFloat(value);
  104863. //Texture
  104864. //This part can be improved by adding the possible options of texture
  104865. }
  104866. else if (key === "map_ka" && material) {
  104867. // ambient texture map with a loaded image
  104868. //We must first get the folder of the image
  104869. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104870. }
  104871. else if (key === "map_kd" && material) {
  104872. // Diffuse texture map with a loaded image
  104873. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104874. }
  104875. else if (key === "map_ks" && material) {
  104876. // Specular texture map with a loaded image
  104877. //We must first get the folder of the image
  104878. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104879. }
  104880. else if (key === "map_ns") {
  104881. //Specular
  104882. //Specular highlight component
  104883. //We must first get the folder of the image
  104884. //
  104885. //Not supported by BABYLON
  104886. //
  104887. // continue;
  104888. }
  104889. else if (key === "map_bump" && material) {
  104890. //The bump texture
  104891. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104892. }
  104893. else if (key === "map_d" && material) {
  104894. // The dissolve of the material
  104895. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104896. //Options for illumination
  104897. }
  104898. else if (key === "illum") {
  104899. //Illumination
  104900. if (value === "0") {
  104901. //That mean Kd == Kd
  104902. }
  104903. else if (value === "1") {
  104904. //Color on and Ambient on
  104905. }
  104906. else if (value === "2") {
  104907. //Highlight on
  104908. }
  104909. else if (value === "3") {
  104910. //Reflection on and Ray trace on
  104911. }
  104912. else if (value === "4") {
  104913. //Transparency: Glass on, Reflection: Ray trace on
  104914. }
  104915. else if (value === "5") {
  104916. //Reflection: Fresnel on and Ray trace on
  104917. }
  104918. else if (value === "6") {
  104919. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  104920. }
  104921. else if (value === "7") {
  104922. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  104923. }
  104924. else if (value === "8") {
  104925. //Reflection on and Ray trace off
  104926. }
  104927. else if (value === "9") {
  104928. //Transparency: Glass on, Reflection: Ray trace off
  104929. }
  104930. else if (value === "10") {
  104931. //Casts shadows onto invisible surfaces
  104932. }
  104933. }
  104934. else {
  104935. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  104936. }
  104937. }
  104938. //At the end of the file, add the last material
  104939. if (material) {
  104940. this.materials.push(material);
  104941. }
  104942. };
  104943. /**
  104944. * Gets the texture for the material.
  104945. *
  104946. * If the material is imported from input file,
  104947. * We sanitize the url to ensure it takes the textre from aside the material.
  104948. *
  104949. * @param rootUrl The root url to load from
  104950. * @param value The value stored in the mtl
  104951. * @return The Texture
  104952. */
  104953. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  104954. if (!value) {
  104955. return null;
  104956. }
  104957. var url = rootUrl;
  104958. // Load from input file.
  104959. if (rootUrl === "file:") {
  104960. var lastDelimiter = value.lastIndexOf("\\");
  104961. if (lastDelimiter === -1) {
  104962. lastDelimiter = value.lastIndexOf("/");
  104963. }
  104964. if (lastDelimiter > -1) {
  104965. url += value.substr(lastDelimiter + 1);
  104966. }
  104967. else {
  104968. url += value;
  104969. }
  104970. }
  104971. else {
  104972. url += value;
  104973. }
  104974. return new BABYLON.Texture(url, scene);
  104975. };
  104976. return MTLFileLoader;
  104977. }());
  104978. BABYLON.MTLFileLoader = MTLFileLoader;
  104979. var OBJFileLoader = /** @class */ (function () {
  104980. function OBJFileLoader() {
  104981. this.name = "obj";
  104982. this.extensions = ".obj";
  104983. this.obj = /^o/;
  104984. this.group = /^g/;
  104985. this.mtllib = /^mtllib /;
  104986. this.usemtl = /^usemtl /;
  104987. this.smooth = /^s /;
  104988. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104989. // vn float float float
  104990. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104991. // vt float float
  104992. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104993. // f vertex vertex vertex ...
  104994. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  104995. // f vertex/uvs vertex/uvs vertex/uvs ...
  104996. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104997. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  104998. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104999. // f vertex//normal vertex//normal vertex//normal ...
  105000. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105001. }
  105002. /**
  105003. * Calls synchronously the MTL file attached to this obj.
  105004. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105005. * Without this function materials are not displayed in the first frame (but displayed after).
  105006. * In consequence it is impossible to get material information in your HTML file
  105007. *
  105008. * @param url The URL of the MTL file
  105009. * @param rootUrl
  105010. * @param onSuccess Callback function to be called when the MTL file is loaded
  105011. * @private
  105012. */
  105013. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105014. //The complete path to the mtl file
  105015. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105016. // Loads through the babylon tools to allow fileInput search.
  105017. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105018. };
  105019. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105020. //get the meshes from OBJ file
  105021. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105022. //Push meshes from OBJ file into the variable mesh of this function
  105023. if (meshes) {
  105024. loadedMeshes.forEach(function (mesh) {
  105025. meshes.push(mesh);
  105026. });
  105027. }
  105028. return true;
  105029. };
  105030. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105031. //Get the 3D model
  105032. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105033. };
  105034. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105035. var container = new BABYLON.AssetContainer(scene);
  105036. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105037. container.removeAllFromScene();
  105038. return container;
  105039. };
  105040. /**
  105041. * Read the OBJ file and create an Array of meshes.
  105042. * Each mesh contains all information given by the OBJ and the MTL file.
  105043. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105044. *
  105045. * @param meshesNames
  105046. * @param scene BABYLON.Scene The scene where are displayed the data
  105047. * @param data String The content of the obj file
  105048. * @param rootUrl String The path to the folder
  105049. * @returns Array<AbstractMesh>
  105050. * @private
  105051. */
  105052. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105053. var positions = []; //values for the positions of vertices
  105054. var normals = []; //Values for the normals
  105055. var uvs = []; //Values for the textures
  105056. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105057. var handledMesh; //The current mesh of meshes array
  105058. var indicesForBabylon = []; //The list of indices for VertexData
  105059. var wrappedPositionForBabylon = []; //The list of position in vectors
  105060. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105061. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105062. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105063. var curPositionInIndices = 0;
  105064. var hasMeshes = false; //Meshes are defined in the file
  105065. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105066. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105067. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105068. var triangles = []; //Indices from new triangles coming from polygons
  105069. var materialNameFromObj = ""; //The name of the current material
  105070. var fileToLoad = ""; //The name of the mtlFile to load
  105071. var materialsFromMTLFile = new MTLFileLoader();
  105072. var objMeshName = ""; //The name of the current obj mesh
  105073. var increment = 1; //Id for meshes created by the multimaterial
  105074. var isFirstMaterial = true;
  105075. /**
  105076. * Search for obj in the given array.
  105077. * This function is called to check if a couple of data already exists in an array.
  105078. *
  105079. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105080. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105081. * @param obj Array<number>
  105082. * @returns {boolean}
  105083. */
  105084. var isInArray = function (arr, obj) {
  105085. if (!arr[obj[0]])
  105086. arr[obj[0]] = { normals: [], idx: [] };
  105087. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105088. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105089. };
  105090. var isInArrayUV = function (arr, obj) {
  105091. if (!arr[obj[0]])
  105092. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105093. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105094. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105095. return arr[obj[0]].idx[idx];
  105096. }
  105097. return -1;
  105098. };
  105099. /**
  105100. * This function set the data for each triangle.
  105101. * Data are position, normals and uvs
  105102. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105103. * If the tuple already exist, add only their indice
  105104. *
  105105. * @param indicePositionFromObj Integer The index in positions array
  105106. * @param indiceUvsFromObj Integer The index in uvs array
  105107. * @param indiceNormalFromObj Integer The index in normals array
  105108. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105109. * @param textureVectorFromOBJ Vector3 The value of uvs
  105110. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105111. */
  105112. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105113. //Check if this tuple already exists in the list of tuples
  105114. var _index;
  105115. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105116. _index = isInArrayUV(tuplePosNorm, [
  105117. indicePositionFromObj,
  105118. indiceNormalFromObj,
  105119. indiceUvsFromObj
  105120. ]);
  105121. }
  105122. else {
  105123. _index = isInArray(tuplePosNorm, [
  105124. indicePositionFromObj,
  105125. indiceNormalFromObj
  105126. ]);
  105127. }
  105128. //If it not exists
  105129. if (_index == -1) {
  105130. //Add an new indice.
  105131. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105132. //We add vertices data in this order
  105133. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105134. //Push the position of vertice for Babylon
  105135. //Each element is a BABYLON.Vector3(x,y,z)
  105136. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105137. //Push the uvs for Babylon
  105138. //Each element is a BABYLON.Vector3(u,v)
  105139. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105140. //Push the normals for Babylon
  105141. //Each element is a BABYLON.Vector3(x,y,z)
  105142. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105143. //Add the tuple in the comparison list
  105144. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105145. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105146. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105147. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105148. }
  105149. else {
  105150. //The tuple already exists
  105151. //Add the index of the already existing tuple
  105152. //At this index we can get the value of position, normal and uvs of vertex
  105153. indicesForBabylon.push(_index);
  105154. }
  105155. };
  105156. /**
  105157. * Transform BABYLON.Vector() object onto 3 digits in an array
  105158. */
  105159. var unwrapData = function () {
  105160. //Every array has the same length
  105161. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105162. //Push the x, y, z values of each element in the unwrapped array
  105163. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105164. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105165. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105166. }
  105167. // Reset arrays for the next new meshes
  105168. wrappedPositionForBabylon = [];
  105169. wrappedNormalsForBabylon = [];
  105170. wrappedUvsForBabylon = [];
  105171. tuplePosNorm = [];
  105172. curPositionInIndices = 0;
  105173. };
  105174. /**
  105175. * Create triangles from polygons by recursion
  105176. * The best to understand how it works is to draw it in the same time you get the recursion.
  105177. * It is important to notice that a triangle is a polygon
  105178. * We get 4 patterns of face defined in OBJ File :
  105179. * facePattern1 = ["1","2","3","4","5","6"]
  105180. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105181. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105182. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105183. * Each pattern is divided by the same method
  105184. * @param face Array[String] The indices of elements
  105185. * @param v Integer The variable to increment
  105186. */
  105187. var getTriangles = function (face, v) {
  105188. //Work for each element of the array
  105189. if (v + 1 < face.length) {
  105190. //Add on the triangle variable the indexes to obtain triangles
  105191. triangles.push(face[0], face[v], face[v + 1]);
  105192. //Incrementation for recursion
  105193. v += 1;
  105194. //Recursion
  105195. getTriangles(face, v);
  105196. }
  105197. //Result obtained after 2 iterations:
  105198. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105199. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105200. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105201. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105202. };
  105203. /**
  105204. * Create triangles and push the data for each polygon for the pattern 1
  105205. * In this pattern we get vertice positions
  105206. * @param face
  105207. * @param v
  105208. */
  105209. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105210. //Get the indices of triangles for each polygon
  105211. getTriangles(face, v);
  105212. //For each element in the triangles array.
  105213. //This var could contains 1 to an infinity of triangles
  105214. for (var k = 0; k < triangles.length; k++) {
  105215. // Set position indice
  105216. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105217. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105218. positions[indicePositionFromObj], //Get the vectors data
  105219. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105220. );
  105221. }
  105222. //Reset variable for the next line
  105223. triangles = [];
  105224. };
  105225. /**
  105226. * Create triangles and push the data for each polygon for the pattern 2
  105227. * In this pattern we get vertice positions and uvsu
  105228. * @param face
  105229. * @param v
  105230. */
  105231. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105232. //Get the indices of triangles for each polygon
  105233. getTriangles(face, v);
  105234. for (var k = 0; k < triangles.length; k++) {
  105235. //triangle[k] = "1/1"
  105236. //Split the data for getting position and uv
  105237. var point = triangles[k].split("/"); // ["1", "1"]
  105238. //Set position indice
  105239. var indicePositionFromObj = parseInt(point[0]) - 1;
  105240. //Set uv indice
  105241. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105242. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105243. positions[indicePositionFromObj], //Get the values for each element
  105244. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105245. );
  105246. }
  105247. //Reset variable for the next line
  105248. triangles = [];
  105249. };
  105250. /**
  105251. * Create triangles and push the data for each polygon for the pattern 3
  105252. * In this pattern we get vertice positions, uvs and normals
  105253. * @param face
  105254. * @param v
  105255. */
  105256. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105257. //Get the indices of triangles for each polygon
  105258. getTriangles(face, v);
  105259. for (var k = 0; k < triangles.length; k++) {
  105260. //triangle[k] = "1/1/1"
  105261. //Split the data for getting position, uv, and normals
  105262. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105263. // Set position indice
  105264. var indicePositionFromObj = parseInt(point[0]) - 1;
  105265. // Set uv indice
  105266. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105267. // Set normal indice
  105268. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105269. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105270. );
  105271. }
  105272. //Reset variable for the next line
  105273. triangles = [];
  105274. };
  105275. /**
  105276. * Create triangles and push the data for each polygon for the pattern 4
  105277. * In this pattern we get vertice positions and normals
  105278. * @param face
  105279. * @param v
  105280. */
  105281. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105282. getTriangles(face, v);
  105283. for (var k = 0; k < triangles.length; k++) {
  105284. //triangle[k] = "1//1"
  105285. //Split the data for getting position and normals
  105286. var point = triangles[k].split("//"); // ["1", "1"]
  105287. // We check indices, and normals
  105288. var indicePositionFromObj = parseInt(point[0]) - 1;
  105289. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105290. setData(indicePositionFromObj, 1, //Default value for uv
  105291. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105292. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105293. }
  105294. //Reset variable for the next line
  105295. triangles = [];
  105296. };
  105297. var addPreviousObjMesh = function () {
  105298. //Check if it is not the first mesh. Otherwise we don't have data.
  105299. if (meshesFromObj.length > 0) {
  105300. //Get the previous mesh for applying the data about the faces
  105301. //=> in obj file, faces definition append after the name of the mesh
  105302. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105303. //Set the data into Array for the mesh
  105304. unwrapData();
  105305. // Reverse tab. Otherwise face are displayed in the wrong sens
  105306. indicesForBabylon.reverse();
  105307. //Set the information for the mesh
  105308. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105309. handledMesh.indices = indicesForBabylon.slice();
  105310. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105311. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105312. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105313. //Reset the array for the next mesh
  105314. indicesForBabylon = [];
  105315. unwrappedPositionsForBabylon = [];
  105316. unwrappedNormalsForBabylon = [];
  105317. unwrappedUVForBabylon = [];
  105318. }
  105319. };
  105320. //Main function
  105321. //Split the file into lines
  105322. var lines = data.split('\n');
  105323. //Look at each line
  105324. for (var i = 0; i < lines.length; i++) {
  105325. var line = lines[i].trim();
  105326. var result;
  105327. //Comment or newLine
  105328. if (line.length === 0 || line.charAt(0) === '#') {
  105329. continue;
  105330. //Get information about one position possible for the vertices
  105331. }
  105332. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105333. //Create a Vector3 with the position x, y, z
  105334. //Value of result:
  105335. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105336. //Add the Vector in the list of positions
  105337. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105338. }
  105339. else if ((result = this.normalPattern.exec(line)) !== null) {
  105340. //Create a Vector3 with the normals x, y, z
  105341. //Value of result
  105342. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105343. //Add the Vector in the list of normals
  105344. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105345. }
  105346. else if ((result = this.uvPattern.exec(line)) !== null) {
  105347. //Create a Vector2 with the normals u, v
  105348. //Value of result
  105349. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105350. //Add the Vector in the list of uvs
  105351. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105352. //Identify patterns of faces
  105353. //Face could be defined in different type of pattern
  105354. }
  105355. else if ((result = this.facePattern3.exec(line)) !== null) {
  105356. //Value of result:
  105357. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105358. //Set the data for this face
  105359. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105360. 1);
  105361. }
  105362. else if ((result = this.facePattern4.exec(line)) !== null) {
  105363. //Value of result:
  105364. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105365. //Set the data for this face
  105366. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105367. 1);
  105368. }
  105369. else if ((result = this.facePattern2.exec(line)) !== null) {
  105370. //Value of result:
  105371. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105372. //Set the data for this face
  105373. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105374. 1);
  105375. }
  105376. else if ((result = this.facePattern1.exec(line)) !== null) {
  105377. //Value of result
  105378. //["f 1 2 3", "1 2 3"...]
  105379. //Set the data for this face
  105380. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105381. 1);
  105382. //Define a mesh or an object
  105383. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105384. }
  105385. else if (this.group.test(line) || this.obj.test(line)) {
  105386. //Create a new mesh corresponding to the name of the group.
  105387. //Definition of the mesh
  105388. var objMesh =
  105389. //Set the name of the current obj mesh
  105390. {
  105391. name: line.substring(2).trim(),
  105392. indices: undefined,
  105393. positions: undefined,
  105394. normals: undefined,
  105395. uvs: undefined,
  105396. materialName: ""
  105397. };
  105398. addPreviousObjMesh();
  105399. //Push the last mesh created with only the name
  105400. meshesFromObj.push(objMesh);
  105401. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105402. hasMeshes = true;
  105403. isFirstMaterial = true;
  105404. increment = 1;
  105405. //Keyword for applying a material
  105406. }
  105407. else if (this.usemtl.test(line)) {
  105408. //Get the name of the material
  105409. materialNameFromObj = line.substring(7).trim();
  105410. //If this new material is in the same mesh
  105411. if (!isFirstMaterial) {
  105412. //Set the data for the previous mesh
  105413. addPreviousObjMesh();
  105414. //Create a new mesh
  105415. var objMesh =
  105416. //Set the name of the current obj mesh
  105417. {
  105418. name: objMeshName + "_mm" + increment.toString(),
  105419. indices: undefined,
  105420. positions: undefined,
  105421. normals: undefined,
  105422. uvs: undefined,
  105423. materialName: materialNameFromObj
  105424. };
  105425. increment++;
  105426. //If meshes are already defined
  105427. meshesFromObj.push(objMesh);
  105428. }
  105429. //Set the material name if the previous line define a mesh
  105430. if (hasMeshes && isFirstMaterial) {
  105431. //Set the material name to the previous mesh (1 material per mesh)
  105432. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105433. isFirstMaterial = false;
  105434. }
  105435. //Keyword for loading the mtl file
  105436. }
  105437. else if (this.mtllib.test(line)) {
  105438. //Get the name of mtl file
  105439. fileToLoad = line.substring(7).trim();
  105440. //Apply smoothing
  105441. }
  105442. else if (this.smooth.test(line)) {
  105443. // smooth shading => apply smoothing
  105444. //Toda y I don't know it work with babylon and with obj.
  105445. //With the obj file an integer is set
  105446. }
  105447. else {
  105448. //If there is another possibility
  105449. console.log("Unhandled expression at line : " + line);
  105450. }
  105451. }
  105452. //At the end of the file, add the last mesh into the meshesFromObj array
  105453. if (hasMeshes) {
  105454. //Set the data for the last mesh
  105455. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105456. //Reverse indices for displaying faces in the good sens
  105457. indicesForBabylon.reverse();
  105458. //Get the good array
  105459. unwrapData();
  105460. //Set array
  105461. handledMesh.indices = indicesForBabylon;
  105462. handledMesh.positions = unwrappedPositionsForBabylon;
  105463. handledMesh.normals = unwrappedNormalsForBabylon;
  105464. handledMesh.uvs = unwrappedUVForBabylon;
  105465. }
  105466. //If any o or g keyword found, create a mesj with a random id
  105467. if (!hasMeshes) {
  105468. // reverse tab of indices
  105469. indicesForBabylon.reverse();
  105470. //Get positions normals uvs
  105471. unwrapData();
  105472. //Set data for one mesh
  105473. meshesFromObj.push({
  105474. name: BABYLON.Geometry.RandomId(),
  105475. indices: indicesForBabylon,
  105476. positions: unwrappedPositionsForBabylon,
  105477. normals: unwrappedNormalsForBabylon,
  105478. uvs: unwrappedUVForBabylon,
  105479. materialName: materialNameFromObj
  105480. });
  105481. }
  105482. //Create a BABYLON.Mesh list
  105483. var babylonMeshesArray = []; //The mesh for babylon
  105484. var materialToUse = new Array();
  105485. //Set data for each mesh
  105486. for (var j = 0; j < meshesFromObj.length; j++) {
  105487. //check meshesNames (stlFileLoader)
  105488. if (meshesNames && meshesFromObj[j].name) {
  105489. if (meshesNames instanceof Array) {
  105490. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105491. continue;
  105492. }
  105493. }
  105494. else {
  105495. if (meshesFromObj[j].name !== meshesNames) {
  105496. continue;
  105497. }
  105498. }
  105499. }
  105500. //Get the current mesh
  105501. //Set the data with VertexBuffer for each mesh
  105502. handledMesh = meshesFromObj[j];
  105503. //Create a BABYLON.Mesh with the name of the obj mesh
  105504. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105505. //Push the name of the material to an array
  105506. //This is indispensable for the importMesh function
  105507. materialToUse.push(meshesFromObj[j].materialName);
  105508. var vertexData = new BABYLON.VertexData(); //The container for the values
  105509. //Set the data for the babylonMesh
  105510. vertexData.positions = handledMesh.positions;
  105511. vertexData.normals = handledMesh.normals;
  105512. vertexData.uvs = handledMesh.uvs;
  105513. vertexData.indices = handledMesh.indices;
  105514. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105515. vertexData.applyToMesh(babylonMesh);
  105516. //Push the mesh into an array
  105517. babylonMeshesArray.push(babylonMesh);
  105518. }
  105519. //load the materials
  105520. //Check if we have a file to load
  105521. if (fileToLoad !== "") {
  105522. //Load the file synchronously
  105523. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105524. //Create materials thanks MTLLoader function
  105525. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105526. //Look at each material loaded in the mtl file
  105527. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105528. //Three variables to get all meshes with the same material
  105529. var startIndex = 0;
  105530. var _indices = [];
  105531. var _index;
  105532. //The material from MTL file is used in the meshes loaded
  105533. //Push the indice in an array
  105534. //Check if the material is not used for another mesh
  105535. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105536. _indices.push(_index);
  105537. startIndex = _index + 1;
  105538. }
  105539. //If the material is not used dispose it
  105540. if (_index == -1 && _indices.length == 0) {
  105541. //If the material is not needed, remove it
  105542. materialsFromMTLFile.materials[n].dispose();
  105543. }
  105544. else {
  105545. for (var o = 0; o < _indices.length; o++) {
  105546. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105547. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105548. }
  105549. }
  105550. }
  105551. });
  105552. }
  105553. //Return an array with all BABYLON.Mesh
  105554. return babylonMeshesArray;
  105555. };
  105556. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105557. return OBJFileLoader;
  105558. }());
  105559. BABYLON.OBJFileLoader = OBJFileLoader;
  105560. if (BABYLON.SceneLoader) {
  105561. //Add this loader into the register plugin
  105562. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105563. }
  105564. })(BABYLON || (BABYLON = {}));
  105565. //# sourceMappingURL=babylon.objFileLoader.js.map
  105566. var BABYLON;
  105567. (function (BABYLON) {
  105568. var GLTFLoaderCoordinateSystemMode;
  105569. (function (GLTFLoaderCoordinateSystemMode) {
  105570. /**
  105571. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105572. */
  105573. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105574. /**
  105575. * Sets the useRightHandedSystem flag on the scene.
  105576. */
  105577. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105578. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105579. var GLTFLoaderAnimationStartMode;
  105580. (function (GLTFLoaderAnimationStartMode) {
  105581. /**
  105582. * No animation will start.
  105583. */
  105584. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105585. /**
  105586. * The first animation will start.
  105587. */
  105588. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105589. /**
  105590. * All animations will start.
  105591. */
  105592. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105593. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105594. var GLTFLoaderState;
  105595. (function (GLTFLoaderState) {
  105596. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  105597. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  105598. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  105599. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105600. var GLTFFileLoader = /** @class */ (function () {
  105601. function GLTFFileLoader() {
  105602. // #region Common options
  105603. /**
  105604. * Raised when the asset has been parsed.
  105605. * The data.json property stores the glTF JSON.
  105606. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  105607. */
  105608. this.onParsedObservable = new BABYLON.Observable();
  105609. // #endregion
  105610. // #region V2 options
  105611. /**
  105612. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  105613. */
  105614. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105615. /**
  105616. * The animation start mode (NONE, FIRST, ALL).
  105617. */
  105618. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105619. /**
  105620. * Set to true to compile materials before raising the success callback.
  105621. */
  105622. this.compileMaterials = false;
  105623. /**
  105624. * Set to true to also compile materials with clip planes.
  105625. */
  105626. this.useClipPlane = false;
  105627. /**
  105628. * Set to true to compile shadow generators before raising the success callback.
  105629. */
  105630. this.compileShadowGenerators = false;
  105631. /**
  105632. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105633. */
  105634. this.onMeshLoadedObservable = new BABYLON.Observable();
  105635. /**
  105636. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  105637. */
  105638. this.onTextureLoadedObservable = new BABYLON.Observable();
  105639. /**
  105640. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105641. */
  105642. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105643. /**
  105644. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  105645. */
  105646. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  105647. /**
  105648. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105649. * For assets with LODs, raised when all of the LODs are complete.
  105650. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105651. */
  105652. this.onCompleteObservable = new BABYLON.Observable();
  105653. /**
  105654. * Raised when the loader is disposed.
  105655. */
  105656. this.onDisposeObservable = new BABYLON.Observable();
  105657. /**
  105658. * Raised after a loader extension is created.
  105659. * Set additional options for a loader extension in this event.
  105660. */
  105661. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105662. // #endregion
  105663. this._loader = null;
  105664. this.name = "gltf";
  105665. this.extensions = {
  105666. ".gltf": { isBinary: false },
  105667. ".glb": { isBinary: true }
  105668. };
  105669. }
  105670. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105671. set: function (callback) {
  105672. if (this._onParsedObserver) {
  105673. this.onParsedObservable.remove(this._onParsedObserver);
  105674. }
  105675. this._onParsedObserver = this.onParsedObservable.add(callback);
  105676. },
  105677. enumerable: true,
  105678. configurable: true
  105679. });
  105680. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105681. set: function (callback) {
  105682. if (this._onMeshLoadedObserver) {
  105683. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105684. }
  105685. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105686. },
  105687. enumerable: true,
  105688. configurable: true
  105689. });
  105690. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105691. set: function (callback) {
  105692. if (this._onTextureLoadedObserver) {
  105693. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105694. }
  105695. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105696. },
  105697. enumerable: true,
  105698. configurable: true
  105699. });
  105700. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105701. set: function (callback) {
  105702. if (this._onMaterialLoadedObserver) {
  105703. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105704. }
  105705. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105706. },
  105707. enumerable: true,
  105708. configurable: true
  105709. });
  105710. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  105711. set: function (callback) {
  105712. if (this._onAnimationGroupLoadedObserver) {
  105713. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  105714. }
  105715. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  105716. },
  105717. enumerable: true,
  105718. configurable: true
  105719. });
  105720. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105721. set: function (callback) {
  105722. if (this._onCompleteObserver) {
  105723. this.onCompleteObservable.remove(this._onCompleteObserver);
  105724. }
  105725. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105726. },
  105727. enumerable: true,
  105728. configurable: true
  105729. });
  105730. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105731. set: function (callback) {
  105732. if (this._onDisposeObserver) {
  105733. this.onDisposeObservable.remove(this._onDisposeObserver);
  105734. }
  105735. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105736. },
  105737. enumerable: true,
  105738. configurable: true
  105739. });
  105740. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105741. set: function (callback) {
  105742. if (this._onExtensionLoadedObserver) {
  105743. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105744. }
  105745. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105746. },
  105747. enumerable: true,
  105748. configurable: true
  105749. });
  105750. /**
  105751. * Gets a promise that resolves when the asset is completely loaded.
  105752. * @returns A promise that resolves when the asset is completely loaded.
  105753. */
  105754. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105755. var _this = this;
  105756. return new Promise(function (resolve) {
  105757. _this.onCompleteObservable.add(function () {
  105758. resolve();
  105759. }, undefined, undefined, undefined, true);
  105760. });
  105761. };
  105762. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105763. /**
  105764. * The loader state or null if not active.
  105765. */
  105766. get: function () {
  105767. return this._loader ? this._loader.state : null;
  105768. },
  105769. enumerable: true,
  105770. configurable: true
  105771. });
  105772. /**
  105773. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105774. */
  105775. GLTFFileLoader.prototype.dispose = function () {
  105776. if (this._loader) {
  105777. this._loader.dispose();
  105778. this._loader = null;
  105779. }
  105780. this.onMeshLoadedObservable.clear();
  105781. this.onTextureLoadedObservable.clear();
  105782. this.onMaterialLoadedObservable.clear();
  105783. this.onDisposeObservable.notifyObservers(this);
  105784. this.onDisposeObservable.clear();
  105785. };
  105786. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105787. var _this = this;
  105788. return Promise.resolve().then(function () {
  105789. var loaderData = _this._parse(data);
  105790. _this._loader = _this._getLoader(loaderData);
  105791. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105792. });
  105793. };
  105794. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105795. var _this = this;
  105796. return Promise.resolve().then(function () {
  105797. var loaderData = _this._parse(data);
  105798. _this._loader = _this._getLoader(loaderData);
  105799. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105800. });
  105801. };
  105802. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105803. var _this = this;
  105804. return Promise.resolve().then(function () {
  105805. var loaderData = _this._parse(data);
  105806. _this._loader = _this._getLoader(loaderData);
  105807. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105808. var container = new BABYLON.AssetContainer(scene);
  105809. Array.prototype.push.apply(container.meshes, result.meshes);
  105810. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105811. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105812. container.removeAllFromScene();
  105813. return container;
  105814. });
  105815. });
  105816. };
  105817. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105818. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105819. };
  105820. GLTFFileLoader.prototype.createPlugin = function () {
  105821. return new GLTFFileLoader();
  105822. };
  105823. GLTFFileLoader.prototype._parse = function (data) {
  105824. var parsedData;
  105825. if (data instanceof ArrayBuffer) {
  105826. parsedData = GLTFFileLoader._parseBinary(data);
  105827. }
  105828. else {
  105829. parsedData = {
  105830. json: JSON.parse(data),
  105831. bin: null
  105832. };
  105833. }
  105834. this.onParsedObservable.notifyObservers(parsedData);
  105835. this.onParsedObservable.clear();
  105836. return parsedData;
  105837. };
  105838. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105839. var _this = this;
  105840. var loaderVersion = { major: 2, minor: 0 };
  105841. var asset = loaderData.json.asset || {};
  105842. var version = GLTFFileLoader._parseVersion(asset.version);
  105843. if (!version) {
  105844. throw new Error("Invalid version: " + asset.version);
  105845. }
  105846. if (asset.minVersion !== undefined) {
  105847. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105848. if (!minVersion) {
  105849. throw new Error("Invalid minimum version: " + asset.minVersion);
  105850. }
  105851. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105852. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105853. }
  105854. }
  105855. var createLoaders = {
  105856. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105857. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105858. };
  105859. var createLoader = createLoaders[version.major];
  105860. if (!createLoader) {
  105861. throw new Error("Unsupported version: " + asset.version);
  105862. }
  105863. var loader = createLoader();
  105864. loader.coordinateSystemMode = this.coordinateSystemMode;
  105865. loader.animationStartMode = this.animationStartMode;
  105866. loader.compileMaterials = this.compileMaterials;
  105867. loader.useClipPlane = this.useClipPlane;
  105868. loader.compileShadowGenerators = this.compileShadowGenerators;
  105869. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  105870. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  105871. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  105872. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  105873. loader.onCompleteObservable.add(function () {
  105874. _this.onMeshLoadedObservable.clear();
  105875. _this.onTextureLoadedObservable.clear();
  105876. _this.onMaterialLoadedObservable.clear();
  105877. _this.onCompleteObservable.notifyObservers(_this);
  105878. _this.onCompleteObservable.clear();
  105879. });
  105880. return loader;
  105881. };
  105882. GLTFFileLoader._parseBinary = function (data) {
  105883. var Binary = {
  105884. Magic: 0x46546C67
  105885. };
  105886. var binaryReader = new BinaryReader(data);
  105887. var magic = binaryReader.readUint32();
  105888. if (magic !== Binary.Magic) {
  105889. throw new Error("Unexpected magic: " + magic);
  105890. }
  105891. var version = binaryReader.readUint32();
  105892. switch (version) {
  105893. case 1: return GLTFFileLoader._parseV1(binaryReader);
  105894. case 2: return GLTFFileLoader._parseV2(binaryReader);
  105895. }
  105896. throw new Error("Unsupported version: " + version);
  105897. };
  105898. GLTFFileLoader._parseV1 = function (binaryReader) {
  105899. var ContentFormat = {
  105900. JSON: 0
  105901. };
  105902. var length = binaryReader.readUint32();
  105903. if (length != binaryReader.getLength()) {
  105904. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105905. }
  105906. var contentLength = binaryReader.readUint32();
  105907. var contentFormat = binaryReader.readUint32();
  105908. var content;
  105909. switch (contentFormat) {
  105910. case ContentFormat.JSON: {
  105911. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105912. break;
  105913. }
  105914. default: {
  105915. throw new Error("Unexpected content format: " + contentFormat);
  105916. }
  105917. }
  105918. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  105919. var body = binaryReader.readUint8Array(bytesRemaining);
  105920. return {
  105921. json: content,
  105922. bin: body
  105923. };
  105924. };
  105925. GLTFFileLoader._parseV2 = function (binaryReader) {
  105926. var ChunkFormat = {
  105927. JSON: 0x4E4F534A,
  105928. BIN: 0x004E4942
  105929. };
  105930. var length = binaryReader.readUint32();
  105931. if (length !== binaryReader.getLength()) {
  105932. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105933. }
  105934. // JSON chunk
  105935. var chunkLength = binaryReader.readUint32();
  105936. var chunkFormat = binaryReader.readUint32();
  105937. if (chunkFormat !== ChunkFormat.JSON) {
  105938. throw new Error("First chunk format is not JSON");
  105939. }
  105940. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  105941. // Look for BIN chunk
  105942. var bin = null;
  105943. while (binaryReader.getPosition() < binaryReader.getLength()) {
  105944. var chunkLength_1 = binaryReader.readUint32();
  105945. var chunkFormat_1 = binaryReader.readUint32();
  105946. switch (chunkFormat_1) {
  105947. case ChunkFormat.JSON: {
  105948. throw new Error("Unexpected JSON chunk");
  105949. }
  105950. case ChunkFormat.BIN: {
  105951. bin = binaryReader.readUint8Array(chunkLength_1);
  105952. break;
  105953. }
  105954. default: {
  105955. // ignore unrecognized chunkFormat
  105956. binaryReader.skipBytes(chunkLength_1);
  105957. break;
  105958. }
  105959. }
  105960. }
  105961. return {
  105962. json: json,
  105963. bin: bin
  105964. };
  105965. };
  105966. GLTFFileLoader._parseVersion = function (version) {
  105967. if (version === "1.0" || version === "1.0.1") {
  105968. return {
  105969. major: 1,
  105970. minor: 0
  105971. };
  105972. }
  105973. var match = (version + "").match(/^(\d+)\.(\d+)/);
  105974. if (!match) {
  105975. return null;
  105976. }
  105977. return {
  105978. major: parseInt(match[1]),
  105979. minor: parseInt(match[2])
  105980. };
  105981. };
  105982. GLTFFileLoader._compareVersion = function (a, b) {
  105983. if (a.major > b.major)
  105984. return 1;
  105985. if (a.major < b.major)
  105986. return -1;
  105987. if (a.minor > b.minor)
  105988. return 1;
  105989. if (a.minor < b.minor)
  105990. return -1;
  105991. return 0;
  105992. };
  105993. GLTFFileLoader._decodeBufferToText = function (buffer) {
  105994. var result = "";
  105995. var length = buffer.byteLength;
  105996. for (var i = 0; i < length; i++) {
  105997. result += String.fromCharCode(buffer[i]);
  105998. }
  105999. return result;
  106000. };
  106001. // #endregion
  106002. // #region V1 options
  106003. GLTFFileLoader.IncrementalLoading = true;
  106004. GLTFFileLoader.HomogeneousCoordinates = false;
  106005. return GLTFFileLoader;
  106006. }());
  106007. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106008. var BinaryReader = /** @class */ (function () {
  106009. function BinaryReader(arrayBuffer) {
  106010. this._arrayBuffer = arrayBuffer;
  106011. this._dataView = new DataView(arrayBuffer);
  106012. this._byteOffset = 0;
  106013. }
  106014. BinaryReader.prototype.getPosition = function () {
  106015. return this._byteOffset;
  106016. };
  106017. BinaryReader.prototype.getLength = function () {
  106018. return this._arrayBuffer.byteLength;
  106019. };
  106020. BinaryReader.prototype.readUint32 = function () {
  106021. var value = this._dataView.getUint32(this._byteOffset, true);
  106022. this._byteOffset += 4;
  106023. return value;
  106024. };
  106025. BinaryReader.prototype.readUint8Array = function (length) {
  106026. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106027. this._byteOffset += length;
  106028. return value;
  106029. };
  106030. BinaryReader.prototype.skipBytes = function (length) {
  106031. this._byteOffset += length;
  106032. };
  106033. return BinaryReader;
  106034. }());
  106035. if (BABYLON.SceneLoader) {
  106036. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106037. }
  106038. })(BABYLON || (BABYLON = {}));
  106039. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106040. var BABYLON;
  106041. (function (BABYLON) {
  106042. var GLTF1;
  106043. (function (GLTF1) {
  106044. /**
  106045. * Enums
  106046. */
  106047. var EComponentType;
  106048. (function (EComponentType) {
  106049. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106050. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106051. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106052. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106053. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106054. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106055. var EShaderType;
  106056. (function (EShaderType) {
  106057. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106058. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106059. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106060. var EParameterType;
  106061. (function (EParameterType) {
  106062. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106063. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106064. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106065. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106066. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106067. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106068. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106069. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106070. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106071. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106072. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106073. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106074. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106075. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106076. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106077. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106078. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106079. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106080. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106081. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106082. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106083. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106084. var ETextureWrapMode;
  106085. (function (ETextureWrapMode) {
  106086. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106087. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106088. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106089. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106090. var ETextureFilterType;
  106091. (function (ETextureFilterType) {
  106092. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106093. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106094. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106095. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106096. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106097. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106098. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106099. var ETextureFormat;
  106100. (function (ETextureFormat) {
  106101. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106102. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106103. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106104. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106105. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106106. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106107. var ECullingType;
  106108. (function (ECullingType) {
  106109. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106110. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106111. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106112. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106113. var EBlendingFunction;
  106114. (function (EBlendingFunction) {
  106115. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106116. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106117. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106118. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106119. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106120. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106121. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106122. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106123. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106124. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106125. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106126. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106127. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106128. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106129. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106130. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106131. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106132. })(BABYLON || (BABYLON = {}));
  106133. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106134. var BABYLON;
  106135. (function (BABYLON) {
  106136. var GLTF1;
  106137. (function (GLTF1) {
  106138. /**
  106139. * Tokenizer. Used for shaders compatibility
  106140. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106141. */
  106142. var ETokenType;
  106143. (function (ETokenType) {
  106144. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106145. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106146. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106147. })(ETokenType || (ETokenType = {}));
  106148. var Tokenizer = /** @class */ (function () {
  106149. function Tokenizer(toParse) {
  106150. this._pos = 0;
  106151. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106152. this._toParse = toParse;
  106153. this._maxPos = toParse.length;
  106154. }
  106155. Tokenizer.prototype.getNextToken = function () {
  106156. if (this.isEnd())
  106157. return ETokenType.END_OF_INPUT;
  106158. this.currentString = this.read();
  106159. this.currentToken = ETokenType.UNKNOWN;
  106160. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106161. this.currentToken = ETokenType.IDENTIFIER;
  106162. this.currentIdentifier = this.currentString;
  106163. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106164. this.currentIdentifier += this.currentString;
  106165. this.forward();
  106166. }
  106167. }
  106168. return this.currentToken;
  106169. };
  106170. Tokenizer.prototype.peek = function () {
  106171. return this._toParse[this._pos];
  106172. };
  106173. Tokenizer.prototype.read = function () {
  106174. return this._toParse[this._pos++];
  106175. };
  106176. Tokenizer.prototype.forward = function () {
  106177. this._pos++;
  106178. };
  106179. Tokenizer.prototype.isEnd = function () {
  106180. return this._pos >= this._maxPos;
  106181. };
  106182. return Tokenizer;
  106183. }());
  106184. /**
  106185. * Values
  106186. */
  106187. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106188. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106189. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106190. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106191. /**
  106192. * Parse
  106193. */
  106194. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106195. for (var buf in parsedBuffers) {
  106196. var parsedBuffer = parsedBuffers[buf];
  106197. gltfRuntime.buffers[buf] = parsedBuffer;
  106198. gltfRuntime.buffersCount++;
  106199. }
  106200. };
  106201. var parseShaders = function (parsedShaders, gltfRuntime) {
  106202. for (var sha in parsedShaders) {
  106203. var parsedShader = parsedShaders[sha];
  106204. gltfRuntime.shaders[sha] = parsedShader;
  106205. gltfRuntime.shaderscount++;
  106206. }
  106207. };
  106208. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106209. for (var object in parsedObjects) {
  106210. var parsedObject = parsedObjects[object];
  106211. gltfRuntime[runtimeProperty][object] = parsedObject;
  106212. }
  106213. };
  106214. /**
  106215. * Utils
  106216. */
  106217. var normalizeUVs = function (buffer) {
  106218. if (!buffer) {
  106219. return;
  106220. }
  106221. for (var i = 0; i < buffer.length / 2; i++) {
  106222. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106223. }
  106224. };
  106225. var getAttribute = function (attributeParameter) {
  106226. if (attributeParameter.semantic === "NORMAL") {
  106227. return "normal";
  106228. }
  106229. else if (attributeParameter.semantic === "POSITION") {
  106230. return "position";
  106231. }
  106232. else if (attributeParameter.semantic === "JOINT") {
  106233. return "matricesIndices";
  106234. }
  106235. else if (attributeParameter.semantic === "WEIGHT") {
  106236. return "matricesWeights";
  106237. }
  106238. else if (attributeParameter.semantic === "COLOR") {
  106239. return "color";
  106240. }
  106241. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106242. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106243. return "uv" + (channel === 0 ? "" : channel + 1);
  106244. }
  106245. return null;
  106246. };
  106247. /**
  106248. * Loads and creates animations
  106249. */
  106250. var loadAnimations = function (gltfRuntime) {
  106251. for (var anim in gltfRuntime.animations) {
  106252. var animation = gltfRuntime.animations[anim];
  106253. if (!animation.channels || !animation.samplers) {
  106254. continue;
  106255. }
  106256. var lastAnimation = null;
  106257. for (var i = 0; i < animation.channels.length; i++) {
  106258. // Get parameters and load buffers
  106259. var channel = animation.channels[i];
  106260. var sampler = animation.samplers[channel.sampler];
  106261. if (!sampler) {
  106262. continue;
  106263. }
  106264. var inputData = null;
  106265. var outputData = null;
  106266. if (animation.parameters) {
  106267. inputData = animation.parameters[sampler.input];
  106268. outputData = animation.parameters[sampler.output];
  106269. }
  106270. else {
  106271. inputData = sampler.input;
  106272. outputData = sampler.output;
  106273. }
  106274. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106275. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106276. var targetID = channel.target.id;
  106277. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106278. if (targetNode === null) {
  106279. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106280. }
  106281. if (targetNode === null) {
  106282. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106283. continue;
  106284. }
  106285. var isBone = targetNode instanceof BABYLON.Bone;
  106286. // Get target path (position, rotation or scaling)
  106287. var targetPath = channel.target.path;
  106288. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106289. if (targetPathIndex !== -1) {
  106290. targetPath = babylonAnimationPaths[targetPathIndex];
  106291. }
  106292. // Determine animation type
  106293. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106294. if (!isBone) {
  106295. if (targetPath === "rotationQuaternion") {
  106296. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106297. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106298. }
  106299. else {
  106300. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106301. }
  106302. }
  106303. // Create animation and key frames
  106304. var babylonAnimation = null;
  106305. var keys = [];
  106306. var arrayOffset = 0;
  106307. var modifyKey = false;
  106308. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106309. babylonAnimation = lastAnimation;
  106310. modifyKey = true;
  106311. }
  106312. if (!modifyKey) {
  106313. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106314. }
  106315. // For each frame
  106316. for (var j = 0; j < bufferInput.length; j++) {
  106317. var value = null;
  106318. if (targetPath === "rotationQuaternion") {
  106319. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106320. arrayOffset += 4;
  106321. }
  106322. else {
  106323. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106324. arrayOffset += 3;
  106325. }
  106326. if (isBone) {
  106327. var bone = targetNode;
  106328. var translation = BABYLON.Vector3.Zero();
  106329. var rotationQuaternion = new BABYLON.Quaternion();
  106330. var scaling = BABYLON.Vector3.Zero();
  106331. // Warning on decompose
  106332. var mat = bone.getBaseMatrix();
  106333. if (modifyKey && lastAnimation) {
  106334. mat = lastAnimation.getKeys()[j].value;
  106335. }
  106336. mat.decompose(scaling, rotationQuaternion, translation);
  106337. if (targetPath === "position") {
  106338. translation = value;
  106339. }
  106340. else if (targetPath === "rotationQuaternion") {
  106341. rotationQuaternion = value;
  106342. }
  106343. else {
  106344. scaling = value;
  106345. }
  106346. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106347. }
  106348. if (!modifyKey) {
  106349. keys.push({
  106350. frame: bufferInput[j],
  106351. value: value
  106352. });
  106353. }
  106354. else if (lastAnimation) {
  106355. lastAnimation.getKeys()[j].value = value;
  106356. }
  106357. }
  106358. // Finish
  106359. if (!modifyKey && babylonAnimation) {
  106360. babylonAnimation.setKeys(keys);
  106361. targetNode.animations.push(babylonAnimation);
  106362. }
  106363. lastAnimation = babylonAnimation;
  106364. gltfRuntime.scene.stopAnimation(targetNode);
  106365. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106366. }
  106367. }
  106368. };
  106369. /**
  106370. * Returns the bones transformation matrix
  106371. */
  106372. var configureBoneTransformation = function (node) {
  106373. var mat = null;
  106374. if (node.translation || node.rotation || node.scale) {
  106375. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106376. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106377. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106378. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106379. }
  106380. else {
  106381. mat = BABYLON.Matrix.FromArray(node.matrix);
  106382. }
  106383. return mat;
  106384. };
  106385. /**
  106386. * Returns the parent bone
  106387. */
  106388. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106389. // Try to find
  106390. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106391. if (newSkeleton.bones[i].name === jointName) {
  106392. return newSkeleton.bones[i];
  106393. }
  106394. }
  106395. // Not found, search in gltf nodes
  106396. var nodes = gltfRuntime.nodes;
  106397. for (var nde in nodes) {
  106398. var node = nodes[nde];
  106399. if (!node.jointName) {
  106400. continue;
  106401. }
  106402. var children = node.children;
  106403. for (var i = 0; i < children.length; i++) {
  106404. var child = gltfRuntime.nodes[children[i]];
  106405. if (!child.jointName) {
  106406. continue;
  106407. }
  106408. if (child.jointName === jointName) {
  106409. var mat = configureBoneTransformation(node);
  106410. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106411. bone.id = nde;
  106412. return bone;
  106413. }
  106414. }
  106415. }
  106416. return null;
  106417. };
  106418. /**
  106419. * Returns the appropriate root node
  106420. */
  106421. var getNodeToRoot = function (nodesToRoot, id) {
  106422. for (var i = 0; i < nodesToRoot.length; i++) {
  106423. var nodeToRoot = nodesToRoot[i];
  106424. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106425. var child = nodeToRoot.node.children[j];
  106426. if (child === id) {
  106427. return nodeToRoot.bone;
  106428. }
  106429. }
  106430. }
  106431. return null;
  106432. };
  106433. /**
  106434. * Returns the node with the joint name
  106435. */
  106436. var getJointNode = function (gltfRuntime, jointName) {
  106437. var nodes = gltfRuntime.nodes;
  106438. var node = nodes[jointName];
  106439. if (node) {
  106440. return {
  106441. node: node,
  106442. id: jointName
  106443. };
  106444. }
  106445. for (var nde in nodes) {
  106446. node = nodes[nde];
  106447. if (node.jointName === jointName) {
  106448. return {
  106449. node: node,
  106450. id: nde
  106451. };
  106452. }
  106453. }
  106454. return null;
  106455. };
  106456. /**
  106457. * Checks if a nodes is in joints
  106458. */
  106459. var nodeIsInJoints = function (skins, id) {
  106460. for (var i = 0; i < skins.jointNames.length; i++) {
  106461. if (skins.jointNames[i] === id) {
  106462. return true;
  106463. }
  106464. }
  106465. return false;
  106466. };
  106467. /**
  106468. * Fills the nodes to root for bones and builds hierarchy
  106469. */
  106470. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106471. // Creates nodes for root
  106472. for (var nde in gltfRuntime.nodes) {
  106473. var node = gltfRuntime.nodes[nde];
  106474. var id = nde;
  106475. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106476. continue;
  106477. }
  106478. // Create node to root bone
  106479. var mat = configureBoneTransformation(node);
  106480. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106481. bone.id = id;
  106482. nodesToRoot.push({ bone: bone, node: node, id: id });
  106483. }
  106484. // Parenting
  106485. for (var i = 0; i < nodesToRoot.length; i++) {
  106486. var nodeToRoot = nodesToRoot[i];
  106487. var children = nodeToRoot.node.children;
  106488. for (var j = 0; j < children.length; j++) {
  106489. var child = null;
  106490. for (var k = 0; k < nodesToRoot.length; k++) {
  106491. if (nodesToRoot[k].id === children[j]) {
  106492. child = nodesToRoot[k];
  106493. break;
  106494. }
  106495. }
  106496. if (child) {
  106497. child.bone._parent = nodeToRoot.bone;
  106498. nodeToRoot.bone.children.push(child.bone);
  106499. }
  106500. }
  106501. }
  106502. };
  106503. /**
  106504. * Imports a skeleton
  106505. */
  106506. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106507. if (!newSkeleton) {
  106508. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106509. }
  106510. if (!skins.babylonSkeleton) {
  106511. return newSkeleton;
  106512. }
  106513. // Find the root bones
  106514. var nodesToRoot = [];
  106515. var nodesToRootToAdd = [];
  106516. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106517. newSkeleton.bones = [];
  106518. // Joints
  106519. for (var i = 0; i < skins.jointNames.length; i++) {
  106520. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106521. if (!jointNode) {
  106522. continue;
  106523. }
  106524. var node = jointNode.node;
  106525. if (!node) {
  106526. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106527. continue;
  106528. }
  106529. var id = jointNode.id;
  106530. // Optimize, if the bone already exists...
  106531. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106532. if (existingBone) {
  106533. newSkeleton.bones.push(existingBone);
  106534. continue;
  106535. }
  106536. // Search for parent bone
  106537. var foundBone = false;
  106538. var parentBone = null;
  106539. for (var j = 0; j < i; j++) {
  106540. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106541. if (!jointNode_1) {
  106542. continue;
  106543. }
  106544. var joint = jointNode_1.node;
  106545. if (!joint) {
  106546. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106547. continue;
  106548. }
  106549. var children = joint.children;
  106550. if (!children) {
  106551. continue;
  106552. }
  106553. foundBone = false;
  106554. for (var k = 0; k < children.length; k++) {
  106555. if (children[k] === id) {
  106556. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106557. foundBone = true;
  106558. break;
  106559. }
  106560. }
  106561. if (foundBone) {
  106562. break;
  106563. }
  106564. }
  106565. // Create bone
  106566. var mat = configureBoneTransformation(node);
  106567. if (!parentBone && nodesToRoot.length > 0) {
  106568. parentBone = getNodeToRoot(nodesToRoot, id);
  106569. if (parentBone) {
  106570. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106571. nodesToRootToAdd.push(parentBone);
  106572. }
  106573. }
  106574. }
  106575. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106576. bone.id = id;
  106577. }
  106578. // Polish
  106579. var bones = newSkeleton.bones;
  106580. newSkeleton.bones = [];
  106581. for (var i = 0; i < skins.jointNames.length; i++) {
  106582. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106583. if (!jointNode) {
  106584. continue;
  106585. }
  106586. for (var j = 0; j < bones.length; j++) {
  106587. if (bones[j].id === jointNode.id) {
  106588. newSkeleton.bones.push(bones[j]);
  106589. break;
  106590. }
  106591. }
  106592. }
  106593. newSkeleton.prepare();
  106594. // Finish
  106595. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106596. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106597. }
  106598. return newSkeleton;
  106599. };
  106600. /**
  106601. * Imports a mesh and its geometries
  106602. */
  106603. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106604. if (!newMesh) {
  106605. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106606. newMesh.id = id;
  106607. }
  106608. if (!node.babylonNode) {
  106609. return newMesh;
  106610. }
  106611. var subMaterials = [];
  106612. var vertexData = null;
  106613. var verticesStarts = new Array();
  106614. var verticesCounts = new Array();
  106615. var indexStarts = new Array();
  106616. var indexCounts = new Array();
  106617. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106618. var meshID = meshes[meshIndex];
  106619. var mesh = gltfRuntime.meshes[meshID];
  106620. if (!mesh) {
  106621. continue;
  106622. }
  106623. // Positions, normals and UVs
  106624. for (var i = 0; i < mesh.primitives.length; i++) {
  106625. // Temporary vertex data
  106626. var tempVertexData = new BABYLON.VertexData();
  106627. var primitive = mesh.primitives[i];
  106628. if (primitive.mode !== 4) {
  106629. // continue;
  106630. }
  106631. var attributes = primitive.attributes;
  106632. var accessor = null;
  106633. var buffer = null;
  106634. // Set positions, normal and uvs
  106635. for (var semantic in attributes) {
  106636. // Link accessor and buffer view
  106637. accessor = gltfRuntime.accessors[attributes[semantic]];
  106638. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106639. if (semantic === "NORMAL") {
  106640. tempVertexData.normals = new Float32Array(buffer.length);
  106641. tempVertexData.normals.set(buffer);
  106642. }
  106643. else if (semantic === "POSITION") {
  106644. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106645. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106646. for (var j = 0; j < buffer.length; j += 4) {
  106647. tempVertexData.positions[j] = buffer[j];
  106648. tempVertexData.positions[j + 1] = buffer[j + 1];
  106649. tempVertexData.positions[j + 2] = buffer[j + 2];
  106650. }
  106651. }
  106652. else {
  106653. tempVertexData.positions = new Float32Array(buffer.length);
  106654. tempVertexData.positions.set(buffer);
  106655. }
  106656. verticesCounts.push(tempVertexData.positions.length);
  106657. }
  106658. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106659. var channel = Number(semantic.split("_")[1]);
  106660. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106661. var uvs = new Float32Array(buffer.length);
  106662. uvs.set(buffer);
  106663. normalizeUVs(uvs);
  106664. tempVertexData.set(uvs, uvKind);
  106665. }
  106666. else if (semantic === "JOINT") {
  106667. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106668. tempVertexData.matricesIndices.set(buffer);
  106669. }
  106670. else if (semantic === "WEIGHT") {
  106671. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106672. tempVertexData.matricesWeights.set(buffer);
  106673. }
  106674. else if (semantic === "COLOR") {
  106675. tempVertexData.colors = new Float32Array(buffer.length);
  106676. tempVertexData.colors.set(buffer);
  106677. }
  106678. }
  106679. // Indices
  106680. accessor = gltfRuntime.accessors[primitive.indices];
  106681. if (accessor) {
  106682. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106683. tempVertexData.indices = new Int32Array(buffer.length);
  106684. tempVertexData.indices.set(buffer);
  106685. indexCounts.push(tempVertexData.indices.length);
  106686. }
  106687. else {
  106688. // Set indices on the fly
  106689. var indices = [];
  106690. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106691. indices.push(j);
  106692. }
  106693. tempVertexData.indices = new Int32Array(indices);
  106694. indexCounts.push(tempVertexData.indices.length);
  106695. }
  106696. if (!vertexData) {
  106697. vertexData = tempVertexData;
  106698. }
  106699. else {
  106700. vertexData.merge(tempVertexData);
  106701. }
  106702. // Sub material
  106703. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106704. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106705. // Update vertices start and index start
  106706. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106707. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106708. }
  106709. }
  106710. var material;
  106711. if (subMaterials.length > 1) {
  106712. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106713. material.subMaterials = subMaterials;
  106714. }
  106715. else {
  106716. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106717. }
  106718. if (subMaterials.length === 1) {
  106719. material = subMaterials[0];
  106720. }
  106721. if (!newMesh.material) {
  106722. newMesh.material = material;
  106723. }
  106724. // Apply geometry
  106725. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106726. newMesh.computeWorldMatrix(true);
  106727. // Apply submeshes
  106728. newMesh.subMeshes = [];
  106729. var index = 0;
  106730. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106731. var meshID = meshes[meshIndex];
  106732. var mesh = gltfRuntime.meshes[meshID];
  106733. if (!mesh) {
  106734. continue;
  106735. }
  106736. for (var i = 0; i < mesh.primitives.length; i++) {
  106737. if (mesh.primitives[i].mode !== 4) {
  106738. //continue;
  106739. }
  106740. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106741. index++;
  106742. }
  106743. }
  106744. // Finish
  106745. return newMesh;
  106746. };
  106747. /**
  106748. * Configure node transformation from position, rotation and scaling
  106749. */
  106750. var configureNode = function (newNode, position, rotation, scaling) {
  106751. if (newNode.position) {
  106752. newNode.position = position;
  106753. }
  106754. if (newNode.rotationQuaternion || newNode.rotation) {
  106755. newNode.rotationQuaternion = rotation;
  106756. }
  106757. if (newNode.scaling) {
  106758. newNode.scaling = scaling;
  106759. }
  106760. };
  106761. /**
  106762. * Configures node from transformation matrix
  106763. */
  106764. var configureNodeFromMatrix = function (newNode, node, parent) {
  106765. if (node.matrix) {
  106766. var position = new BABYLON.Vector3(0, 0, 0);
  106767. var rotation = new BABYLON.Quaternion();
  106768. var scaling = new BABYLON.Vector3(0, 0, 0);
  106769. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106770. mat.decompose(scaling, rotation, position);
  106771. configureNode(newNode, position, rotation, scaling);
  106772. }
  106773. else if (node.translation && node.rotation && node.scale) {
  106774. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106775. }
  106776. newNode.computeWorldMatrix(true);
  106777. };
  106778. /**
  106779. * Imports a node
  106780. */
  106781. var importNode = function (gltfRuntime, node, id, parent) {
  106782. var lastNode = null;
  106783. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106784. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106785. return null;
  106786. }
  106787. }
  106788. // Meshes
  106789. if (node.skin) {
  106790. if (node.meshes) {
  106791. var skin = gltfRuntime.skins[node.skin];
  106792. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106793. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106794. if (newMesh.skeleton === null) {
  106795. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106796. if (!skin.babylonSkeleton) {
  106797. skin.babylonSkeleton = newMesh.skeleton;
  106798. }
  106799. }
  106800. lastNode = newMesh;
  106801. }
  106802. }
  106803. else if (node.meshes) {
  106804. /**
  106805. * Improve meshes property
  106806. */
  106807. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106808. lastNode = newMesh;
  106809. }
  106810. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106811. var light = gltfRuntime.lights[node.light];
  106812. if (light) {
  106813. if (light.type === "ambient") {
  106814. var ambienLight = light[light.type];
  106815. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106816. hemiLight.name = node.name || "";
  106817. if (ambienLight.color) {
  106818. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106819. }
  106820. lastNode = hemiLight;
  106821. }
  106822. else if (light.type === "directional") {
  106823. var directionalLight = light[light.type];
  106824. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106825. dirLight.name = node.name || "";
  106826. if (directionalLight.color) {
  106827. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106828. }
  106829. lastNode = dirLight;
  106830. }
  106831. else if (light.type === "point") {
  106832. var pointLight = light[light.type];
  106833. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106834. ptLight.name = node.name || "";
  106835. if (pointLight.color) {
  106836. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106837. }
  106838. lastNode = ptLight;
  106839. }
  106840. else if (light.type === "spot") {
  106841. var spotLight = light[light.type];
  106842. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106843. spLight.name = node.name || "";
  106844. if (spotLight.color) {
  106845. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106846. }
  106847. if (spotLight.fallOfAngle) {
  106848. spLight.angle = spotLight.fallOfAngle;
  106849. }
  106850. if (spotLight.fallOffExponent) {
  106851. spLight.exponent = spotLight.fallOffExponent;
  106852. }
  106853. lastNode = spLight;
  106854. }
  106855. }
  106856. }
  106857. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106858. var camera = gltfRuntime.cameras[node.camera];
  106859. if (camera) {
  106860. if (camera.type === "orthographic") {
  106861. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106862. orthoCamera.name = node.name || "";
  106863. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106864. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106865. lastNode = orthoCamera;
  106866. }
  106867. else if (camera.type === "perspective") {
  106868. var perspectiveCamera = camera[camera.type];
  106869. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106870. persCamera.name = node.name || "";
  106871. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106872. if (!perspectiveCamera.aspectRatio) {
  106873. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106874. }
  106875. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106876. persCamera.maxZ = perspectiveCamera.zfar;
  106877. persCamera.minZ = perspectiveCamera.znear;
  106878. }
  106879. lastNode = persCamera;
  106880. }
  106881. }
  106882. }
  106883. // Empty node
  106884. if (!node.jointName) {
  106885. if (node.babylonNode) {
  106886. return node.babylonNode;
  106887. }
  106888. else if (lastNode === null) {
  106889. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106890. node.babylonNode = dummy;
  106891. lastNode = dummy;
  106892. }
  106893. }
  106894. if (lastNode !== null) {
  106895. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106896. configureNodeFromMatrix(lastNode, node, parent);
  106897. }
  106898. else {
  106899. var translation = node.translation || [0, 0, 0];
  106900. var rotation = node.rotation || [0, 0, 0, 1];
  106901. var scale = node.scale || [1, 1, 1];
  106902. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106903. }
  106904. lastNode.updateCache(true);
  106905. node.babylonNode = lastNode;
  106906. }
  106907. return lastNode;
  106908. };
  106909. /**
  106910. * Traverses nodes and creates them
  106911. */
  106912. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106913. if (meshIncluded === void 0) { meshIncluded = false; }
  106914. var node = gltfRuntime.nodes[id];
  106915. var newNode = null;
  106916. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  106917. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  106918. meshIncluded = true;
  106919. }
  106920. else {
  106921. meshIncluded = false;
  106922. }
  106923. }
  106924. else {
  106925. meshIncluded = true;
  106926. }
  106927. if (!node.jointName && meshIncluded) {
  106928. newNode = importNode(gltfRuntime, node, id, parent);
  106929. if (newNode !== null) {
  106930. newNode.id = id;
  106931. newNode.parent = parent;
  106932. }
  106933. }
  106934. if (node.children) {
  106935. for (var i = 0; i < node.children.length; i++) {
  106936. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  106937. }
  106938. }
  106939. };
  106940. /**
  106941. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  106942. */
  106943. var postLoad = function (gltfRuntime) {
  106944. // Nodes
  106945. var currentScene = gltfRuntime.currentScene;
  106946. if (currentScene) {
  106947. for (var i = 0; i < currentScene.nodes.length; i++) {
  106948. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106949. }
  106950. }
  106951. else {
  106952. for (var thing in gltfRuntime.scenes) {
  106953. currentScene = gltfRuntime.scenes[thing];
  106954. for (var i = 0; i < currentScene.nodes.length; i++) {
  106955. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106956. }
  106957. }
  106958. }
  106959. // Set animations
  106960. loadAnimations(gltfRuntime);
  106961. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  106962. var skeleton = gltfRuntime.scene.skeletons[i];
  106963. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  106964. }
  106965. };
  106966. /**
  106967. * onBind shaderrs callback to set uniforms and matrices
  106968. */
  106969. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  106970. var materialValues = material.values || technique.parameters;
  106971. for (var unif in unTreatedUniforms) {
  106972. var uniform = unTreatedUniforms[unif];
  106973. var type = uniform.type;
  106974. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  106975. if (uniform.semantic && !uniform.source && !uniform.node) {
  106976. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  106977. }
  106978. else if (uniform.semantic && (uniform.source || uniform.node)) {
  106979. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  106980. if (source === null) {
  106981. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  106982. }
  106983. if (source === null) {
  106984. continue;
  106985. }
  106986. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  106987. }
  106988. }
  106989. else {
  106990. var value = materialValues[technique.uniforms[unif]];
  106991. if (!value) {
  106992. continue;
  106993. }
  106994. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106995. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  106996. if (texture === null || texture === undefined) {
  106997. continue;
  106998. }
  106999. shaderMaterial.getEffect().setTexture(unif, texture);
  107000. }
  107001. else {
  107002. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107003. }
  107004. }
  107005. }
  107006. onSuccess(shaderMaterial);
  107007. };
  107008. /**
  107009. * Prepare uniforms to send the only one time
  107010. * Loads the appropriate textures
  107011. */
  107012. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107013. var materialValues = material.values || technique.parameters;
  107014. var techniqueUniforms = technique.uniforms;
  107015. /**
  107016. * Prepare values here (not matrices)
  107017. */
  107018. for (var unif in unTreatedUniforms) {
  107019. var uniform = unTreatedUniforms[unif];
  107020. var type = uniform.type;
  107021. var value = materialValues[techniqueUniforms[unif]];
  107022. if (value === undefined) {
  107023. // In case the value is the same for all materials
  107024. value = uniform.value;
  107025. }
  107026. if (!value) {
  107027. continue;
  107028. }
  107029. var onLoadTexture = function (uniformName) {
  107030. return function (texture) {
  107031. if (uniform.value && uniformName) {
  107032. // Static uniform
  107033. shaderMaterial.setTexture(uniformName, texture);
  107034. delete unTreatedUniforms[uniformName];
  107035. }
  107036. };
  107037. };
  107038. // Texture (sampler2D)
  107039. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107040. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107041. }
  107042. else {
  107043. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107044. // Static uniform
  107045. delete unTreatedUniforms[unif];
  107046. }
  107047. }
  107048. }
  107049. };
  107050. /**
  107051. * Shader compilation failed
  107052. */
  107053. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107054. return function (effect, error) {
  107055. shaderMaterial.dispose(true);
  107056. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107057. };
  107058. };
  107059. /**
  107060. * Shader compilation success
  107061. */
  107062. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107063. return function (_) {
  107064. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107065. shaderMaterial.onBind = function (mesh) {
  107066. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107067. };
  107068. };
  107069. };
  107070. /**
  107071. * Returns the appropriate uniform if already handled by babylon
  107072. */
  107073. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107074. for (var unif in technique.uniforms) {
  107075. var uniform = technique.uniforms[unif];
  107076. var uniformParameter = technique.parameters[uniform];
  107077. if (tokenizer.currentIdentifier === unif) {
  107078. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107079. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107080. if (transformIndex !== -1) {
  107081. delete unTreatedUniforms[unif];
  107082. return babylonTransforms[transformIndex];
  107083. }
  107084. }
  107085. }
  107086. }
  107087. return tokenizer.currentIdentifier;
  107088. };
  107089. /**
  107090. * All shaders loaded. Create materials one by one
  107091. */
  107092. var importMaterials = function (gltfRuntime) {
  107093. // Create materials
  107094. for (var mat in gltfRuntime.materials) {
  107095. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107096. }
  107097. };
  107098. /**
  107099. * Implementation of the base glTF spec
  107100. */
  107101. var GLTFLoaderBase = /** @class */ (function () {
  107102. function GLTFLoaderBase() {
  107103. }
  107104. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107105. var gltfRuntime = {
  107106. extensions: {},
  107107. accessors: {},
  107108. buffers: {},
  107109. bufferViews: {},
  107110. meshes: {},
  107111. lights: {},
  107112. cameras: {},
  107113. nodes: {},
  107114. images: {},
  107115. textures: {},
  107116. shaders: {},
  107117. programs: {},
  107118. samplers: {},
  107119. techniques: {},
  107120. materials: {},
  107121. animations: {},
  107122. skins: {},
  107123. extensionsUsed: [],
  107124. scenes: {},
  107125. buffersCount: 0,
  107126. shaderscount: 0,
  107127. scene: scene,
  107128. rootUrl: rootUrl,
  107129. loadedBufferCount: 0,
  107130. loadedBufferViews: {},
  107131. loadedShaderCount: 0,
  107132. importOnlyMeshes: false,
  107133. dummyNodes: []
  107134. };
  107135. // Parse
  107136. if (parsedData.extensions) {
  107137. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107138. }
  107139. if (parsedData.extensionsUsed) {
  107140. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107141. }
  107142. if (parsedData.buffers) {
  107143. parseBuffers(parsedData.buffers, gltfRuntime);
  107144. }
  107145. if (parsedData.bufferViews) {
  107146. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107147. }
  107148. if (parsedData.accessors) {
  107149. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107150. }
  107151. if (parsedData.meshes) {
  107152. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107153. }
  107154. if (parsedData.lights) {
  107155. parseObject(parsedData.lights, "lights", gltfRuntime);
  107156. }
  107157. if (parsedData.cameras) {
  107158. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107159. }
  107160. if (parsedData.nodes) {
  107161. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107162. }
  107163. if (parsedData.images) {
  107164. parseObject(parsedData.images, "images", gltfRuntime);
  107165. }
  107166. if (parsedData.textures) {
  107167. parseObject(parsedData.textures, "textures", gltfRuntime);
  107168. }
  107169. if (parsedData.shaders) {
  107170. parseShaders(parsedData.shaders, gltfRuntime);
  107171. }
  107172. if (parsedData.programs) {
  107173. parseObject(parsedData.programs, "programs", gltfRuntime);
  107174. }
  107175. if (parsedData.samplers) {
  107176. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107177. }
  107178. if (parsedData.techniques) {
  107179. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107180. }
  107181. if (parsedData.materials) {
  107182. parseObject(parsedData.materials, "materials", gltfRuntime);
  107183. }
  107184. if (parsedData.animations) {
  107185. parseObject(parsedData.animations, "animations", gltfRuntime);
  107186. }
  107187. if (parsedData.skins) {
  107188. parseObject(parsedData.skins, "skins", gltfRuntime);
  107189. }
  107190. if (parsedData.scenes) {
  107191. gltfRuntime.scenes = parsedData.scenes;
  107192. }
  107193. if (parsedData.scene && parsedData.scenes) {
  107194. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107195. }
  107196. return gltfRuntime;
  107197. };
  107198. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107199. var buffer = gltfRuntime.buffers[id];
  107200. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107201. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107202. }
  107203. else {
  107204. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107205. if (request) {
  107206. onError(request.status + " " + request.statusText);
  107207. }
  107208. });
  107209. }
  107210. };
  107211. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107212. var texture = gltfRuntime.textures[id];
  107213. if (!texture || !texture.source) {
  107214. onError("");
  107215. return;
  107216. }
  107217. if (texture.babylonTexture) {
  107218. onSuccess(null);
  107219. return;
  107220. }
  107221. var source = gltfRuntime.images[texture.source];
  107222. if (BABYLON.Tools.IsBase64(source.uri)) {
  107223. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107224. }
  107225. else {
  107226. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107227. if (request) {
  107228. onError(request.status + " " + request.statusText);
  107229. }
  107230. });
  107231. }
  107232. };
  107233. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107234. var texture = gltfRuntime.textures[id];
  107235. if (texture.babylonTexture) {
  107236. onSuccess(texture.babylonTexture);
  107237. return;
  107238. }
  107239. var sampler = gltfRuntime.samplers[texture.sampler];
  107240. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107241. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107242. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107243. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107244. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107245. var blob = new Blob([buffer]);
  107246. var blobURL = URL.createObjectURL(blob);
  107247. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107248. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107249. if (sampler.wrapS !== undefined) {
  107250. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107251. }
  107252. if (sampler.wrapT !== undefined) {
  107253. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107254. }
  107255. newTexture.name = id;
  107256. texture.babylonTexture = newTexture;
  107257. onSuccess(newTexture);
  107258. };
  107259. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107260. var shader = gltfRuntime.shaders[id];
  107261. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107262. var shaderString = atob(shader.uri.split(",")[1]);
  107263. onSuccess(shaderString);
  107264. }
  107265. else {
  107266. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107267. if (request) {
  107268. onError(request.status + " " + request.statusText);
  107269. }
  107270. });
  107271. }
  107272. };
  107273. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107274. var material = gltfRuntime.materials[id];
  107275. if (!material.technique) {
  107276. if (onError) {
  107277. onError("No technique found.");
  107278. }
  107279. return;
  107280. }
  107281. var technique = gltfRuntime.techniques[material.technique];
  107282. if (!technique) {
  107283. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107284. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107285. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107286. onSuccess(defaultMaterial);
  107287. return;
  107288. }
  107289. var program = gltfRuntime.programs[technique.program];
  107290. var states = technique.states;
  107291. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107292. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107293. var newVertexShader = "";
  107294. var newPixelShader = "";
  107295. var vertexTokenizer = new Tokenizer(vertexShader);
  107296. var pixelTokenizer = new Tokenizer(pixelShader);
  107297. var unTreatedUniforms = {};
  107298. var uniforms = [];
  107299. var attributes = [];
  107300. var samplers = [];
  107301. // Fill uniform, sampler2D and attributes
  107302. for (var unif in technique.uniforms) {
  107303. var uniform = technique.uniforms[unif];
  107304. var uniformParameter = technique.parameters[uniform];
  107305. unTreatedUniforms[unif] = uniformParameter;
  107306. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107307. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107308. if (transformIndex !== -1) {
  107309. uniforms.push(babylonTransforms[transformIndex]);
  107310. delete unTreatedUniforms[unif];
  107311. }
  107312. else {
  107313. uniforms.push(unif);
  107314. }
  107315. }
  107316. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107317. samplers.push(unif);
  107318. }
  107319. else {
  107320. uniforms.push(unif);
  107321. }
  107322. }
  107323. for (var attr in technique.attributes) {
  107324. var attribute = technique.attributes[attr];
  107325. var attributeParameter = technique.parameters[attribute];
  107326. if (attributeParameter.semantic) {
  107327. attributes.push(getAttribute(attributeParameter));
  107328. }
  107329. }
  107330. // Configure vertex shader
  107331. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107332. var tokenType = vertexTokenizer.currentToken;
  107333. if (tokenType !== ETokenType.IDENTIFIER) {
  107334. newVertexShader += vertexTokenizer.currentString;
  107335. continue;
  107336. }
  107337. var foundAttribute = false;
  107338. for (var attr in technique.attributes) {
  107339. var attribute = technique.attributes[attr];
  107340. var attributeParameter = technique.parameters[attribute];
  107341. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107342. newVertexShader += getAttribute(attributeParameter);
  107343. foundAttribute = true;
  107344. break;
  107345. }
  107346. }
  107347. if (foundAttribute) {
  107348. continue;
  107349. }
  107350. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107351. }
  107352. // Configure pixel shader
  107353. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107354. var tokenType = pixelTokenizer.currentToken;
  107355. if (tokenType !== ETokenType.IDENTIFIER) {
  107356. newPixelShader += pixelTokenizer.currentString;
  107357. continue;
  107358. }
  107359. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107360. }
  107361. // Create shader material
  107362. var shaderPath = {
  107363. vertex: program.vertexShader + id,
  107364. fragment: program.fragmentShader + id
  107365. };
  107366. var options = {
  107367. attributes: attributes,
  107368. uniforms: uniforms,
  107369. samplers: samplers,
  107370. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107371. };
  107372. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107373. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107374. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107375. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107376. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107377. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107378. if (states && states.functions) {
  107379. var functions = states.functions;
  107380. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107381. shaderMaterial.backFaceCulling = false;
  107382. }
  107383. var blendFunc = functions.blendFuncSeparate;
  107384. if (blendFunc) {
  107385. 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) {
  107386. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107387. }
  107388. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107389. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107390. }
  107391. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107392. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107393. }
  107394. 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) {
  107395. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107396. }
  107397. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107398. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107399. }
  107400. 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) {
  107401. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107402. }
  107403. }
  107404. }
  107405. };
  107406. return GLTFLoaderBase;
  107407. }());
  107408. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107409. /**
  107410. * glTF V1 Loader
  107411. */
  107412. var GLTFLoader = /** @class */ (function () {
  107413. function GLTFLoader() {
  107414. // #region Stubs for IGLTFLoader interface
  107415. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107416. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107417. this.compileMaterials = false;
  107418. this.useClipPlane = false;
  107419. this.compileShadowGenerators = false;
  107420. this.onDisposeObservable = new BABYLON.Observable();
  107421. this.onMeshLoadedObservable = new BABYLON.Observable();
  107422. this.onTextureLoadedObservable = new BABYLON.Observable();
  107423. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107424. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107425. this.onCompleteObservable = new BABYLON.Observable();
  107426. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107427. this.state = null;
  107428. }
  107429. GLTFLoader.RegisterExtension = function (extension) {
  107430. if (GLTFLoader.Extensions[extension.name]) {
  107431. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107432. return;
  107433. }
  107434. GLTFLoader.Extensions[extension.name] = extension;
  107435. };
  107436. GLTFLoader.prototype.dispose = function () { };
  107437. // #endregion
  107438. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107439. var _this = this;
  107440. scene.useRightHandedSystem = true;
  107441. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107442. gltfRuntime.importOnlyMeshes = true;
  107443. if (meshesNames === "") {
  107444. gltfRuntime.importMeshesNames = [];
  107445. }
  107446. else if (typeof meshesNames === "string") {
  107447. gltfRuntime.importMeshesNames = [meshesNames];
  107448. }
  107449. else if (meshesNames && !(meshesNames instanceof Array)) {
  107450. gltfRuntime.importMeshesNames = [meshesNames];
  107451. }
  107452. else {
  107453. gltfRuntime.importMeshesNames = [];
  107454. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107455. }
  107456. // Create nodes
  107457. _this._createNodes(gltfRuntime);
  107458. var meshes = new Array();
  107459. var skeletons = new Array();
  107460. // Fill arrays of meshes and skeletons
  107461. for (var nde in gltfRuntime.nodes) {
  107462. var node = gltfRuntime.nodes[nde];
  107463. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107464. meshes.push(node.babylonNode);
  107465. }
  107466. }
  107467. for (var skl in gltfRuntime.skins) {
  107468. var skin = gltfRuntime.skins[skl];
  107469. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107470. skeletons.push(skin.babylonSkeleton);
  107471. }
  107472. }
  107473. // Load buffers, shaders, materials, etc.
  107474. _this._loadBuffersAsync(gltfRuntime, function () {
  107475. _this._loadShadersAsync(gltfRuntime, function () {
  107476. importMaterials(gltfRuntime);
  107477. postLoad(gltfRuntime);
  107478. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107479. onSuccess(meshes, [], skeletons);
  107480. }
  107481. });
  107482. }, onProgress);
  107483. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107484. onSuccess(meshes, [], skeletons);
  107485. }
  107486. }, onError);
  107487. return true;
  107488. };
  107489. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107490. var _this = this;
  107491. return new Promise(function (resolve, reject) {
  107492. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107493. resolve({
  107494. meshes: meshes,
  107495. particleSystems: particleSystems,
  107496. skeletons: skeletons
  107497. });
  107498. }, onProgress, function (message) {
  107499. reject(new Error(message));
  107500. });
  107501. });
  107502. };
  107503. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107504. var _this = this;
  107505. scene.useRightHandedSystem = true;
  107506. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107507. // Load runtime extensios
  107508. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107509. // Create nodes
  107510. _this._createNodes(gltfRuntime);
  107511. // Load buffers, shaders, materials, etc.
  107512. _this._loadBuffersAsync(gltfRuntime, function () {
  107513. _this._loadShadersAsync(gltfRuntime, function () {
  107514. importMaterials(gltfRuntime);
  107515. postLoad(gltfRuntime);
  107516. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107517. onSuccess();
  107518. }
  107519. });
  107520. });
  107521. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107522. onSuccess();
  107523. }
  107524. }, onError);
  107525. }, onError);
  107526. };
  107527. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107528. var _this = this;
  107529. return new Promise(function (resolve, reject) {
  107530. _this._loadAsync(scene, data, rootUrl, function () {
  107531. resolve();
  107532. }, onProgress, function (message) {
  107533. reject(new Error(message));
  107534. });
  107535. });
  107536. };
  107537. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107538. var hasShaders = false;
  107539. var processShader = function (sha, shader) {
  107540. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107541. gltfRuntime.loadedShaderCount++;
  107542. if (shaderString) {
  107543. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107544. }
  107545. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107546. onload();
  107547. }
  107548. }, function () {
  107549. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107550. });
  107551. };
  107552. for (var sha in gltfRuntime.shaders) {
  107553. hasShaders = true;
  107554. var shader = gltfRuntime.shaders[sha];
  107555. if (shader) {
  107556. processShader.bind(this, sha, shader)();
  107557. }
  107558. else {
  107559. BABYLON.Tools.Error("No shader named: " + sha);
  107560. }
  107561. }
  107562. if (!hasShaders) {
  107563. onload();
  107564. }
  107565. };
  107566. ;
  107567. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107568. var hasBuffers = false;
  107569. var processBuffer = function (buf, buffer) {
  107570. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107571. gltfRuntime.loadedBufferCount++;
  107572. if (bufferView) {
  107573. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107574. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107575. }
  107576. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107577. }
  107578. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107579. onLoad();
  107580. }
  107581. }, function () {
  107582. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107583. });
  107584. };
  107585. for (var buf in gltfRuntime.buffers) {
  107586. hasBuffers = true;
  107587. var buffer = gltfRuntime.buffers[buf];
  107588. if (buffer) {
  107589. processBuffer.bind(this, buf, buffer)();
  107590. }
  107591. else {
  107592. BABYLON.Tools.Error("No buffer named: " + buf);
  107593. }
  107594. }
  107595. if (!hasBuffers) {
  107596. onLoad();
  107597. }
  107598. };
  107599. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107600. var currentScene = gltfRuntime.currentScene;
  107601. if (currentScene) {
  107602. // Only one scene even if multiple scenes are defined
  107603. for (var i = 0; i < currentScene.nodes.length; i++) {
  107604. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107605. }
  107606. }
  107607. else {
  107608. // Load all scenes
  107609. for (var thing in gltfRuntime.scenes) {
  107610. currentScene = gltfRuntime.scenes[thing];
  107611. for (var i = 0; i < currentScene.nodes.length; i++) {
  107612. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107613. }
  107614. }
  107615. }
  107616. };
  107617. GLTFLoader.Extensions = {};
  107618. return GLTFLoader;
  107619. }());
  107620. GLTF1.GLTFLoader = GLTFLoader;
  107621. ;
  107622. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107623. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107624. })(BABYLON || (BABYLON = {}));
  107625. //# sourceMappingURL=babylon.glTFLoader.js.map
  107626. var BABYLON;
  107627. (function (BABYLON) {
  107628. var GLTF1;
  107629. (function (GLTF1) {
  107630. /**
  107631. * Utils functions for GLTF
  107632. */
  107633. var GLTFUtils = /** @class */ (function () {
  107634. function GLTFUtils() {
  107635. }
  107636. /**
  107637. * Sets the given "parameter" matrix
  107638. * @param scene: the {BABYLON.Scene} object
  107639. * @param source: the source node where to pick the matrix
  107640. * @param parameter: the GLTF technique parameter
  107641. * @param uniformName: the name of the shader's uniform
  107642. * @param shaderMaterial: the shader material
  107643. */
  107644. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107645. var mat = null;
  107646. if (parameter.semantic === "MODEL") {
  107647. mat = source.getWorldMatrix();
  107648. }
  107649. else if (parameter.semantic === "PROJECTION") {
  107650. mat = scene.getProjectionMatrix();
  107651. }
  107652. else if (parameter.semantic === "VIEW") {
  107653. mat = scene.getViewMatrix();
  107654. }
  107655. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107656. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107657. }
  107658. else if (parameter.semantic === "MODELVIEW") {
  107659. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107660. }
  107661. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107662. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107663. }
  107664. else if (parameter.semantic === "MODELINVERSE") {
  107665. mat = source.getWorldMatrix().invert();
  107666. }
  107667. else if (parameter.semantic === "VIEWINVERSE") {
  107668. mat = scene.getViewMatrix().invert();
  107669. }
  107670. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107671. mat = scene.getProjectionMatrix().invert();
  107672. }
  107673. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107674. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107675. }
  107676. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107677. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107678. }
  107679. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107680. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107681. }
  107682. else {
  107683. debugger;
  107684. }
  107685. if (mat) {
  107686. switch (parameter.type) {
  107687. case GLTF1.EParameterType.FLOAT_MAT2:
  107688. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107689. break;
  107690. case GLTF1.EParameterType.FLOAT_MAT3:
  107691. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107692. break;
  107693. case GLTF1.EParameterType.FLOAT_MAT4:
  107694. shaderMaterial.setMatrix(uniformName, mat);
  107695. break;
  107696. default: break;
  107697. }
  107698. }
  107699. };
  107700. /**
  107701. * Sets the given "parameter" matrix
  107702. * @param shaderMaterial: the shader material
  107703. * @param uniform: the name of the shader's uniform
  107704. * @param value: the value of the uniform
  107705. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107706. */
  107707. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107708. switch (type) {
  107709. case GLTF1.EParameterType.FLOAT:
  107710. shaderMaterial.setFloat(uniform, value);
  107711. return true;
  107712. case GLTF1.EParameterType.FLOAT_VEC2:
  107713. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107714. return true;
  107715. case GLTF1.EParameterType.FLOAT_VEC3:
  107716. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107717. return true;
  107718. case GLTF1.EParameterType.FLOAT_VEC4:
  107719. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107720. return true;
  107721. default: return false;
  107722. }
  107723. };
  107724. /**
  107725. * Returns the wrap mode of the texture
  107726. * @param mode: the mode value
  107727. */
  107728. GLTFUtils.GetWrapMode = function (mode) {
  107729. switch (mode) {
  107730. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107731. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107732. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107733. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107734. }
  107735. };
  107736. /**
  107737. * Returns the byte stride giving an accessor
  107738. * @param accessor: the GLTF accessor objet
  107739. */
  107740. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107741. // Needs this function since "byteStride" isn't requiered in glTF format
  107742. var type = accessor.type;
  107743. switch (type) {
  107744. case "VEC2": return 2;
  107745. case "VEC3": return 3;
  107746. case "VEC4": return 4;
  107747. case "MAT2": return 4;
  107748. case "MAT3": return 9;
  107749. case "MAT4": return 16;
  107750. default: return 1;
  107751. }
  107752. };
  107753. /**
  107754. * Returns the texture filter mode giving a mode value
  107755. * @param mode: the filter mode value
  107756. */
  107757. GLTFUtils.GetTextureFilterMode = function (mode) {
  107758. switch (mode) {
  107759. case GLTF1.ETextureFilterType.LINEAR:
  107760. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107761. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107762. case GLTF1.ETextureFilterType.NEAREST:
  107763. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107764. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107765. }
  107766. };
  107767. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107768. var byteOffset = bufferView.byteOffset + byteOffset;
  107769. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107770. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107771. throw new Error("Buffer access is out of range");
  107772. }
  107773. var buffer = loadedBufferView.buffer;
  107774. byteOffset += loadedBufferView.byteOffset;
  107775. switch (componentType) {
  107776. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107777. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107778. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107779. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107780. default: return new Float32Array(buffer, byteOffset, byteLength);
  107781. }
  107782. };
  107783. /**
  107784. * Returns a buffer from its accessor
  107785. * @param gltfRuntime: the GLTF runtime
  107786. * @param accessor: the GLTF accessor
  107787. */
  107788. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107789. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107790. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107791. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107792. };
  107793. /**
  107794. * Decodes a buffer view into a string
  107795. * @param view: the buffer view
  107796. */
  107797. GLTFUtils.DecodeBufferToText = function (view) {
  107798. var result = "";
  107799. var length = view.byteLength;
  107800. for (var i = 0; i < length; ++i) {
  107801. result += String.fromCharCode(view[i]);
  107802. }
  107803. return result;
  107804. };
  107805. /**
  107806. * Returns the default material of gltf. Related to
  107807. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107808. * @param scene: the Babylon.js scene
  107809. */
  107810. GLTFUtils.GetDefaultMaterial = function (scene) {
  107811. if (!GLTFUtils._DefaultMaterial) {
  107812. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107813. "precision highp float;",
  107814. "",
  107815. "uniform mat4 worldView;",
  107816. "uniform mat4 projection;",
  107817. "",
  107818. "attribute vec3 position;",
  107819. "",
  107820. "void main(void)",
  107821. "{",
  107822. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107823. "}"
  107824. ].join("\n");
  107825. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107826. "precision highp float;",
  107827. "",
  107828. "uniform vec4 u_emission;",
  107829. "",
  107830. "void main(void)",
  107831. "{",
  107832. " gl_FragColor = u_emission;",
  107833. "}"
  107834. ].join("\n");
  107835. var shaderPath = {
  107836. vertex: "GLTFDefaultMaterial",
  107837. fragment: "GLTFDefaultMaterial"
  107838. };
  107839. var options = {
  107840. attributes: ["position"],
  107841. uniforms: ["worldView", "projection", "u_emission"],
  107842. samplers: new Array(),
  107843. needAlphaBlending: false
  107844. };
  107845. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107846. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107847. }
  107848. return GLTFUtils._DefaultMaterial;
  107849. };
  107850. // The GLTF default material
  107851. GLTFUtils._DefaultMaterial = null;
  107852. return GLTFUtils;
  107853. }());
  107854. GLTF1.GLTFUtils = GLTFUtils;
  107855. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107856. })(BABYLON || (BABYLON = {}));
  107857. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107858. var BABYLON;
  107859. (function (BABYLON) {
  107860. var GLTF1;
  107861. (function (GLTF1) {
  107862. var GLTFLoaderExtension = /** @class */ (function () {
  107863. function GLTFLoaderExtension(name) {
  107864. this._name = name;
  107865. }
  107866. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107867. get: function () {
  107868. return this._name;
  107869. },
  107870. enumerable: true,
  107871. configurable: true
  107872. });
  107873. /**
  107874. * Defines an override for loading the runtime
  107875. * Return true to stop further extensions from loading the runtime
  107876. */
  107877. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107878. return false;
  107879. };
  107880. /**
  107881. * Defines an onverride for creating gltf runtime
  107882. * Return true to stop further extensions from creating the runtime
  107883. */
  107884. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107885. return false;
  107886. };
  107887. /**
  107888. * Defines an override for loading buffers
  107889. * Return true to stop further extensions from loading this buffer
  107890. */
  107891. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107892. return false;
  107893. };
  107894. /**
  107895. * Defines an override for loading texture buffers
  107896. * Return true to stop further extensions from loading this texture data
  107897. */
  107898. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107899. return false;
  107900. };
  107901. /**
  107902. * Defines an override for creating textures
  107903. * Return true to stop further extensions from loading this texture
  107904. */
  107905. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107906. return false;
  107907. };
  107908. /**
  107909. * Defines an override for loading shader strings
  107910. * Return true to stop further extensions from loading this shader data
  107911. */
  107912. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107913. return false;
  107914. };
  107915. /**
  107916. * Defines an override for loading materials
  107917. * Return true to stop further extensions from loading this material
  107918. */
  107919. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107920. return false;
  107921. };
  107922. // ---------
  107923. // Utilities
  107924. // ---------
  107925. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107926. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107927. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  107928. }, function () {
  107929. setTimeout(function () {
  107930. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107931. });
  107932. });
  107933. };
  107934. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107935. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107936. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  107937. }, function () {
  107938. setTimeout(function () {
  107939. onSuccess();
  107940. });
  107941. });
  107942. };
  107943. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107944. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107945. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107946. }, function () {
  107947. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107948. });
  107949. };
  107950. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  107951. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  107952. };
  107953. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107954. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107955. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107956. }, function () {
  107957. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107958. });
  107959. };
  107960. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107961. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107962. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107963. }, function () {
  107964. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107965. });
  107966. };
  107967. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107968. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107969. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107970. }, function () {
  107971. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107972. });
  107973. };
  107974. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107975. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107976. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107977. }, function () {
  107978. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107979. });
  107980. };
  107981. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107982. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107983. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107984. if (func(loaderExtension)) {
  107985. return;
  107986. }
  107987. }
  107988. defaultFunc();
  107989. };
  107990. return GLTFLoaderExtension;
  107991. }());
  107992. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107993. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107994. })(BABYLON || (BABYLON = {}));
  107995. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107996. var BABYLON;
  107997. (function (BABYLON) {
  107998. var GLTF1;
  107999. (function (GLTF1) {
  108000. var BinaryExtensionBufferName = "binary_glTF";
  108001. ;
  108002. ;
  108003. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108004. __extends(GLTFBinaryExtension, _super);
  108005. function GLTFBinaryExtension() {
  108006. return _super.call(this, "KHR_binary_glTF") || this;
  108007. }
  108008. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108009. var extensionsUsed = data.json.extensionsUsed;
  108010. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108011. return false;
  108012. }
  108013. this._bin = data.bin;
  108014. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108015. return true;
  108016. };
  108017. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108018. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108019. return false;
  108020. }
  108021. if (id !== BinaryExtensionBufferName) {
  108022. return false;
  108023. }
  108024. onSuccess(this._bin);
  108025. return true;
  108026. };
  108027. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108028. var texture = gltfRuntime.textures[id];
  108029. var source = gltfRuntime.images[texture.source];
  108030. if (!source.extensions || !(this.name in source.extensions)) {
  108031. return false;
  108032. }
  108033. var sourceExt = source.extensions[this.name];
  108034. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108035. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108036. onSuccess(buffer);
  108037. return true;
  108038. };
  108039. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108040. var shader = gltfRuntime.shaders[id];
  108041. if (!shader.extensions || !(this.name in shader.extensions)) {
  108042. return false;
  108043. }
  108044. var binaryExtensionShader = shader.extensions[this.name];
  108045. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108046. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108047. setTimeout(function () {
  108048. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108049. onSuccess(shaderString);
  108050. });
  108051. return true;
  108052. };
  108053. return GLTFBinaryExtension;
  108054. }(GLTF1.GLTFLoaderExtension));
  108055. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108056. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108057. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108058. })(BABYLON || (BABYLON = {}));
  108059. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108060. var BABYLON;
  108061. (function (BABYLON) {
  108062. var GLTF1;
  108063. (function (GLTF1) {
  108064. ;
  108065. ;
  108066. ;
  108067. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108068. __extends(GLTFMaterialsCommonExtension, _super);
  108069. function GLTFMaterialsCommonExtension() {
  108070. return _super.call(this, "KHR_materials_common") || this;
  108071. }
  108072. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108073. if (!gltfRuntime.extensions)
  108074. return false;
  108075. var extension = gltfRuntime.extensions[this.name];
  108076. if (!extension)
  108077. return false;
  108078. // Create lights
  108079. var lights = extension.lights;
  108080. if (lights) {
  108081. for (var thing in lights) {
  108082. var light = lights[thing];
  108083. switch (light.type) {
  108084. case "ambient":
  108085. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108086. var ambient = light.ambient;
  108087. if (ambient) {
  108088. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108089. }
  108090. break;
  108091. case "point":
  108092. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108093. var point = light.point;
  108094. if (point) {
  108095. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108096. }
  108097. break;
  108098. case "directional":
  108099. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108100. var directional = light.directional;
  108101. if (directional) {
  108102. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108103. }
  108104. break;
  108105. case "spot":
  108106. var spot = light.spot;
  108107. if (spot) {
  108108. 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);
  108109. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108110. }
  108111. break;
  108112. default:
  108113. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108114. break;
  108115. }
  108116. }
  108117. }
  108118. return false;
  108119. };
  108120. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108121. var material = gltfRuntime.materials[id];
  108122. if (!material || !material.extensions)
  108123. return false;
  108124. var extension = material.extensions[this.name];
  108125. if (!extension)
  108126. return false;
  108127. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108128. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108129. if (extension.technique === "CONSTANT") {
  108130. standardMaterial.disableLighting = true;
  108131. }
  108132. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108133. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108134. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108135. // Ambient
  108136. if (typeof extension.values.ambient === "string") {
  108137. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108138. }
  108139. else {
  108140. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108141. }
  108142. // Diffuse
  108143. if (typeof extension.values.diffuse === "string") {
  108144. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108145. }
  108146. else {
  108147. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108148. }
  108149. // Emission
  108150. if (typeof extension.values.emission === "string") {
  108151. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108152. }
  108153. else {
  108154. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108155. }
  108156. // Specular
  108157. if (typeof extension.values.specular === "string") {
  108158. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108159. }
  108160. else {
  108161. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108162. }
  108163. return true;
  108164. };
  108165. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108166. // Create buffer from texture url
  108167. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108168. // Create texture from buffer
  108169. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108170. }, onError);
  108171. };
  108172. return GLTFMaterialsCommonExtension;
  108173. }(GLTF1.GLTFLoaderExtension));
  108174. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108175. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108176. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108177. })(BABYLON || (BABYLON = {}));
  108178. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108179. var BABYLON;
  108180. (function (BABYLON) {
  108181. var GLTF2;
  108182. (function (GLTF2) {
  108183. var ArrayItem = /** @class */ (function () {
  108184. function ArrayItem() {
  108185. }
  108186. ArrayItem.Assign = function (values) {
  108187. if (values) {
  108188. for (var index = 0; index < values.length; index++) {
  108189. values[index]._index = index;
  108190. }
  108191. }
  108192. };
  108193. return ArrayItem;
  108194. }());
  108195. GLTF2.ArrayItem = ArrayItem;
  108196. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108197. })(BABYLON || (BABYLON = {}));
  108198. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108199. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108200. var BABYLON;
  108201. (function (BABYLON) {
  108202. var GLTF2;
  108203. (function (GLTF2) {
  108204. var GLTFLoader = /** @class */ (function () {
  108205. function GLTFLoader() {
  108206. this._completePromises = new Array();
  108207. this._disposed = false;
  108208. this._state = null;
  108209. this._extensions = {};
  108210. this._defaultSampler = {};
  108211. this._requests = new Array();
  108212. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108213. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108214. this.compileMaterials = false;
  108215. this.useClipPlane = false;
  108216. this.compileShadowGenerators = false;
  108217. this.onDisposeObservable = new BABYLON.Observable();
  108218. this.onMeshLoadedObservable = new BABYLON.Observable();
  108219. this.onTextureLoadedObservable = new BABYLON.Observable();
  108220. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108221. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108222. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108223. this.onCompleteObservable = new BABYLON.Observable();
  108224. }
  108225. GLTFLoader._Register = function (name, factory) {
  108226. if (GLTFLoader._Factories[name]) {
  108227. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108228. return;
  108229. }
  108230. GLTFLoader._Factories[name] = factory;
  108231. // Keep the order of registration so that extensions registered first are called first.
  108232. GLTFLoader._Names.push(name);
  108233. };
  108234. Object.defineProperty(GLTFLoader.prototype, "state", {
  108235. get: function () {
  108236. return this._state;
  108237. },
  108238. enumerable: true,
  108239. configurable: true
  108240. });
  108241. GLTFLoader.prototype.dispose = function () {
  108242. if (this._disposed) {
  108243. return;
  108244. }
  108245. this._disposed = true;
  108246. this.onDisposeObservable.notifyObservers(this);
  108247. this.onDisposeObservable.clear();
  108248. this._clear();
  108249. };
  108250. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108251. var _this = this;
  108252. return Promise.resolve().then(function () {
  108253. var nodes = null;
  108254. if (meshesNames) {
  108255. var nodeMap_1 = {};
  108256. if (_this._gltf.nodes) {
  108257. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108258. var node = _a[_i];
  108259. if (node.name) {
  108260. nodeMap_1[node.name] = node;
  108261. }
  108262. }
  108263. }
  108264. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108265. nodes = names.map(function (name) {
  108266. var node = nodeMap_1[name];
  108267. if (!node) {
  108268. throw new Error("Failed to find node '" + name + "'");
  108269. }
  108270. return node;
  108271. });
  108272. }
  108273. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108274. return {
  108275. meshes: _this._getMeshes(),
  108276. particleSystems: [],
  108277. skeletons: _this._getSkeletons(),
  108278. };
  108279. });
  108280. });
  108281. };
  108282. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108283. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108284. };
  108285. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108286. var _this = this;
  108287. return Promise.resolve().then(function () {
  108288. _this._loadExtensions();
  108289. _this._babylonScene = scene;
  108290. _this._rootUrl = rootUrl;
  108291. _this._progressCallback = onProgress;
  108292. _this._state = BABYLON.GLTFLoaderState.Loading;
  108293. _this._loadData(data);
  108294. _this._checkExtensions();
  108295. var promises = new Array();
  108296. if (nodes) {
  108297. promises.push(_this._loadNodesAsync(nodes));
  108298. }
  108299. else {
  108300. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108301. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108302. }
  108303. if (_this.compileMaterials) {
  108304. promises.push(_this._compileMaterialsAsync());
  108305. }
  108306. if (_this.compileShadowGenerators) {
  108307. promises.push(_this._compileShadowGeneratorsAsync());
  108308. }
  108309. var resultPromise = Promise.all(promises).then(function () {
  108310. _this._state = BABYLON.GLTFLoaderState.Ready;
  108311. _this._startAnimations();
  108312. });
  108313. resultPromise.then(function () {
  108314. _this._rootBabylonMesh.setEnabled(true);
  108315. BABYLON.Tools.SetImmediate(function () {
  108316. if (!_this._disposed) {
  108317. Promise.all(_this._completePromises).then(function () {
  108318. _this._state = BABYLON.GLTFLoaderState.Complete;
  108319. _this.onCompleteObservable.notifyObservers(_this);
  108320. _this.onCompleteObservable.clear();
  108321. _this._clear();
  108322. }).catch(function (error) {
  108323. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108324. _this._clear();
  108325. });
  108326. }
  108327. });
  108328. });
  108329. return resultPromise;
  108330. }).catch(function (error) {
  108331. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108332. _this._clear();
  108333. throw error;
  108334. });
  108335. };
  108336. GLTFLoader.prototype._loadExtensions = function () {
  108337. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108338. var name_1 = _a[_i];
  108339. var extension = GLTFLoader._Factories[name_1](this);
  108340. this._extensions[name_1] = extension;
  108341. this.onExtensionLoadedObservable.notifyObservers(extension);
  108342. }
  108343. this.onExtensionLoadedObservable.clear();
  108344. };
  108345. GLTFLoader.prototype._loadData = function (data) {
  108346. this._gltf = data.json;
  108347. this._setupData();
  108348. if (data.bin) {
  108349. var buffers = this._gltf.buffers;
  108350. if (buffers && buffers[0] && !buffers[0].uri) {
  108351. var binaryBuffer = buffers[0];
  108352. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108353. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108354. }
  108355. binaryBuffer._data = Promise.resolve(data.bin);
  108356. }
  108357. else {
  108358. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108359. }
  108360. }
  108361. };
  108362. GLTFLoader.prototype._setupData = function () {
  108363. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108364. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108365. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108366. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108367. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108368. GLTF2.ArrayItem.Assign(this._gltf.images);
  108369. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108370. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108371. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108372. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108373. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108374. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108375. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108376. if (this._gltf.nodes) {
  108377. var nodeParents = {};
  108378. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108379. var node = _a[_i];
  108380. if (node.children) {
  108381. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108382. var index = _c[_b];
  108383. nodeParents[index] = node._index;
  108384. }
  108385. }
  108386. }
  108387. var rootNode = this._createRootNode();
  108388. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108389. var node = _e[_d];
  108390. var parentIndex = nodeParents[node._index];
  108391. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108392. }
  108393. }
  108394. };
  108395. GLTFLoader.prototype._checkExtensions = function () {
  108396. if (this._gltf.extensionsRequired) {
  108397. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108398. var name_2 = _a[_i];
  108399. var extension = this._extensions[name_2];
  108400. if (!extension || !extension.enabled) {
  108401. throw new Error("Require extension " + name_2 + " is not available");
  108402. }
  108403. }
  108404. }
  108405. };
  108406. GLTFLoader.prototype._createRootNode = function () {
  108407. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108408. this._rootBabylonMesh.setEnabled(false);
  108409. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108410. switch (this.coordinateSystemMode) {
  108411. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108412. if (!this._babylonScene.useRightHandedSystem) {
  108413. rootNode.rotation = [0, 1, 0, 0];
  108414. rootNode.scale = [1, 1, -1];
  108415. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108416. }
  108417. break;
  108418. }
  108419. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108420. this._babylonScene.useRightHandedSystem = true;
  108421. break;
  108422. }
  108423. default: {
  108424. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108425. }
  108426. }
  108427. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108428. return rootNode;
  108429. };
  108430. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108431. var promises = new Array();
  108432. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108433. var node = nodes_1[_i];
  108434. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108435. }
  108436. promises.push(this._loadAnimationsAsync());
  108437. return Promise.all(promises).then(function () { });
  108438. };
  108439. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108440. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108441. if (promise) {
  108442. return promise;
  108443. }
  108444. var promises = new Array();
  108445. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108446. var index = _a[_i];
  108447. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108448. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108449. }
  108450. promises.push(this._loadAnimationsAsync());
  108451. return Promise.all(promises).then(function () { });
  108452. };
  108453. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  108454. if (node._babylonMesh) {
  108455. callback(node._babylonMesh);
  108456. }
  108457. if (node._primitiveBabylonMeshes) {
  108458. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108459. var babylonMesh = _a[_i];
  108460. callback(babylonMesh);
  108461. }
  108462. }
  108463. };
  108464. GLTFLoader.prototype._getMeshes = function () {
  108465. var meshes = new Array();
  108466. // Root mesh is always first.
  108467. meshes.push(this._rootBabylonMesh);
  108468. var nodes = this._gltf.nodes;
  108469. if (nodes) {
  108470. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108471. var node = nodes_2[_i];
  108472. this._forEachNodeMesh(node, function (mesh) {
  108473. meshes.push(mesh);
  108474. });
  108475. }
  108476. }
  108477. return meshes;
  108478. };
  108479. GLTFLoader.prototype._getSkeletons = function () {
  108480. var skeletons = new Array();
  108481. var skins = this._gltf.skins;
  108482. if (skins) {
  108483. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108484. var skin = skins_1[_i];
  108485. if (skin._babylonSkeleton) {
  108486. skeletons.push(skin._babylonSkeleton);
  108487. }
  108488. }
  108489. }
  108490. return skeletons;
  108491. };
  108492. GLTFLoader.prototype._startAnimations = function () {
  108493. var animations = this._gltf.animations;
  108494. if (!animations) {
  108495. return;
  108496. }
  108497. switch (this.animationStartMode) {
  108498. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108499. // do nothing
  108500. break;
  108501. }
  108502. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108503. var animation = animations[0];
  108504. animation._babylonAnimationGroup.start(true);
  108505. break;
  108506. }
  108507. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108508. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108509. var animation = animations_1[_i];
  108510. animation._babylonAnimationGroup.start(true);
  108511. }
  108512. break;
  108513. }
  108514. default: {
  108515. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108516. return;
  108517. }
  108518. }
  108519. };
  108520. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108521. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108522. if (promise) {
  108523. return promise;
  108524. }
  108525. if (node._babylonMesh) {
  108526. throw new Error(context + ": Invalid recursive node hierarchy");
  108527. }
  108528. var promises = new Array();
  108529. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108530. node._babylonMesh = babylonMesh;
  108531. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108532. node._babylonAnimationTargets.push(babylonMesh);
  108533. GLTFLoader._LoadTransform(node, babylonMesh);
  108534. if (node.mesh != undefined) {
  108535. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108536. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108537. }
  108538. if (node.children) {
  108539. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108540. var index = _a[_i];
  108541. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108542. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108543. }
  108544. }
  108545. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108546. return Promise.all(promises).then(function () { });
  108547. };
  108548. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108549. // TODO: instancing
  108550. var _this = this;
  108551. var promises = new Array();
  108552. var primitives = mesh.primitives;
  108553. if (!primitives || primitives.length === 0) {
  108554. throw new Error(context + ": Primitives are missing");
  108555. }
  108556. GLTF2.ArrayItem.Assign(primitives);
  108557. if (primitives.length === 1) {
  108558. var primitive = primitives[0];
  108559. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108560. }
  108561. else {
  108562. node._primitiveBabylonMeshes = [];
  108563. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108564. var primitive = primitives_1[_i];
  108565. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108566. node._primitiveBabylonMeshes.push(babylonMesh);
  108567. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108568. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108569. }
  108570. }
  108571. if (node.skin != undefined) {
  108572. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108573. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108574. }
  108575. return Promise.all(promises).then(function () {
  108576. _this._forEachNodeMesh(node, function (babylonMesh) {
  108577. babylonMesh._refreshBoundingInfo(true);
  108578. });
  108579. });
  108580. };
  108581. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108582. var _this = this;
  108583. var promises = new Array();
  108584. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108585. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  108586. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  108587. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  108588. }));
  108589. if (primitive.material == undefined) {
  108590. babylonMesh.material = this._getDefaultMaterial();
  108591. }
  108592. else {
  108593. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108594. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  108595. babylonMesh.material = babylonMaterial;
  108596. }));
  108597. }
  108598. return Promise.all(promises).then(function () { });
  108599. };
  108600. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108601. var _this = this;
  108602. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108603. if (promise) {
  108604. return promise;
  108605. }
  108606. var attributes = primitive.attributes;
  108607. if (!attributes) {
  108608. throw new Error(context + ": Attributes are missing");
  108609. }
  108610. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  108611. // TODO: handle other primitive modes
  108612. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  108613. }
  108614. var promises = new Array();
  108615. var babylonVertexData = new BABYLON.VertexData();
  108616. if (primitive.indices == undefined) {
  108617. var positionAccessorIndex = attributes["POSITION"];
  108618. if (positionAccessorIndex != undefined) {
  108619. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  108620. babylonVertexData.indices = new Uint32Array(accessor.count);
  108621. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  108622. babylonVertexData.indices[i] = i;
  108623. }
  108624. }
  108625. }
  108626. else {
  108627. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108628. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  108629. babylonVertexData.indices = data;
  108630. }));
  108631. }
  108632. var loadAttribute = function (attribute, kind) {
  108633. if (attributes[attribute] == undefined) {
  108634. return;
  108635. }
  108636. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108637. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108638. babylonMesh._delayInfo.push(kind);
  108639. }
  108640. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108641. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108642. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  108643. if (attribute === "COLOR_0") {
  108644. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  108645. babylonMesh.hasVertexAlpha = true;
  108646. if (accessor.type === "VEC3") {
  108647. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  108648. }
  108649. }
  108650. babylonVertexData.set(attributeData, kind);
  108651. }));
  108652. };
  108653. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108654. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108655. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108656. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108657. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108658. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108659. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108660. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108661. return Promise.all(promises).then(function () {
  108662. return babylonVertexData;
  108663. });
  108664. };
  108665. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108666. if (!primitive.targets) {
  108667. return;
  108668. }
  108669. if (node._numMorphTargets == undefined) {
  108670. node._numMorphTargets = primitive.targets.length;
  108671. }
  108672. else if (primitive.targets.length !== node._numMorphTargets) {
  108673. throw new Error(context + ": Primitives do not have the same number of targets");
  108674. }
  108675. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108676. for (var index = 0; index < primitive.targets.length; index++) {
  108677. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108678. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108679. // TODO: tell the target whether it has positions, normals, tangents
  108680. }
  108681. };
  108682. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108683. if (!primitive.targets) {
  108684. return Promise.resolve();
  108685. }
  108686. var promises = new Array();
  108687. var morphTargetManager = babylonMesh.morphTargetManager;
  108688. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108689. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108690. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108691. }
  108692. return Promise.all(promises).then(function () { });
  108693. };
  108694. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108695. var _this = this;
  108696. var promises = new Array();
  108697. var loadAttribute = function (attribute, setData) {
  108698. if (attributes[attribute] == undefined) {
  108699. return;
  108700. }
  108701. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108702. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108703. setData(data);
  108704. }));
  108705. };
  108706. loadAttribute("POSITION", function (data) {
  108707. if (babylonVertexData.positions) {
  108708. for (var i = 0; i < data.length; i++) {
  108709. data[i] += babylonVertexData.positions[i];
  108710. }
  108711. babylonMorphTarget.setPositions(data);
  108712. }
  108713. });
  108714. loadAttribute("NORMAL", function (data) {
  108715. if (babylonVertexData.normals) {
  108716. for (var i = 0; i < data.length; i++) {
  108717. data[i] += babylonVertexData.normals[i];
  108718. }
  108719. babylonMorphTarget.setNormals(data);
  108720. }
  108721. });
  108722. loadAttribute("TANGENT", function (data) {
  108723. if (babylonVertexData.tangents) {
  108724. // Tangent data for morph targets is stored as xyz delta.
  108725. // The vertexData.tangent is stored as xyzw.
  108726. // So we need to skip every fourth vertexData.tangent.
  108727. for (var i = 0, j = 0; i < data.length; i++) {
  108728. data[i] += babylonVertexData.tangents[j++];
  108729. if ((i + 1) % 3 == 0) {
  108730. j++;
  108731. }
  108732. }
  108733. babylonMorphTarget.setTangents(data);
  108734. }
  108735. });
  108736. return Promise.all(promises).then(function () { });
  108737. };
  108738. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108739. if (accessor.componentType == 5126 /* FLOAT */) {
  108740. return data;
  108741. }
  108742. var factor = 1;
  108743. if (accessor.normalized) {
  108744. switch (accessor.componentType) {
  108745. case 5121 /* UNSIGNED_BYTE */: {
  108746. factor = 1 / 255;
  108747. break;
  108748. }
  108749. case 5123 /* UNSIGNED_SHORT */: {
  108750. factor = 1 / 65535;
  108751. break;
  108752. }
  108753. default: {
  108754. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  108755. }
  108756. }
  108757. }
  108758. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108759. for (var i = 0; i < result.length; i++) {
  108760. result[i] = data[i] * factor;
  108761. }
  108762. return result;
  108763. };
  108764. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108765. var result = new Float32Array(data.length / 3 * 4);
  108766. var offset = 0;
  108767. for (var i = 0; i < result.length; i++) {
  108768. if ((i + 1) % 4 === 0) {
  108769. result[i] = 1;
  108770. }
  108771. else {
  108772. result[i] = data[offset++];
  108773. }
  108774. }
  108775. return result;
  108776. };
  108777. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108778. var position = BABYLON.Vector3.Zero();
  108779. var rotation = BABYLON.Quaternion.Identity();
  108780. var scaling = BABYLON.Vector3.One();
  108781. if (node.matrix) {
  108782. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108783. matrix.decompose(scaling, rotation, position);
  108784. }
  108785. else {
  108786. if (node.translation)
  108787. position = BABYLON.Vector3.FromArray(node.translation);
  108788. if (node.rotation)
  108789. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108790. if (node.scale)
  108791. scaling = BABYLON.Vector3.FromArray(node.scale);
  108792. }
  108793. babylonNode.position = position;
  108794. babylonNode.rotationQuaternion = rotation;
  108795. babylonNode.scaling = scaling;
  108796. };
  108797. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108798. var _this = this;
  108799. var assignSkeleton = function () {
  108800. _this._forEachNodeMesh(node, function (babylonMesh) {
  108801. babylonMesh.skeleton = skin._babylonSkeleton;
  108802. });
  108803. node._babylonMesh.parent = _this._rootBabylonMesh;
  108804. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108805. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108806. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108807. };
  108808. if (skin._loaded) {
  108809. return skin._loaded.then(function () {
  108810. assignSkeleton();
  108811. });
  108812. }
  108813. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108814. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108815. var skeletonId = "skeleton" + skin._index;
  108816. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108817. skin._babylonSkeleton = babylonSkeleton;
  108818. _this._loadBones(context, skin, inverseBindMatricesData);
  108819. assignSkeleton();
  108820. }));
  108821. };
  108822. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108823. if (skin.inverseBindMatrices == undefined) {
  108824. return Promise.resolve(null);
  108825. }
  108826. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108827. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108828. return data;
  108829. });
  108830. };
  108831. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108832. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108833. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108834. node._babylonAnimationTargets.push(babylonBone);
  108835. return babylonBone;
  108836. };
  108837. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108838. var babylonBones = {};
  108839. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108840. var index = _a[_i];
  108841. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108842. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108843. }
  108844. };
  108845. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108846. var babylonBone = babylonBones[node._index];
  108847. if (babylonBone) {
  108848. return babylonBone;
  108849. }
  108850. var boneIndex = skin.joints.indexOf(node._index);
  108851. var baseMatrix = BABYLON.Matrix.Identity();
  108852. if (inverseBindMatricesData && boneIndex !== -1) {
  108853. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108854. baseMatrix.invertToRef(baseMatrix);
  108855. }
  108856. var babylonParentBone = null;
  108857. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108858. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108859. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108860. }
  108861. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108862. babylonBones[node._index] = babylonBone;
  108863. return babylonBone;
  108864. };
  108865. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108866. return node.matrix ?
  108867. BABYLON.Matrix.FromArray(node.matrix) :
  108868. 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());
  108869. };
  108870. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108871. var animations = this._gltf.animations;
  108872. if (!animations) {
  108873. return Promise.resolve();
  108874. }
  108875. var promises = new Array();
  108876. for (var index = 0; index < animations.length; index++) {
  108877. var animation = animations[index];
  108878. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108879. }
  108880. return Promise.all(promises).then(function () { });
  108881. };
  108882. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108883. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108884. animation._babylonAnimationGroup = babylonAnimationGroup;
  108885. var promises = new Array();
  108886. GLTF2.ArrayItem.Assign(animation.channels);
  108887. GLTF2.ArrayItem.Assign(animation.samplers);
  108888. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108889. var channel = _a[_i];
  108890. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108891. }
  108892. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  108893. return Promise.all(promises).then(function () {
  108894. babylonAnimationGroup.normalize();
  108895. });
  108896. };
  108897. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108898. var _this = this;
  108899. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108900. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  108901. return Promise.resolve();
  108902. }
  108903. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108904. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108905. var targetPath;
  108906. var animationType;
  108907. switch (channel.target.path) {
  108908. case "translation" /* TRANSLATION */: {
  108909. targetPath = "position";
  108910. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108911. break;
  108912. }
  108913. case "rotation" /* ROTATION */: {
  108914. targetPath = "rotationQuaternion";
  108915. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108916. break;
  108917. }
  108918. case "scale" /* SCALE */: {
  108919. targetPath = "scaling";
  108920. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108921. break;
  108922. }
  108923. case "weights" /* WEIGHTS */: {
  108924. targetPath = "influence";
  108925. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108926. break;
  108927. }
  108928. default: {
  108929. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  108930. }
  108931. }
  108932. var outputBufferOffset = 0;
  108933. var getNextOutputValue;
  108934. switch (targetPath) {
  108935. case "position": {
  108936. getNextOutputValue = function () {
  108937. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108938. outputBufferOffset += 3;
  108939. return value;
  108940. };
  108941. break;
  108942. }
  108943. case "rotationQuaternion": {
  108944. getNextOutputValue = function () {
  108945. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108946. outputBufferOffset += 4;
  108947. return value;
  108948. };
  108949. break;
  108950. }
  108951. case "scaling": {
  108952. getNextOutputValue = function () {
  108953. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108954. outputBufferOffset += 3;
  108955. return value;
  108956. };
  108957. break;
  108958. }
  108959. case "influence": {
  108960. getNextOutputValue = function () {
  108961. var value = new Array(targetNode._numMorphTargets);
  108962. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108963. value[i] = data.output[outputBufferOffset++];
  108964. }
  108965. return value;
  108966. };
  108967. break;
  108968. }
  108969. }
  108970. var getNextKey;
  108971. switch (data.interpolation) {
  108972. case "STEP" /* STEP */: {
  108973. getNextKey = function (frameIndex) { return ({
  108974. frame: data.input[frameIndex],
  108975. value: getNextOutputValue(),
  108976. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  108977. }); };
  108978. break;
  108979. }
  108980. case "LINEAR" /* LINEAR */: {
  108981. getNextKey = function (frameIndex) { return ({
  108982. frame: data.input[frameIndex],
  108983. value: getNextOutputValue()
  108984. }); };
  108985. break;
  108986. }
  108987. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108988. getNextKey = function (frameIndex) { return ({
  108989. frame: data.input[frameIndex],
  108990. inTangent: getNextOutputValue(),
  108991. value: getNextOutputValue(),
  108992. outTangent: getNextOutputValue()
  108993. }); };
  108994. break;
  108995. }
  108996. }
  108997. var keys;
  108998. if (data.input.length === 1) {
  108999. var key = getNextKey(0);
  109000. keys = [
  109001. { frame: key.frame, value: key.value },
  109002. { frame: key.frame + 1, value: key.value }
  109003. ];
  109004. }
  109005. else {
  109006. keys = new Array(data.input.length);
  109007. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109008. keys[frameIndex] = getNextKey(frameIndex);
  109009. }
  109010. }
  109011. if (targetPath === "influence") {
  109012. var _loop_1 = function (targetIndex) {
  109013. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109014. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109015. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109016. frame: key.frame,
  109017. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109018. value: key.value[targetIndex],
  109019. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109020. }); }));
  109021. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  109022. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109023. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109024. });
  109025. };
  109026. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109027. _loop_1(targetIndex);
  109028. }
  109029. }
  109030. else {
  109031. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109032. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109033. babylonAnimation.setKeys(keys);
  109034. if (targetNode._babylonAnimationTargets) {
  109035. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109036. var target = _a[_i];
  109037. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109038. }
  109039. }
  109040. }
  109041. });
  109042. };
  109043. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109044. if (sampler._data) {
  109045. return sampler._data;
  109046. }
  109047. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109048. switch (interpolation) {
  109049. case "STEP" /* STEP */:
  109050. case "LINEAR" /* LINEAR */:
  109051. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109052. break;
  109053. }
  109054. default: {
  109055. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109056. }
  109057. }
  109058. var inputData;
  109059. var outputData;
  109060. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109061. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109062. sampler._data = Promise.all([
  109063. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109064. inputData = data;
  109065. }),
  109066. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109067. outputData = data;
  109068. })
  109069. ]).then(function () {
  109070. return {
  109071. input: inputData,
  109072. interpolation: interpolation,
  109073. output: outputData,
  109074. };
  109075. });
  109076. return sampler._data;
  109077. };
  109078. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109079. if (buffer._data) {
  109080. return buffer._data;
  109081. }
  109082. if (!buffer.uri) {
  109083. throw new Error(context + ": Uri is missing");
  109084. }
  109085. buffer._data = this._loadUriAsync(context, buffer.uri);
  109086. return buffer._data;
  109087. };
  109088. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109089. if (bufferView._data) {
  109090. return bufferView._data;
  109091. }
  109092. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109093. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109094. try {
  109095. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109096. }
  109097. catch (e) {
  109098. throw new Error(context + ": " + e.message);
  109099. }
  109100. });
  109101. return bufferView._data;
  109102. };
  109103. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109104. var _this = this;
  109105. if (accessor.sparse) {
  109106. throw new Error(context + ": Sparse accessors are not currently supported");
  109107. }
  109108. if (accessor._data) {
  109109. return accessor._data;
  109110. }
  109111. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109112. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109113. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109114. var byteOffset = accessor.byteOffset || 0;
  109115. var byteStride = bufferView.byteStride;
  109116. if (byteStride === 0) {
  109117. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109118. }
  109119. try {
  109120. switch (accessor.componentType) {
  109121. case 5120 /* BYTE */: {
  109122. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109123. }
  109124. case 5121 /* UNSIGNED_BYTE */: {
  109125. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109126. }
  109127. case 5122 /* SHORT */: {
  109128. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109129. }
  109130. case 5123 /* UNSIGNED_SHORT */: {
  109131. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109132. }
  109133. case 5125 /* UNSIGNED_INT */: {
  109134. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109135. }
  109136. case 5126 /* FLOAT */: {
  109137. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109138. }
  109139. default: {
  109140. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109141. }
  109142. }
  109143. }
  109144. catch (e) {
  109145. throw new Error(context + ": " + e.messsage);
  109146. }
  109147. });
  109148. return accessor._data;
  109149. };
  109150. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109151. byteOffset += data.byteOffset;
  109152. var targetLength = count * numComponents;
  109153. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109154. return new typedArray(data.buffer, byteOffset, targetLength);
  109155. }
  109156. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109157. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109158. var targetBuffer = new typedArray(targetLength);
  109159. var sourceIndex = 0;
  109160. var targetIndex = 0;
  109161. while (targetIndex < targetLength) {
  109162. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109163. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109164. targetIndex++;
  109165. }
  109166. sourceIndex += elementStride;
  109167. }
  109168. return targetBuffer;
  109169. };
  109170. GLTFLoader.prototype._getDefaultMaterial = function () {
  109171. var id = "__gltf_default";
  109172. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109173. if (!babylonMaterial) {
  109174. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109175. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109176. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109177. babylonMaterial.metallic = 1;
  109178. babylonMaterial.roughness = 1;
  109179. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109180. }
  109181. return babylonMaterial;
  109182. };
  109183. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109184. var promises = new Array();
  109185. var babylonMaterial = material._babylonMaterial;
  109186. // Ensure metallic workflow
  109187. babylonMaterial.metallic = 1;
  109188. babylonMaterial.roughness = 1;
  109189. var properties = material.pbrMetallicRoughness;
  109190. if (properties) {
  109191. if (properties.baseColorFactor) {
  109192. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109193. babylonMaterial.alpha = properties.baseColorFactor[3];
  109194. }
  109195. else {
  109196. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109197. }
  109198. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109199. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109200. if (properties.baseColorTexture) {
  109201. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109202. babylonMaterial.albedoTexture = texture;
  109203. }));
  109204. }
  109205. if (properties.metallicRoughnessTexture) {
  109206. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109207. babylonMaterial.metallicTexture = texture;
  109208. }));
  109209. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109210. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109211. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109212. }
  109213. }
  109214. this._loadMaterialAlphaProperties(context, material);
  109215. return Promise.all(promises).then(function () { });
  109216. };
  109217. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109218. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109219. if (promise) {
  109220. return promise;
  109221. }
  109222. material._babylonMeshes = material._babylonMeshes || [];
  109223. material._babylonMeshes.push(babylonMesh);
  109224. if (!material._loaded) {
  109225. var promises = new Array();
  109226. var babylonMaterial = this._createMaterial(material);
  109227. material._babylonMaterial = babylonMaterial;
  109228. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109229. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109230. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109231. material._loaded = Promise.all(promises).then(function () { });
  109232. }
  109233. assign(material._babylonMaterial);
  109234. return material._loaded;
  109235. };
  109236. GLTFLoader.prototype._createMaterial = function (material) {
  109237. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109238. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109239. return babylonMaterial;
  109240. };
  109241. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109242. var promises = new Array();
  109243. var babylonMaterial = material._babylonMaterial;
  109244. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109245. if (material.doubleSided) {
  109246. babylonMaterial.backFaceCulling = false;
  109247. babylonMaterial.twoSidedLighting = true;
  109248. }
  109249. if (material.normalTexture) {
  109250. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109251. babylonMaterial.bumpTexture = texture;
  109252. }));
  109253. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109254. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109255. if (material.normalTexture.scale != undefined) {
  109256. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109257. }
  109258. }
  109259. if (material.occlusionTexture) {
  109260. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109261. babylonMaterial.ambientTexture = texture;
  109262. }));
  109263. babylonMaterial.useAmbientInGrayScale = true;
  109264. if (material.occlusionTexture.strength != undefined) {
  109265. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109266. }
  109267. }
  109268. if (material.emissiveTexture) {
  109269. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109270. babylonMaterial.emissiveTexture = texture;
  109271. }));
  109272. }
  109273. return Promise.all(promises).then(function () { });
  109274. };
  109275. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109276. var babylonMaterial = material._babylonMaterial;
  109277. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109278. switch (alphaMode) {
  109279. case "OPAQUE" /* OPAQUE */: {
  109280. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109281. break;
  109282. }
  109283. case "MASK" /* MASK */: {
  109284. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109285. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109286. if (babylonMaterial.alpha) {
  109287. if (babylonMaterial.alpha === 0) {
  109288. babylonMaterial.alphaCutOff = 1;
  109289. }
  109290. else {
  109291. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109292. }
  109293. babylonMaterial.alpha = 1;
  109294. }
  109295. if (babylonMaterial.albedoTexture) {
  109296. babylonMaterial.albedoTexture.hasAlpha = true;
  109297. }
  109298. break;
  109299. }
  109300. case "BLEND" /* BLEND */: {
  109301. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109302. if (babylonMaterial.albedoTexture) {
  109303. babylonMaterial.albedoTexture.hasAlpha = true;
  109304. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109305. }
  109306. break;
  109307. }
  109308. default: {
  109309. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109310. }
  109311. }
  109312. };
  109313. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109314. var _this = this;
  109315. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109316. context = "#/textures/" + textureInfo.index;
  109317. var promises = new Array();
  109318. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109319. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109320. var deferred = new BABYLON.Deferred();
  109321. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109322. if (!_this._disposed) {
  109323. deferred.resolve();
  109324. }
  109325. }, function (message, exception) {
  109326. if (!_this._disposed) {
  109327. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109328. }
  109329. });
  109330. promises.push(deferred.promise);
  109331. babylonTexture.name = texture.name || "texture" + texture._index;
  109332. babylonTexture.wrapU = samplerData.wrapU;
  109333. babylonTexture.wrapV = samplerData.wrapV;
  109334. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109335. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109336. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109337. babylonTexture.updateURL(objectURL);
  109338. }));
  109339. assign(babylonTexture);
  109340. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109341. return Promise.all(promises).then(function () { });
  109342. };
  109343. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109344. if (!sampler._data) {
  109345. sampler._data = {
  109346. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109347. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109348. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109349. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109350. };
  109351. }
  109352. ;
  109353. return sampler._data;
  109354. };
  109355. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109356. if (image._objectURL) {
  109357. return image._objectURL;
  109358. }
  109359. var promise;
  109360. if (image.uri) {
  109361. promise = this._loadUriAsync(context, image.uri);
  109362. }
  109363. else {
  109364. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109365. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109366. }
  109367. image._objectURL = promise.then(function (data) {
  109368. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109369. });
  109370. return image._objectURL;
  109371. };
  109372. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109373. var _this = this;
  109374. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109375. if (promise) {
  109376. return promise;
  109377. }
  109378. if (!GLTFLoader._ValidateUri(uri)) {
  109379. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109380. }
  109381. if (BABYLON.Tools.IsBase64(uri)) {
  109382. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109383. }
  109384. return new Promise(function (resolve, reject) {
  109385. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109386. if (!_this._disposed) {
  109387. resolve(new Uint8Array(data));
  109388. }
  109389. }, function (event) {
  109390. if (!_this._disposed) {
  109391. try {
  109392. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109393. request._lengthComputable = event.lengthComputable;
  109394. request._loaded = event.loaded;
  109395. request._total = event.total;
  109396. _this._onProgress();
  109397. }
  109398. }
  109399. catch (e) {
  109400. reject(e);
  109401. }
  109402. }
  109403. }, _this._babylonScene.database, true, function (request, exception) {
  109404. if (!_this._disposed) {
  109405. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109406. }
  109407. });
  109408. _this._requests.push(request);
  109409. });
  109410. };
  109411. GLTFLoader.prototype._onProgress = function () {
  109412. if (!this._progressCallback) {
  109413. return;
  109414. }
  109415. var lengthComputable = true;
  109416. var loaded = 0;
  109417. var total = 0;
  109418. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109419. var request = _a[_i];
  109420. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109421. return;
  109422. }
  109423. lengthComputable = lengthComputable && request._lengthComputable;
  109424. loaded += request._loaded;
  109425. total += request._total;
  109426. }
  109427. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109428. };
  109429. GLTFLoader._GetProperty = function (context, array, index) {
  109430. if (!array || index == undefined || !array[index]) {
  109431. throw new Error(context + ": Failed to find index (" + index + ")");
  109432. }
  109433. return array[index];
  109434. };
  109435. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109436. // Set defaults if undefined
  109437. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109438. switch (mode) {
  109439. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109440. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109441. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109442. default:
  109443. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109444. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109445. }
  109446. };
  109447. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109448. // Set defaults if undefined
  109449. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109450. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109451. if (magFilter === 9729 /* LINEAR */) {
  109452. switch (minFilter) {
  109453. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109454. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109455. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109456. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109457. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109458. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109459. default:
  109460. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109461. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109462. }
  109463. }
  109464. else {
  109465. if (magFilter !== 9728 /* NEAREST */) {
  109466. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109467. }
  109468. switch (minFilter) {
  109469. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109470. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109471. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109472. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109473. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109474. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109475. default:
  109476. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109477. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109478. }
  109479. }
  109480. };
  109481. GLTFLoader._GetNumComponents = function (context, type) {
  109482. switch (type) {
  109483. case "SCALAR": return 1;
  109484. case "VEC2": return 2;
  109485. case "VEC3": return 3;
  109486. case "VEC4": return 4;
  109487. case "MAT2": return 4;
  109488. case "MAT3": return 9;
  109489. case "MAT4": return 16;
  109490. }
  109491. throw new Error(context + ": Invalid type (" + type + ")");
  109492. };
  109493. GLTFLoader._ValidateUri = function (uri) {
  109494. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109495. };
  109496. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109497. var promises = new Array();
  109498. if (this._gltf.materials) {
  109499. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109500. var material = _a[_i];
  109501. var babylonMaterial = material._babylonMaterial;
  109502. var babylonMeshes = material._babylonMeshes;
  109503. if (babylonMaterial && babylonMeshes) {
  109504. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109505. var babylonMesh = babylonMeshes_1[_b];
  109506. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109507. if (this.useClipPlane) {
  109508. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109509. }
  109510. }
  109511. }
  109512. }
  109513. }
  109514. return Promise.all(promises).then(function () { });
  109515. };
  109516. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109517. var promises = new Array();
  109518. var lights = this._babylonScene.lights;
  109519. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109520. var light = lights_1[_i];
  109521. var generator = light.getShadowGenerator();
  109522. if (generator) {
  109523. promises.push(generator.forceCompilationAsync());
  109524. }
  109525. }
  109526. return Promise.all(promises).then(function () { });
  109527. };
  109528. GLTFLoader.prototype._clear = function () {
  109529. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109530. var request = _a[_i];
  109531. request.abort();
  109532. }
  109533. this._requests.length = 0;
  109534. if (this._gltf && this._gltf.images) {
  109535. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109536. var image = _c[_b];
  109537. if (image._objectURL) {
  109538. image._objectURL.then(function (value) {
  109539. URL.revokeObjectURL(value);
  109540. });
  109541. image._objectURL = undefined;
  109542. }
  109543. }
  109544. }
  109545. delete this._gltf;
  109546. delete this._babylonScene;
  109547. this._completePromises.length = 0;
  109548. for (var name_3 in this._extensions) {
  109549. this._extensions[name_3].dispose();
  109550. }
  109551. this._extensions = {};
  109552. delete this._rootBabylonMesh;
  109553. delete this._progressCallback;
  109554. this.onMeshLoadedObservable.clear();
  109555. this.onTextureLoadedObservable.clear();
  109556. this.onMaterialLoadedObservable.clear();
  109557. };
  109558. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109559. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109560. var name_4 = _a[_i];
  109561. var extension = this._extensions[name_4];
  109562. if (extension.enabled) {
  109563. var promise = actionAsync(extension);
  109564. if (promise) {
  109565. return promise;
  109566. }
  109567. }
  109568. }
  109569. return null;
  109570. };
  109571. GLTFLoader._Names = new Array();
  109572. GLTFLoader._Factories = {};
  109573. return GLTFLoader;
  109574. }());
  109575. GLTF2.GLTFLoader = GLTFLoader;
  109576. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  109577. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109578. })(BABYLON || (BABYLON = {}));
  109579. //# sourceMappingURL=babylon.glTFLoader.js.map
  109580. var BABYLON;
  109581. (function (BABYLON) {
  109582. var GLTF2;
  109583. (function (GLTF2) {
  109584. var GLTFLoaderExtension = /** @class */ (function () {
  109585. function GLTFLoaderExtension(loader) {
  109586. this.enabled = true;
  109587. this._loader = loader;
  109588. }
  109589. GLTFLoaderExtension.prototype.dispose = function () {
  109590. delete this._loader;
  109591. };
  109592. // #region Overridable Methods
  109593. /** Override this method to modify the default behavior for loading scenes. */
  109594. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109595. /** Override this method to modify the default behavior for loading nodes. */
  109596. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109597. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  109598. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109599. /** Override this method to modify the default behavior for loading materials. */
  109600. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  109601. /** Override this method to modify the default behavior for loading uris. */
  109602. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109603. // #endregion
  109604. /** Helper method called by a loader extension to load an glTF extension. */
  109605. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109606. if (!property.extensions) {
  109607. return null;
  109608. }
  109609. var extensions = property.extensions;
  109610. var extension = extensions[this.name];
  109611. if (!extension) {
  109612. return null;
  109613. }
  109614. // Clear out the extension before executing the action to avoid recursing into the same property.
  109615. delete extensions[this.name];
  109616. try {
  109617. return actionAsync(context + "/extensions/" + this.name, extension);
  109618. }
  109619. finally {
  109620. // Restore the extension after executing the action.
  109621. extensions[this.name] = extension;
  109622. }
  109623. };
  109624. /** Helper method called by the loader to allow extensions to override loading scenes. */
  109625. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109626. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109627. };
  109628. /** Helper method called by the loader to allow extensions to override loading nodes. */
  109629. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109630. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109631. };
  109632. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  109633. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109634. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109635. };
  109636. /** Helper method called by the loader to allow extensions to override loading materials. */
  109637. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  109638. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  109639. };
  109640. /** Helper method called by the loader to allow extensions to override loading uris. */
  109641. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109642. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109643. };
  109644. return GLTFLoaderExtension;
  109645. }());
  109646. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109647. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109648. })(BABYLON || (BABYLON = {}));
  109649. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109650. var BABYLON;
  109651. (function (BABYLON) {
  109652. var GLTF2;
  109653. (function (GLTF2) {
  109654. var Extensions;
  109655. (function (Extensions) {
  109656. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  109657. var NAME = "MSFT_lod";
  109658. var MSFT_lod = /** @class */ (function (_super) {
  109659. __extends(MSFT_lod, _super);
  109660. function MSFT_lod() {
  109661. var _this = _super !== null && _super.apply(this, arguments) || this;
  109662. _this.name = NAME;
  109663. /**
  109664. * Maximum number of LODs to load, starting from the lowest LOD.
  109665. */
  109666. _this.maxLODsToLoad = Number.MAX_VALUE;
  109667. _this._loadingNodeLOD = null;
  109668. _this._loadNodeSignals = {};
  109669. _this._loadingMaterialLOD = null;
  109670. _this._loadMaterialSignals = {};
  109671. return _this;
  109672. }
  109673. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109674. var _this = this;
  109675. return this._loadExtensionAsync(context, node, function (context, extension) {
  109676. var firstPromise;
  109677. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  109678. var _loop_1 = function (indexLOD) {
  109679. var nodeLOD = nodeLODs[indexLOD];
  109680. if (indexLOD !== 0) {
  109681. _this._loadingNodeLOD = nodeLOD;
  109682. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109683. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109684. }
  109685. }
  109686. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109687. if (indexLOD !== 0) {
  109688. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109689. if (previousNodeLOD._babylonMesh) {
  109690. previousNodeLOD._babylonMesh.dispose();
  109691. delete previousNodeLOD._babylonMesh;
  109692. }
  109693. }
  109694. if (indexLOD !== nodeLODs.length - 1) {
  109695. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109696. if (_this._loadNodeSignals[nodeIndex]) {
  109697. _this._loadNodeSignals[nodeIndex].resolve();
  109698. delete _this._loadNodeSignals[nodeIndex];
  109699. }
  109700. }
  109701. });
  109702. if (indexLOD === 0) {
  109703. firstPromise = promise;
  109704. }
  109705. else {
  109706. _this._loader._completePromises.push(promise);
  109707. _this._loadingNodeLOD = null;
  109708. }
  109709. };
  109710. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109711. _loop_1(indexLOD);
  109712. }
  109713. return firstPromise;
  109714. });
  109715. };
  109716. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109717. var _this = this;
  109718. // Don't load material LODs if already loading a node LOD.
  109719. if (this._loadingNodeLOD) {
  109720. return null;
  109721. }
  109722. return this._loadExtensionAsync(context, material, function (context, extension) {
  109723. var firstPromise;
  109724. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109725. var _loop_2 = function (indexLOD) {
  109726. var materialLOD = materialLODs[indexLOD];
  109727. if (indexLOD !== 0) {
  109728. _this._loadingMaterialLOD = materialLOD;
  109729. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109730. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109731. }
  109732. }
  109733. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  109734. if (indexLOD !== 0) {
  109735. assign(materialLOD._babylonMaterial);
  109736. var previousMaterialLOD = materialLODs[indexLOD - 1];
  109737. if (previousMaterialLOD._babylonMaterial) {
  109738. previousMaterialLOD._babylonMaterial.dispose();
  109739. delete previousMaterialLOD._babylonMaterial;
  109740. }
  109741. }
  109742. if (indexLOD !== materialLODs.length - 1) {
  109743. var materialIndex = materialLODs[indexLOD + 1]._index;
  109744. if (_this._loadMaterialSignals[materialIndex]) {
  109745. _this._loadMaterialSignals[materialIndex].resolve();
  109746. delete _this._loadMaterialSignals[materialIndex];
  109747. }
  109748. }
  109749. });
  109750. if (indexLOD === 0) {
  109751. firstPromise = promise;
  109752. }
  109753. else {
  109754. _this._loader._completePromises.push(promise);
  109755. _this._loadingMaterialLOD = null;
  109756. }
  109757. };
  109758. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109759. _loop_2(indexLOD);
  109760. }
  109761. return firstPromise;
  109762. });
  109763. };
  109764. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109765. var _this = this;
  109766. // Defer the loading of uris if loading a material or node LOD.
  109767. if (this._loadingMaterialLOD) {
  109768. var index = this._loadingMaterialLOD._index;
  109769. return this._loadMaterialSignals[index].promise.then(function () {
  109770. return _this._loader._loadUriAsync(context, uri);
  109771. });
  109772. }
  109773. else if (this._loadingNodeLOD) {
  109774. var index = this._loadingNodeLOD._index;
  109775. return this._loadNodeSignals[index].promise.then(function () {
  109776. return _this._loader._loadUriAsync(context, uri);
  109777. });
  109778. }
  109779. return null;
  109780. };
  109781. /**
  109782. * Gets an array of LOD properties from lowest to highest.
  109783. */
  109784. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109785. if (this.maxLODsToLoad <= 0) {
  109786. throw new Error("maxLODsToLoad must be greater than zero");
  109787. }
  109788. var properties = new Array();
  109789. for (var i = ids.length - 1; i >= 0; i--) {
  109790. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109791. if (properties.length === this.maxLODsToLoad) {
  109792. return properties;
  109793. }
  109794. }
  109795. properties.push(property);
  109796. return properties;
  109797. };
  109798. return MSFT_lod;
  109799. }(GLTF2.GLTFLoaderExtension));
  109800. Extensions.MSFT_lod = MSFT_lod;
  109801. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109802. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109803. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109804. })(BABYLON || (BABYLON = {}));
  109805. //# sourceMappingURL=MSFT_lod.js.map
  109806. var BABYLON;
  109807. (function (BABYLON) {
  109808. var GLTF2;
  109809. (function (GLTF2) {
  109810. var Extensions;
  109811. (function (Extensions) {
  109812. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109813. var NAME = "KHR_draco_mesh_compression";
  109814. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109815. __extends(KHR_draco_mesh_compression, _super);
  109816. function KHR_draco_mesh_compression(loader) {
  109817. var _this = _super.call(this, loader) || this;
  109818. _this.name = NAME;
  109819. _this._dracoCompression = null;
  109820. // Disable extension if decoder is not available.
  109821. if (!BABYLON.DracoCompression.DecoderUrl) {
  109822. _this.enabled = false;
  109823. }
  109824. return _this;
  109825. }
  109826. KHR_draco_mesh_compression.prototype.dispose = function () {
  109827. if (this._dracoCompression) {
  109828. this._dracoCompression.dispose();
  109829. }
  109830. _super.prototype.dispose.call(this);
  109831. };
  109832. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109833. var _this = this;
  109834. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109835. if (primitive.mode != undefined) {
  109836. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109837. primitive.mode !== 4 /* TRIANGLES */) {
  109838. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109839. }
  109840. // TODO: handle triangle strips
  109841. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109842. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109843. }
  109844. }
  109845. var attributes = {};
  109846. var loadAttribute = function (name, kind) {
  109847. var uniqueId = extension.attributes[name];
  109848. if (uniqueId == undefined) {
  109849. return;
  109850. }
  109851. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109852. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109853. babylonMesh._delayInfo.push(kind);
  109854. }
  109855. attributes[kind] = uniqueId;
  109856. };
  109857. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109858. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109859. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109860. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109861. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109862. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109863. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109864. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109865. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109866. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109867. try {
  109868. if (!_this._dracoCompression) {
  109869. _this._dracoCompression = new BABYLON.DracoCompression();
  109870. }
  109871. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  109872. }
  109873. catch (e) {
  109874. throw new Error(context + ": " + e.message);
  109875. }
  109876. });
  109877. });
  109878. };
  109879. return KHR_draco_mesh_compression;
  109880. }(GLTF2.GLTFLoaderExtension));
  109881. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109882. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109883. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109884. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109885. })(BABYLON || (BABYLON = {}));
  109886. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109887. var BABYLON;
  109888. (function (BABYLON) {
  109889. var GLTF2;
  109890. (function (GLTF2) {
  109891. var Extensions;
  109892. (function (Extensions) {
  109893. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  109894. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109895. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109896. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109897. function KHR_materials_pbrSpecularGlossiness() {
  109898. var _this = _super !== null && _super.apply(this, arguments) || this;
  109899. _this.name = NAME;
  109900. return _this;
  109901. }
  109902. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109903. var _this = this;
  109904. return this._loadExtensionAsync(context, material, function (context, extension) {
  109905. material._babylonMeshes = material._babylonMeshes || [];
  109906. material._babylonMeshes.push(babylonMesh);
  109907. if (!material._loaded) {
  109908. var promises = new Array();
  109909. var babylonMaterial = _this._loader._createMaterial(material);
  109910. material._babylonMaterial = babylonMaterial;
  109911. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  109912. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  109913. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109914. material._loaded = Promise.all(promises).then(function () { });
  109915. }
  109916. assign(material._babylonMaterial);
  109917. return material._loaded;
  109918. });
  109919. };
  109920. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  109921. var promises = new Array();
  109922. var babylonMaterial = material._babylonMaterial;
  109923. if (properties.diffuseFactor) {
  109924. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109925. babylonMaterial.alpha = properties.diffuseFactor[3];
  109926. }
  109927. else {
  109928. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109929. }
  109930. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109931. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109932. if (properties.diffuseTexture) {
  109933. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109934. babylonMaterial.albedoTexture = texture;
  109935. }));
  109936. }
  109937. if (properties.specularGlossinessTexture) {
  109938. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109939. babylonMaterial.reflectivityTexture = texture;
  109940. }));
  109941. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109942. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109943. }
  109944. this._loader._loadMaterialAlphaProperties(context, material);
  109945. return Promise.all(promises).then(function () { });
  109946. };
  109947. return KHR_materials_pbrSpecularGlossiness;
  109948. }(GLTF2.GLTFLoaderExtension));
  109949. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109950. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109951. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109952. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109953. })(BABYLON || (BABYLON = {}));
  109954. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109955. var BABYLON;
  109956. (function (BABYLON) {
  109957. var GLTF2;
  109958. (function (GLTF2) {
  109959. var Extensions;
  109960. (function (Extensions) {
  109961. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  109962. var NAME = "KHR_lights";
  109963. var LightType;
  109964. (function (LightType) {
  109965. LightType["AMBIENT"] = "ambient";
  109966. LightType["DIRECTIONAL"] = "directional";
  109967. LightType["POINT"] = "point";
  109968. LightType["SPOT"] = "spot";
  109969. })(LightType || (LightType = {}));
  109970. var KHR_lights = /** @class */ (function (_super) {
  109971. __extends(KHR_lights, _super);
  109972. function KHR_lights() {
  109973. var _this = _super !== null && _super.apply(this, arguments) || this;
  109974. _this.name = NAME;
  109975. return _this;
  109976. }
  109977. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109978. var _this = this;
  109979. return this._loadExtensionAsync(context, scene, function (context, extension) {
  109980. var promise = _this._loader._loadSceneAsync(context, scene);
  109981. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109982. if (light.type !== LightType.AMBIENT) {
  109983. throw new Error(context + ": Only ambient lights are allowed on a scene");
  109984. }
  109985. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109986. return promise;
  109987. });
  109988. };
  109989. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109990. var _this = this;
  109991. return this._loadExtensionAsync(context, node, function (context, extension) {
  109992. var promise = _this._loader._loadNodeAsync(context, node);
  109993. var babylonLight;
  109994. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109995. var name = node._babylonMesh.name;
  109996. switch (light.type) {
  109997. case LightType.AMBIENT: {
  109998. throw new Error(context + ": Ambient lights are not allowed on a node");
  109999. }
  110000. case LightType.DIRECTIONAL: {
  110001. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110002. break;
  110003. }
  110004. case LightType.POINT: {
  110005. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110006. break;
  110007. }
  110008. case LightType.SPOT: {
  110009. var spotLight = light;
  110010. // TODO: support inner and outer cone angles
  110011. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110012. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110013. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110014. break;
  110015. }
  110016. default: {
  110017. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110018. }
  110019. }
  110020. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110021. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110022. babylonLight.parent = node._babylonMesh;
  110023. return promise;
  110024. });
  110025. };
  110026. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110027. get: function () {
  110028. var extensions = this._loader._gltf.extensions;
  110029. if (!extensions || !extensions[this.name]) {
  110030. throw new Error("#/extensions: '" + this.name + "' not found");
  110031. }
  110032. var extension = extensions[this.name];
  110033. return extension.lights;
  110034. },
  110035. enumerable: true,
  110036. configurable: true
  110037. });
  110038. return KHR_lights;
  110039. }(GLTF2.GLTFLoaderExtension));
  110040. Extensions.KHR_lights = KHR_lights;
  110041. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110042. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110043. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110044. })(BABYLON || (BABYLON = {}));
  110045. //# sourceMappingURL=KHR_lights.js.map
  110046. return BABYLON;
  110047. });
  110048. /***/ }),
  110049. /* 33 */
  110050. /***/ (function(module, exports, __webpack_require__) {
  110051. /*!
  110052. * PEP v0.4.3 | https://github.com/jquery/PEP
  110053. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110054. */
  110055. !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);
  110056. // define inherited MouseEvent properties
  110057. // skip bubbles and cancelable since they're set above in initEvent()
  110058. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110059. // Spec requires that pointers without pressure specified use 0.5 for down
  110060. // state and 0 for up state.
  110061. var f=0;
  110062. // add x/y properties aliased to clientX/Y
  110063. // define the properties of the PointerEvent interface
  110064. 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(){
  110065. // only activate if this platform does not have pointer events
  110066. 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}})}/**
  110067. * This is the constructor for new PointerEvents.
  110068. *
  110069. * New Pointer Events must be given a type, and an optional dictionary of
  110070. * initialization properties.
  110071. *
  110072. * Due to certain platform requirements, events returned from the constructor
  110073. * identify as MouseEvents.
  110074. *
  110075. * @constructor
  110076. * @param {String} inType The type of the event to create.
  110077. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110078. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110079. */
  110080. 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},
  110081. // return value, key, map
  110082. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110083. // MouseEvent
  110084. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110085. // DOM Level 3
  110086. "buttons",
  110087. // PointerEvent
  110088. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110089. // event instance
  110090. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110091. // MouseEvent
  110092. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110093. // DOM Level 3
  110094. 0,
  110095. // PointerEvent
  110096. 0,0,0,0,0,0,"",0,!1,
  110097. // event instance
  110098. "",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),
  110099. // Scope objects for native events.
  110100. // This exists for ease of testing.
  110101. eventSources:Object.create(null),eventSourceList:[],/**
  110102. * Add a new event source that will generate pointer events.
  110103. *
  110104. * `inSource` must contain an array of event names named `events`, and
  110105. * functions with the names specified in the `events` array.
  110106. * @param {string} name A name for the event source
  110107. * @param {Object} source A new source of platform events.
  110108. */
  110109. 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++)
  110110. // call eventsource register
  110111. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110112. // call eventsource register
  110113. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110114. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110115. return!1}},
  110116. // EVENTS
  110117. 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)},
  110118. // LISTENER LOGIC
  110119. eventHandler:function(a){
  110120. // This is used to prevent multiple dispatch of pointerevents from
  110121. // platform events. This can happen when two elements in different scopes
  110122. // are set up to create pointer events, which is relevant to Shadow DOM.
  110123. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110124. // set up event listeners
  110125. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110126. // remove event listeners
  110127. 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)},
  110128. // EVENT CREATION AND TRACKING
  110129. /**
  110130. * Creates a new Event of type `inType`, based on the information in
  110131. * `inEvent`.
  110132. *
  110133. * @param {string} inType A string representing the type of event to create
  110134. * @param {Event} inEvent A platform event with a target
  110135. * @return {Event} A PointerEvent of type `inType`
  110136. */
  110137. makeEvent:function(b,c){
  110138. // relatedTarget must be null if pointer is captured
  110139. 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},
  110140. // make and dispatch an event in one call
  110141. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110142. * Returns a snapshot of inEvent, with writable properties.
  110143. *
  110144. * @param {Event} inEvent An event that contains properties to copy.
  110145. * @return {Object} An object containing shallow copies of `inEvent`'s
  110146. * properties.
  110147. */
  110148. 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],
  110149. // Work around SVGInstanceElement shadow tree
  110150. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110151. // This is the behavior implemented by Firefox.
  110152. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110153. // keep the semantics of preventDefault
  110154. 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){
  110155. // Order of conditions due to document.contains() missing in IE.
  110156. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110157. // Touch: Do not propagate if node is detached.
  110158. 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)}},/**
  110159. * Dispatches the event to its target.
  110160. *
  110161. * @param {Event} inEvent The event to be dispatched.
  110162. * @return {Boolean} True if an event handler returns true, false otherwise.
  110163. */
  110164. 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(
  110165. // is element a shadow host?
  110166. e=this.targetingShadow(f);e;){if(
  110167. // find the the element inside the shadow root
  110168. d=e.elementFromPoint(b,c)){
  110169. // shadowed element may contain a shadow root
  110170. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110171. // check for older shadows
  110172. e=this.olderShadow(e)}
  110173. // light dom element is the target
  110174. return f}},owner:function(a){
  110175. // walk up until you hit the shadow root or document
  110176. for(var b=a;b.parentNode;)b=b.parentNode;
  110177. // the owner element is expected to be a Document or ShadowRoot
  110178. 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);
  110179. // if x, y is not in this root, fall back to document search
  110180. 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){
  110181. // Only watch scopes that can target find, as these are top-level.
  110182. // Otherwise we can see duplicate additions and removals that add noise.
  110183. //
  110184. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110185. // a removal without an insertion when a node is redistributed among
  110186. // shadows. Since it all ends up correct in the document, watching only
  110187. // the document will yield the correct mutations to watch.
  110188. 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))},
  110189. // register all touch-action = none nodes on document load
  110190. 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){
  110191. // find children with touch-action
  110192. var b=x(a,this.findElements,this);
  110193. // flatten the list
  110194. // make sure the added nodes are accounted for
  110195. 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){}
  110196. // handler block for native mouse events
  110197. 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:[],
  110198. // collide with the global mouse listener
  110199. 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++){
  110200. // simulated mouse events will be swallowed near a primary touchend
  110201. 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);
  110202. // Update buttons state after possible out-of-document mouseup.
  110203. 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];
  110204. // Produces wrong state of buttons in Browsers without `buttons` support
  110205. // when a mouse button that was pressed outside the document is released
  110206. // inside and other buttons are still pressed down.
  110207. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110208. // Support: Firefox <=44 only
  110209. // FF Ubuntu includes the lifted button in the `buttons` property on
  110210. // mouseup.
  110211. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110212. 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),
  110213. // set touch-action on shadows as well
  110214. 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),
  110215. // remove touch-action from shadow
  110216. 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);
  110217. // simply update scrollType if listeners are already established
  110218. 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){
  110219. // set primary touch if there no pointers, or the only pointer is the mouse
  110220. (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,
  110221. // forward modifier keys
  110222. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110223. // forward touch preventDefaults
  110224. 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))},
  110225. // For single axis scrollers, determines whether the element should emit
  110226. // pointer events or behave as a scroller
  110227. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110228. // this element is a touch-action: none, should never scroll
  110229. b=!1;else if("XY"===c)
  110230. // this element should always scroll
  110231. 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]);
  110232. // if delta in the scroll axis > delta other axis, scroll instead of
  110233. // making events
  110234. 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},
  110235. // In some instances, a touchstart can happen without a touchend. This
  110236. // leaves the pointermap in a broken state.
  110237. // Therefore, on every touchstart, we remove the touches that did not fire a
  110238. // touchend event.
  110239. // To keep state globally consistent, we fire a
  110240. // pointercancel for this "abandoned" touch
  110241. vacuumTouches:function(a){var b=a.touches;
  110242. // pointermap.size should be < tl.length here, as the touchstart has not
  110243. // been processed yet.
  110244. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110245. // Never remove pointerId == 1, which is mouse.
  110246. // Touch identifiers are 2 smaller than their pointerId, which is the
  110247. // index in pointermap.
  110248. 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);
  110249. // a finger drifted off the screen, ignore it
  110250. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110251. // recover from retargeting by shadow
  110252. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110253. // clean up case when finger leaves the screen
  110254. 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)},
  110255. // prevent synth mouse events from creating pointer events
  110256. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110257. // only the primary finger will synth mouse events
  110258. if(this.isPrimaryTouch(c)){
  110259. // remember x/y of last touch
  110260. 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});
  110261. /***/ }),
  110262. /* 34 */
  110263. /***/ (function(module, exports, __webpack_require__) {
  110264. "use strict";
  110265. Object.defineProperty(exports, "__esModule", { value: true });
  110266. var defaultViewer_1 = __webpack_require__(4);
  110267. var mappers_1 = __webpack_require__(1);
  110268. function InitTags(selector) {
  110269. if (selector === void 0) { selector = 'babylon'; }
  110270. var elements = document.querySelectorAll(selector);
  110271. for (var i = 0; i < elements.length; ++i) {
  110272. var element = elements.item(i);
  110273. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110274. var config = configMapper.map(element);
  110275. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110276. }
  110277. }
  110278. exports.InitTags = InitTags;
  110279. /***/ })
  110280. /******/ ]);
  110281. return BabylonViewer;
  110282. });