12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196 |
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- __.prototype = b.prototype;
- d.prototype = new __();
- };
- var BABYLON;
- (function (BABYLON) {
- var ToGammaSpace = 1 / 2.2;
- var ToLinearSpace = 2.2;
- var Color3 = (function () {
- function Color3(r, g, b) {
- if (r === void 0) { r = 0; }
- if (g === void 0) { g = 0; }
- if (b === void 0) { b = 0; }
- this.r = r;
- this.g = g;
- this.b = b;
- }
- Color3.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
- };
- // Operators
- Color3.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.r;
- array[index + 1] = this.g;
- array[index + 2] = this.b;
- return this;
- };
- Color3.prototype.toColor4 = function (alpha) {
- if (alpha === void 0) { alpha = 1; }
- return new Color4(this.r, this.g, this.b, alpha);
- };
- Color3.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Color3.prototype.toLuminance = function () {
- return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
- };
- Color3.prototype.multiply = function (otherColor) {
- return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
- };
- Color3.prototype.multiplyToRef = function (otherColor, result) {
- result.r = this.r * otherColor.r;
- result.g = this.g * otherColor.g;
- result.b = this.b * otherColor.b;
- return this;
- };
- Color3.prototype.equals = function (otherColor) {
- return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
- };
- Color3.prototype.equalsFloats = function (r, g, b) {
- return this.r === r && this.g === g && this.b === b;
- };
- Color3.prototype.scale = function (scale) {
- return new Color3(this.r * scale, this.g * scale, this.b * scale);
- };
- Color3.prototype.scaleToRef = function (scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- return this;
- };
- Color3.prototype.add = function (otherColor) {
- return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
- };
- Color3.prototype.addToRef = function (otherColor, result) {
- result.r = this.r + otherColor.r;
- result.g = this.g + otherColor.g;
- result.b = this.b + otherColor.b;
- return this;
- };
- Color3.prototype.subtract = function (otherColor) {
- return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
- };
- Color3.prototype.subtractToRef = function (otherColor, result) {
- result.r = this.r - otherColor.r;
- result.g = this.g - otherColor.g;
- result.b = this.b - otherColor.b;
- return this;
- };
- Color3.prototype.clone = function () {
- return new Color3(this.r, this.g, this.b);
- };
- Color3.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- return this;
- };
- Color3.prototype.copyFromFloats = function (r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
- return this;
- };
- Color3.prototype.toHexString = function () {
- var intR = (this.r * 255) | 0;
- var intG = (this.g * 255) | 0;
- var intB = (this.b * 255) | 0;
- return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
- };
- Color3.prototype.toLinearSpace = function () {
- var convertedColor = new Color3();
- this.toLinearSpaceToRef(convertedColor);
- return convertedColor;
- };
- Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
- convertedColor.r = Math.pow(this.r, ToLinearSpace);
- convertedColor.g = Math.pow(this.g, ToLinearSpace);
- convertedColor.b = Math.pow(this.b, ToLinearSpace);
- return this;
- };
- Color3.prototype.toGammaSpace = function () {
- var convertedColor = new Color3();
- this.toGammaSpaceToRef(convertedColor);
- return convertedColor;
- };
- Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
- convertedColor.r = Math.pow(this.r, ToGammaSpace);
- convertedColor.g = Math.pow(this.g, ToGammaSpace);
- convertedColor.b = Math.pow(this.b, ToGammaSpace);
- return this;
- };
- // Statics
- Color3.FromHexString = function (hex) {
- if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
- BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
- return new Color3(0, 0, 0);
- }
- var r = parseInt(hex.substring(1, 3), 16);
- var g = parseInt(hex.substring(3, 5), 16);
- var b = parseInt(hex.substring(5, 7), 16);
- return Color3.FromInts(r, g, b);
- };
- Color3.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Color3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Color3.FromInts = function (r, g, b) {
- return new Color3(r / 255.0, g / 255.0, b / 255.0);
- };
- Color3.Lerp = function (start, end, amount) {
- var r = start.r + ((end.r - start.r) * amount);
- var g = start.g + ((end.g - start.g) * amount);
- var b = start.b + ((end.b - start.b) * amount);
- return new Color3(r, g, b);
- };
- Color3.Red = function () { return new Color3(1, 0, 0); };
- Color3.Green = function () { return new Color3(0, 1, 0); };
- Color3.Blue = function () { return new Color3(0, 0, 1); };
- Color3.Black = function () { return new Color3(0, 0, 0); };
- Color3.White = function () { return new Color3(1, 1, 1); };
- Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
- Color3.Magenta = function () { return new Color3(1, 0, 1); };
- Color3.Yellow = function () { return new Color3(1, 1, 0); };
- Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
- return Color3;
- })();
- BABYLON.Color3 = Color3;
- var Color4 = (function () {
- function Color4(r, g, b, a) {
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- }
- // Operators
- Color4.prototype.addInPlace = function (right) {
- this.r += right.r;
- this.g += right.g;
- this.b += right.b;
- this.a += right.a;
- return this;
- };
- Color4.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Color4.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.r;
- array[index + 1] = this.g;
- array[index + 2] = this.b;
- array[index + 3] = this.a;
- return this;
- };
- Color4.prototype.add = function (right) {
- return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
- };
- Color4.prototype.subtract = function (right) {
- return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
- };
- Color4.prototype.subtractToRef = function (right, result) {
- result.r = this.r - right.r;
- result.g = this.g - right.g;
- result.b = this.b - right.b;
- result.a = this.a - right.a;
- return this;
- };
- Color4.prototype.scale = function (scale) {
- return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
- };
- Color4.prototype.scaleToRef = function (scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- result.a = this.a * scale;
- return this;
- };
- Color4.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
- };
- Color4.prototype.clone = function () {
- return new Color4(this.r, this.g, this.b, this.a);
- };
- Color4.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- this.a = source.a;
- return this;
- };
- Color4.prototype.toHexString = function () {
- var intR = (this.r * 255) | 0;
- var intG = (this.g * 255) | 0;
- var intB = (this.b * 255) | 0;
- var intA = (this.a * 255) | 0;
- return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
- };
- // Statics
- Color4.FromHexString = function (hex) {
- if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
- BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
- return new Color4(0, 0, 0, 0);
- }
- var r = parseInt(hex.substring(1, 3), 16);
- var g = parseInt(hex.substring(3, 5), 16);
- var b = parseInt(hex.substring(5, 7), 16);
- var a = parseInt(hex.substring(7, 9), 16);
- return Color4.FromInts(r, g, b, a);
- };
- Color4.Lerp = function (left, right, amount) {
- var result = new Color4(0, 0, 0, 0);
- Color4.LerpToRef(left, right, amount, result);
- return result;
- };
- Color4.LerpToRef = function (left, right, amount, result) {
- result.r = left.r + (right.r - left.r) * amount;
- result.g = left.g + (right.g - left.g) * amount;
- result.b = left.b + (right.b - left.b) * amount;
- result.a = left.a + (right.a - left.a) * amount;
- };
- Color4.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Color4.FromInts = function (r, g, b, a) {
- return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
- };
- Color4.CheckColors4 = function (colors, count) {
- // Check if color3 was used
- if (colors.length === count * 3) {
- var colors4 = [];
- for (var index = 0; index < colors.length; index += 3) {
- var newIndex = (index / 3) * 4;
- colors4[newIndex] = colors[index];
- colors4[newIndex + 1] = colors[index + 1];
- colors4[newIndex + 2] = colors[index + 2];
- colors4[newIndex + 3] = 1.0;
- }
- return colors4;
- }
- return colors;
- };
- return Color4;
- })();
- BABYLON.Color4 = Color4;
- var Vector2 = (function () {
- function Vector2(x, y) {
- this.x = x;
- this.y = y;
- }
- Vector2.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + "}";
- };
- // Operators
- Vector2.prototype.toArray = function (array, index) {
- if (index === void 0) { index = 0; }
- array[index] = this.x;
- array[index + 1] = this.y;
- return this;
- };
- Vector2.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector2.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- return this;
- };
- Vector2.prototype.copyFromFloats = function (x, y) {
- this.x = x;
- this.y = y;
- return this;
- };
- Vector2.prototype.add = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- Vector2.prototype.addVector3 = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- Vector2.prototype.subtract = function (otherVector) {
- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
- };
- Vector2.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- return this;
- };
- Vector2.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- return this;
- };
- Vector2.prototype.multiply = function (otherVector) {
- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
- };
- Vector2.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- return this;
- };
- Vector2.prototype.multiplyByFloats = function (x, y) {
- return new Vector2(this.x * x, this.y * y);
- };
- Vector2.prototype.divide = function (otherVector) {
- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
- };
- Vector2.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- return this;
- };
- Vector2.prototype.negate = function () {
- return new Vector2(-this.x, -this.y);
- };
- Vector2.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- return this;
- };
- Vector2.prototype.scale = function (scale) {
- return new Vector2(this.x * scale, this.y * scale);
- };
- Vector2.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y;
- };
- Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
- return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
- };
- // Properties
- Vector2.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- };
- Vector2.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y);
- };
- // Methods
- Vector2.prototype.normalize = function () {
- var len = this.length();
- if (len === 0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- return this;
- };
- Vector2.prototype.clone = function () {
- return new Vector2(this.x, this.y);
- };
- // Statics
- Vector2.Zero = function () {
- return new Vector2(0, 0);
- };
- Vector2.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Vector2(array[offset], array[offset + 1]);
- };
- Vector2.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- };
- Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
- (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
- ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
- var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
- (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
- ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
- return new Vector2(x, y);
- };
- Vector2.Clamp = function (value, min, max) {
- var x = value.x;
- x = (x > max.x) ? max.x : x;
- x = (x < min.x) ? min.x : x;
- var y = value.y;
- y = (y > max.y) ? max.y : y;
- y = (y < min.y) ? min.y : y;
- return new Vector2(x, y);
- };
- Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
- var part2 = (-2.0 * cubed) + (3.0 * squared);
- var part3 = (cubed - (2.0 * squared)) + amount;
- var part4 = cubed - squared;
- var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
- var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
- return new Vector2(x, y);
- };
- Vector2.Lerp = function (start, end, amount) {
- var x = start.x + ((end.x - start.x) * amount);
- var y = start.y + ((end.y - start.y) * amount);
- return new Vector2(x, y);
- };
- Vector2.Dot = function (left, right) {
- return left.x * right.x + left.y * right.y;
- };
- Vector2.Normalize = function (vector) {
- var newVector = vector.clone();
- newVector.normalize();
- return newVector;
- };
- Vector2.Minimize = function (left, right) {
- var x = (left.x < right.x) ? left.x : right.x;
- var y = (left.y < right.y) ? left.y : right.y;
- return new Vector2(x, y);
- };
- Vector2.Maximize = function (left, right) {
- var x = (left.x > right.x) ? left.x : right.x;
- var y = (left.y > right.y) ? left.y : right.y;
- return new Vector2(x, y);
- };
- Vector2.Transform = function (vector, transformation) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
- return new Vector2(x, y);
- };
- Vector2.Distance = function (value1, value2) {
- return Math.sqrt(Vector2.DistanceSquared(value1, value2));
- };
- Vector2.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- return (x * x) + (y * y);
- };
- return Vector2;
- })();
- BABYLON.Vector2 = Vector2;
- var Vector3 = (function () {
- function Vector3(x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- Vector3.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
- };
- // Operators
- Vector3.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector3.prototype.toArray = function (array, index) {
- if (index === void 0) { index = 0; }
- array[index] = this.x;
- array[index + 1] = this.y;
- array[index + 2] = this.z;
- return this;
- };
- Vector3.prototype.toQuaternion = function () {
- var result = new Quaternion(0, 0, 0, 1);
- var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
- var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
- var coszMinusx = Math.cos((this.z - this.x) * 0.5);
- var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
- var cosy = Math.cos(this.y * 0.5);
- var siny = Math.sin(this.y * 0.5);
- result.x = coszMinusx * siny;
- result.y = -sinzMinusx * siny;
- result.z = sinxPlusz * cosy;
- result.w = cosxPlusz * cosy;
- return result;
- };
- Vector3.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- return this;
- };
- Vector3.prototype.add = function (otherVector) {
- return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
- };
- Vector3.prototype.addToRef = function (otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- result.z = this.z + otherVector.z;
- return this;
- };
- Vector3.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- return this;
- };
- Vector3.prototype.subtract = function (otherVector) {
- return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
- };
- Vector3.prototype.subtractToRef = function (otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- result.z = this.z - otherVector.z;
- return this;
- };
- Vector3.prototype.subtractFromFloats = function (x, y, z) {
- return new Vector3(this.x - x, this.y - y, this.z - z);
- };
- Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
- result.x = this.x - x;
- result.y = this.y - y;
- result.z = this.z - z;
- return this;
- };
- Vector3.prototype.negate = function () {
- return new Vector3(-this.x, -this.y, -this.z);
- };
- Vector3.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- return this;
- };
- Vector3.prototype.scale = function (scale) {
- return new Vector3(this.x * scale, this.y * scale, this.z * scale);
- };
- Vector3.prototype.scaleToRef = function (scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- result.z = this.z * scale;
- };
- Vector3.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
- };
- Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
- return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
- };
- Vector3.prototype.equalsToFloats = function (x, y, z) {
- return this.x === x && this.y === y && this.z === z;
- };
- Vector3.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- return this;
- };
- Vector3.prototype.multiply = function (otherVector) {
- return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
- };
- Vector3.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- result.z = this.z * otherVector.z;
- return this;
- };
- Vector3.prototype.multiplyByFloats = function (x, y, z) {
- return new Vector3(this.x * x, this.y * y, this.z * z);
- };
- Vector3.prototype.divide = function (otherVector) {
- return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
- };
- Vector3.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- result.z = this.z / otherVector.z;
- return this;
- };
- Vector3.prototype.MinimizeInPlace = function (other) {
- if (other.x < this.x)
- this.x = other.x;
- if (other.y < this.y)
- this.y = other.y;
- if (other.z < this.z)
- this.z = other.z;
- return this;
- };
- Vector3.prototype.MaximizeInPlace = function (other) {
- if (other.x > this.x)
- this.x = other.x;
- if (other.y > this.y)
- this.y = other.y;
- if (other.z > this.z)
- this.z = other.z;
- return this;
- };
- // Properties
- Vector3.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
- };
- Vector3.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z);
- };
- // Methods
- Vector3.prototype.normalize = function () {
- var len = this.length();
- if (len === 0 || len === 1.0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- this.z *= num;
- return this;
- };
- Vector3.prototype.clone = function () {
- return new Vector3(this.x, this.y, this.z);
- };
- Vector3.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- return this;
- };
- Vector3.prototype.copyFromFloats = function (x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- return this;
- };
- // Statics
- Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
- var d0 = Vector3.Dot(vector0, axis) - size;
- var d1 = Vector3.Dot(vector1, axis) - size;
- var s = d0 / (d0 - d1);
- return s;
- };
- Vector3.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Vector3.FromFloatArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Vector3.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- };
- Vector3.FromFloatArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- };
- Vector3.FromFloatsToRef = function (x, y, z, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- };
- Vector3.Zero = function () {
- return new Vector3(0, 0, 0);
- };
- Vector3.Up = function () {
- return new Vector3(0, 1.0, 0);
- };
- Vector3.TransformCoordinates = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformCoordinatesToRef(vector, transformation, result);
- return result;
- };
- Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
- var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
- var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
- result.x = x / w;
- result.y = y / w;
- result.z = z / w;
- };
- Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
- var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
- var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
- var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
- var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
- result.x = rx / rw;
- result.y = ry / rw;
- result.z = rz / rw;
- };
- Vector3.TransformNormal = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformNormalToRef(vector, transformation, result);
- return result;
- };
- Vector3.TransformNormalToRef = function (vector, transformation, result) {
- result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
- result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
- result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
- };
- Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
- result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
- result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
- result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
- };
- Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
- (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
- ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
- var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
- (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
- ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
- var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
- (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
- ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
- return new Vector3(x, y, z);
- };
- Vector3.Clamp = function (value, min, max) {
- var x = value.x;
- x = (x > max.x) ? max.x : x;
- x = (x < min.x) ? min.x : x;
- var y = value.y;
- y = (y > max.y) ? max.y : y;
- y = (y < min.y) ? min.y : y;
- var z = value.z;
- z = (z > max.z) ? max.z : z;
- z = (z < min.z) ? min.z : z;
- return new Vector3(x, y, z);
- };
- Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
- var part2 = (-2.0 * cubed) + (3.0 * squared);
- var part3 = (cubed - (2.0 * squared)) + amount;
- var part4 = cubed - squared;
- var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
- var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
- var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
- return new Vector3(x, y, z);
- };
- Vector3.Lerp = function (start, end, amount) {
- var x = start.x + ((end.x - start.x) * amount);
- var y = start.y + ((end.y - start.y) * amount);
- var z = start.z + ((end.z - start.z) * amount);
- return new Vector3(x, y, z);
- };
- Vector3.Dot = function (left, right) {
- return (left.x * right.x + left.y * right.y + left.z * right.z);
- };
- Vector3.Cross = function (left, right) {
- var result = Vector3.Zero();
- Vector3.CrossToRef(left, right, result);
- return result;
- };
- Vector3.CrossToRef = function (left, right, result) {
- result.x = left.y * right.z - left.z * right.y;
- result.y = left.z * right.x - left.x * right.z;
- result.z = left.x * right.y - left.y * right.x;
- };
- Vector3.Normalize = function (vector) {
- var result = Vector3.Zero();
- Vector3.NormalizeToRef(vector, result);
- return result;
- };
- Vector3.NormalizeToRef = function (vector, result) {
- result.copyFrom(vector);
- result.normalize();
- };
- Vector3.Project = function (vector, world, transform, viewport) {
- var cw = viewport.width;
- var ch = viewport.height;
- var cx = viewport.x;
- var cy = viewport.y;
- var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
- var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
- return Vector3.TransformCoordinates(vector, finalMatrix);
- };
- Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
- var matrix = world.multiply(transform);
- matrix.invert();
- source.x = source.x / viewportWidth * 2 - 1;
- source.y = -(source.y / viewportHeight * 2 - 1);
- var vector = Vector3.TransformCoordinates(source, matrix);
- var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
- if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
- vector = vector.scale(1.0 / num);
- }
- return vector;
- };
- Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
- var matrix = world.multiply(view).multiply(projection);
- matrix.invert();
- var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
- var vector = Vector3.TransformCoordinates(screenSource, matrix);
- var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
- if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
- vector = vector.scale(1.0 / num);
- }
- return vector;
- };
- Vector3.Minimize = function (left, right) {
- var min = left.clone();
- min.MinimizeInPlace(right);
- return min;
- };
- Vector3.Maximize = function (left, right) {
- var max = left.clone();
- max.MaximizeInPlace(right);
- return max;
- };
- Vector3.Distance = function (value1, value2) {
- return Math.sqrt(Vector3.DistanceSquared(value1, value2));
- };
- Vector3.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- var z = value1.z - value2.z;
- return (x * x) + (y * y) + (z * z);
- };
- Vector3.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- /**
- * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
- * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
- * to something in order to rotate it from its local system to the given target system.
- */
- Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
- var rotation = Vector3.Zero();
- Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
- return rotation;
- };
- /**
- * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
- */
- Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
- var u = axis1.normalize();
- var w = axis3.normalize();
- // world axis
- var X = Axis.X;
- var Y = Axis.Y;
- // equation unknowns and vars
- var yaw = 0.0;
- var pitch = 0.0;
- var roll = 0.0;
- var x = 0.0;
- var y = 0.0;
- var z = 0.0;
- var t = 0.0;
- var sign = -1.0;
- var nbRevert = 0;
- var cross = Tmp.Vector3[0];
- var dot = 0.0;
- // step 1 : rotation around w
- // Rv3(u) = u1, and u1 belongs to plane xOz
- // Rv3(w) = w1 = w invariant
- var u1 = Tmp.Vector3[1];
- if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
- z = 1.0;
- }
- else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
- x = 1.0;
- }
- else {
- t = w.z / w.x;
- x = -t * Math.sqrt(1 / (1 + t * t));
- z = Math.sqrt(1 / (1 + t * t));
- }
- u1.x = x;
- u1.y = y;
- u1.z = z;
- u1.normalize();
- Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(w, cross) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(u, u1);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- roll = Math.acos(dot) * sign;
- if (Vector3.Dot(u1, X) < 0) {
- roll = Math.PI + roll;
- u1 = u1.scaleInPlace(-1);
- nbRevert++;
- }
- // step 2 : rotate around u1
- // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
- // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
- var w2 = Tmp.Vector3[2];
- var v2 = Tmp.Vector3[3];
- x = 0.0;
- y = 0.0;
- z = 0.0;
- sign = -1.0;
- if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
- x = 1.0;
- }
- else {
- t = u1.z / u1.x;
- x = -t * Math.sqrt(1 / (1 + t * t));
- z = Math.sqrt(1 / (1 + t * t));
- }
- w2.x = x;
- w2.y = y;
- w2.z = z;
- w2.normalize();
- Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
- v2.normalize();
- Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(u1, cross) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(w, w2);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- pitch = Math.acos(dot) * sign;
- if (Vector3.Dot(v2, Y) < 0) {
- pitch = Math.PI + pitch;
- nbRevert++;
- }
- // step 3 : rotate around v2
- // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
- sign = -1.0;
- Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(cross, Y) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(u1, X);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
- if (dot < 0 && nbRevert < 2) {
- yaw = Math.PI + yaw;
- }
- ref.x = pitch;
- ref.y = yaw;
- ref.z = roll;
- };
- return Vector3;
- })();
- BABYLON.Vector3 = Vector3;
- //Vector4 class created for EulerAngle class conversion to Quaternion
- var Vector4 = (function () {
- function Vector4(x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- Vector4.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
- };
- // Operators
- Vector4.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector4.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.x;
- array[index + 1] = this.y;
- array[index + 2] = this.z;
- array[index + 3] = this.w;
- return this;
- };
- Vector4.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- this.w += otherVector.w;
- return this;
- };
- Vector4.prototype.add = function (otherVector) {
- return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
- };
- Vector4.prototype.addToRef = function (otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- result.z = this.z + otherVector.z;
- result.w = this.w + otherVector.w;
- return this;
- };
- Vector4.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- this.w -= otherVector.w;
- return this;
- };
- Vector4.prototype.subtract = function (otherVector) {
- return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
- };
- Vector4.prototype.subtractToRef = function (otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- result.z = this.z - otherVector.z;
- result.w = this.w - otherVector.w;
- return this;
- };
- Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
- return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
- };
- Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
- result.x = this.x - x;
- result.y = this.y - y;
- result.z = this.z - z;
- result.w = this.w - w;
- return this;
- };
- Vector4.prototype.negate = function () {
- return new Vector4(-this.x, -this.y, -this.z, -this.w);
- };
- Vector4.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- this.w *= scale;
- return this;
- };
- Vector4.prototype.scale = function (scale) {
- return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
- };
- Vector4.prototype.scaleToRef = function (scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- result.z = this.z * scale;
- result.w = this.w * scale;
- };
- Vector4.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
- };
- Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
- return otherVector
- && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
- && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
- && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
- && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
- };
- Vector4.prototype.equalsToFloats = function (x, y, z, w) {
- return this.x === x && this.y === y && this.z === z && this.w === w;
- };
- Vector4.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- this.w *= otherVector.w;
- return this;
- };
- Vector4.prototype.multiply = function (otherVector) {
- return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
- };
- Vector4.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- result.z = this.z * otherVector.z;
- result.w = this.w * otherVector.w;
- return this;
- };
- Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
- return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
- };
- Vector4.prototype.divide = function (otherVector) {
- return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
- };
- Vector4.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- result.z = this.z / otherVector.z;
- result.w = this.w / otherVector.w;
- return this;
- };
- Vector4.prototype.MinimizeInPlace = function (other) {
- if (other.x < this.x)
- this.x = other.x;
- if (other.y < this.y)
- this.y = other.y;
- if (other.z < this.z)
- this.z = other.z;
- if (other.w < this.w)
- this.w = other.w;
- return this;
- };
- Vector4.prototype.MaximizeInPlace = function (other) {
- if (other.x > this.x)
- this.x = other.x;
- if (other.y > this.y)
- this.y = other.y;
- if (other.z > this.z)
- this.z = other.z;
- if (other.w > this.w)
- this.w = other.w;
- return this;
- };
- // Properties
- Vector4.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- Vector4.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- // Methods
- Vector4.prototype.normalize = function () {
- var len = this.length();
- if (len === 0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- this.z *= num;
- this.w *= num;
- return this;
- };
- Vector4.prototype.clone = function () {
- return new Vector4(this.x, this.y, this.z, this.w);
- };
- Vector4.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- this.w = source.w;
- return this;
- };
- Vector4.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- // Statics
- Vector4.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Vector4.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- result.w = array[offset + 3];
- };
- Vector4.FromFloatArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- result.w = array[offset + 3];
- };
- Vector4.FromFloatsToRef = function (x, y, z, w, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- result.w = w;
- };
- Vector4.Zero = function () {
- return new Vector4(0, 0, 0, 0);
- };
- Vector4.Normalize = function (vector) {
- var result = Vector4.Zero();
- Vector4.NormalizeToRef(vector, result);
- return result;
- };
- Vector4.NormalizeToRef = function (vector, result) {
- result.copyFrom(vector);
- result.normalize();
- };
- Vector4.Minimize = function (left, right) {
- var min = left.clone();
- min.MinimizeInPlace(right);
- return min;
- };
- Vector4.Maximize = function (left, right) {
- var max = left.clone();
- max.MaximizeInPlace(right);
- return max;
- };
- Vector4.Distance = function (value1, value2) {
- return Math.sqrt(Vector4.DistanceSquared(value1, value2));
- };
- Vector4.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- var z = value1.z - value2.z;
- var w = value1.w - value2.w;
- return (x * x) + (y * y) + (z * z) + (w * w);
- };
- Vector4.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- return Vector4;
- })();
- BABYLON.Vector4 = Vector4;
- var Quaternion = (function () {
- function Quaternion(x, y, z, w) {
- if (x === void 0) { x = 0; }
- if (y === void 0) { y = 0; }
- if (z === void 0) { z = 0; }
- if (w === void 0) { w = 1; }
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- Quaternion.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
- };
- Quaternion.prototype.asArray = function () {
- return [this.x, this.y, this.z, this.w];
- };
- Quaternion.prototype.equals = function (otherQuaternion) {
- return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
- };
- Quaternion.prototype.clone = function () {
- return new Quaternion(this.x, this.y, this.z, this.w);
- };
- Quaternion.prototype.copyFrom = function (other) {
- this.x = other.x;
- this.y = other.y;
- this.z = other.z;
- this.w = other.w;
- return this;
- };
- Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- Quaternion.prototype.add = function (other) {
- return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
- };
- Quaternion.prototype.subtract = function (other) {
- return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
- };
- Quaternion.prototype.scale = function (value) {
- return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
- };
- Quaternion.prototype.multiply = function (q1) {
- var result = new Quaternion(0, 0, 0, 1.0);
- this.multiplyToRef(q1, result);
- return result;
- };
- Quaternion.prototype.multiplyToRef = function (q1, result) {
- var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
- var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
- var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
- var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
- result.copyFromFloats(x, y, z, w);
- return this;
- };
- Quaternion.prototype.multiplyInPlace = function (q1) {
- this.multiplyToRef(q1, this);
- return this;
- };
- Quaternion.prototype.length = function () {
- return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
- };
- Quaternion.prototype.normalize = function () {
- var length = 1.0 / this.length();
- this.x *= length;
- this.y *= length;
- this.z *= length;
- this.w *= length;
- return this;
- };
- Quaternion.prototype.toEulerAngles = function (order) {
- if (order === void 0) { order = "YZX"; }
- var result = Vector3.Zero();
- this.toEulerAnglesToRef(result, order);
- return result;
- };
- Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
- if (order === void 0) { order = "YZX"; }
- var heading, attitude, bank;
- var x = this.x, y = this.y, z = this.z, w = this.w;
- switch (order) {
- case "YZX":
- var test = x * y + z * w;
- if (test > 0.499) {
- heading = 2 * Math.atan2(x, w);
- attitude = Math.PI / 2;
- bank = 0;
- }
- if (test < -0.499) {
- heading = -2 * Math.atan2(x, w);
- attitude = -Math.PI / 2;
- bank = 0;
- }
- if (isNaN(heading)) {
- var sqx = x * x;
- var sqy = y * y;
- var sqz = z * z;
- heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
- attitude = Math.asin(2 * test); // attitude
- bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
- }
- break;
- default:
- throw new Error("Euler order " + order + " not supported yet.");
- }
- result.y = heading;
- result.z = attitude;
- result.x = bank;
- return this;
- };
- ;
- Quaternion.prototype.toRotationMatrix = function (result) {
- var xx = this.x * this.x;
- var yy = this.y * this.y;
- var zz = this.z * this.z;
- var xy = this.x * this.y;
- var zw = this.z * this.w;
- var zx = this.z * this.x;
- var yw = this.y * this.w;
- var yz = this.y * this.z;
- var xw = this.x * this.w;
- result.m[0] = 1.0 - (2.0 * (yy + zz));
- result.m[1] = 2.0 * (xy + zw);
- result.m[2] = 2.0 * (zx - yw);
- result.m[3] = 0;
- result.m[4] = 2.0 * (xy - zw);
- result.m[5] = 1.0 - (2.0 * (zz + xx));
- result.m[6] = 2.0 * (yz + xw);
- result.m[7] = 0;
- result.m[8] = 2.0 * (zx + yw);
- result.m[9] = 2.0 * (yz - xw);
- result.m[10] = 1.0 - (2.0 * (yy + xx));
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- result.m[15] = 1.0;
- return this;
- };
- Quaternion.prototype.fromRotationMatrix = function (matrix) {
- Quaternion.FromRotationMatrixToRef(matrix, this);
- return this;
- };
- // Statics
- Quaternion.FromRotationMatrix = function (matrix) {
- var result = new Quaternion();
- Quaternion.FromRotationMatrixToRef(matrix, result);
- return result;
- };
- Quaternion.FromRotationMatrixToRef = function (matrix, result) {
- var data = matrix.m;
- var m11 = data[0], m12 = data[4], m13 = data[8];
- var m21 = data[1], m22 = data[5], m23 = data[9];
- var m31 = data[2], m32 = data[6], m33 = data[10];
- var trace = m11 + m22 + m33;
- var s;
- if (trace > 0) {
- s = 0.5 / Math.sqrt(trace + 1.0);
- result.w = 0.25 / s;
- result.x = (m32 - m23) * s;
- result.y = (m13 - m31) * s;
- result.z = (m21 - m12) * s;
- }
- else if (m11 > m22 && m11 > m33) {
- s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
- result.w = (m32 - m23) / s;
- result.x = 0.25 * s;
- result.y = (m12 + m21) / s;
- result.z = (m13 + m31) / s;
- }
- else if (m22 > m33) {
- s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
- result.w = (m13 - m31) / s;
- result.x = (m12 + m21) / s;
- result.y = 0.25 * s;
- result.z = (m23 + m32) / s;
- }
- else {
- s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
- result.w = (m21 - m12) / s;
- result.x = (m13 + m31) / s;
- result.y = (m23 + m32) / s;
- result.z = 0.25 * s;
- }
- };
- Quaternion.Inverse = function (q) {
- return new Quaternion(-q.x, -q.y, -q.z, q.w);
- };
- Quaternion.Identity = function () {
- return new Quaternion(0, 0, 0, 1);
- };
- Quaternion.RotationAxis = function (axis, angle) {
- var result = new Quaternion();
- var sin = Math.sin(angle / 2);
- axis.normalize();
- result.w = Math.cos(angle / 2);
- result.x = axis.x * sin;
- result.y = axis.y * sin;
- result.z = axis.z * sin;
- return result;
- };
- Quaternion.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var result = new Quaternion();
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- };
- Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
- // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
- var halfRoll = roll * 0.5;
- var halfPitch = pitch * 0.5;
- var halfYaw = yaw * 0.5;
- var sinRoll = Math.sin(halfRoll);
- var cosRoll = Math.cos(halfRoll);
- var sinPitch = Math.sin(halfPitch);
- var cosPitch = Math.cos(halfPitch);
- var sinYaw = Math.sin(halfYaw);
- var cosYaw = Math.cos(halfYaw);
- result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
- result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
- result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
- result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
- };
- Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
- var result = new Quaternion();
- Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
- return result;
- };
- Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
- // Produces a quaternion from Euler angles in the z-x-z orientation
- var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
- var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
- var halfBeta = beta * 0.5;
- result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
- result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
- result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
- result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
- };
- Quaternion.Slerp = function (left, right, amount) {
- var num2;
- var num3;
- var num = amount;
- var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
- var flag = false;
- if (num4 < 0) {
- flag = true;
- num4 = -num4;
- }
- if (num4 > 0.999999) {
- num3 = 1 - num;
- num2 = flag ? -num : num;
- }
- else {
- var num5 = Math.acos(num4);
- var num6 = (1.0 / Math.sin(num5));
- num3 = (Math.sin((1.0 - num) * num5)) * num6;
- num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
- }
- return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
- };
- return Quaternion;
- })();
- BABYLON.Quaternion = Quaternion;
- var Matrix = (function () {
- function Matrix() {
- this.m = new Float32Array(16);
- }
- // Properties
- Matrix.prototype.isIdentity = function () {
- if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
- return false;
- if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
- this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
- this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
- this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
- return false;
- return true;
- };
- Matrix.prototype.determinant = function () {
- var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
- var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
- var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
- var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
- var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
- var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
- return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
- (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
- (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
- };
- // Methods
- Matrix.prototype.toArray = function () {
- return this.m;
- };
- Matrix.prototype.asArray = function () {
- return this.toArray();
- };
- Matrix.prototype.invert = function () {
- this.invertToRef(this);
- return this;
- };
- Matrix.prototype.reset = function () {
- for (var index = 0; index < 16; index++) {
- this.m[index] = 0;
- }
- return this;
- };
- Matrix.prototype.add = function (other) {
- var result = new Matrix();
- this.addToRef(other, result);
- return result;
- };
- Matrix.prototype.addToRef = function (other, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = this.m[index] + other.m[index];
- }
- return this;
- };
- Matrix.prototype.addToSelf = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] += other.m[index];
- }
- return this;
- };
- Matrix.prototype.invertToRef = function (other) {
- var l1 = this.m[0];
- var l2 = this.m[1];
- var l3 = this.m[2];
- var l4 = this.m[3];
- var l5 = this.m[4];
- var l6 = this.m[5];
- var l7 = this.m[6];
- var l8 = this.m[7];
- var l9 = this.m[8];
- var l10 = this.m[9];
- var l11 = this.m[10];
- var l12 = this.m[11];
- var l13 = this.m[12];
- var l14 = this.m[13];
- var l15 = this.m[14];
- var l16 = this.m[15];
- var l17 = (l11 * l16) - (l12 * l15);
- var l18 = (l10 * l16) - (l12 * l14);
- var l19 = (l10 * l15) - (l11 * l14);
- var l20 = (l9 * l16) - (l12 * l13);
- var l21 = (l9 * l15) - (l11 * l13);
- var l22 = (l9 * l14) - (l10 * l13);
- var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
- var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
- var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
- var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
- var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
- var l28 = (l7 * l16) - (l8 * l15);
- var l29 = (l6 * l16) - (l8 * l14);
- var l30 = (l6 * l15) - (l7 * l14);
- var l31 = (l5 * l16) - (l8 * l13);
- var l32 = (l5 * l15) - (l7 * l13);
- var l33 = (l5 * l14) - (l6 * l13);
- var l34 = (l7 * l12) - (l8 * l11);
- var l35 = (l6 * l12) - (l8 * l10);
- var l36 = (l6 * l11) - (l7 * l10);
- var l37 = (l5 * l12) - (l8 * l9);
- var l38 = (l5 * l11) - (l7 * l9);
- var l39 = (l5 * l10) - (l6 * l9);
- other.m[0] = l23 * l27;
- other.m[4] = l24 * l27;
- other.m[8] = l25 * l27;
- other.m[12] = l26 * l27;
- other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
- other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
- other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
- other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
- other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
- other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
- other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
- other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
- other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
- other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
- other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
- other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
- return this;
- };
- Matrix.prototype.setTranslation = function (vector3) {
- this.m[12] = vector3.x;
- this.m[13] = vector3.y;
- this.m[14] = vector3.z;
- return this;
- };
- Matrix.prototype.multiply = function (other) {
- var result = new Matrix();
- this.multiplyToRef(other, result);
- return result;
- };
- Matrix.prototype.copyFrom = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] = other.m[index];
- }
- return this;
- };
- Matrix.prototype.copyToArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- for (var index = 0; index < 16; index++) {
- array[offset + index] = this.m[index];
- }
- return this;
- };
- Matrix.prototype.multiplyToRef = function (other, result) {
- this.multiplyToArray(other, result.m, 0);
- return this;
- };
- Matrix.prototype.multiplyToArray = function (other, result, offset) {
- var tm0 = this.m[0];
- var tm1 = this.m[1];
- var tm2 = this.m[2];
- var tm3 = this.m[3];
- var tm4 = this.m[4];
- var tm5 = this.m[5];
- var tm6 = this.m[6];
- var tm7 = this.m[7];
- var tm8 = this.m[8];
- var tm9 = this.m[9];
- var tm10 = this.m[10];
- var tm11 = this.m[11];
- var tm12 = this.m[12];
- var tm13 = this.m[13];
- var tm14 = this.m[14];
- var tm15 = this.m[15];
- var om0 = other.m[0];
- var om1 = other.m[1];
- var om2 = other.m[2];
- var om3 = other.m[3];
- var om4 = other.m[4];
- var om5 = other.m[5];
- var om6 = other.m[6];
- var om7 = other.m[7];
- var om8 = other.m[8];
- var om9 = other.m[9];
- var om10 = other.m[10];
- var om11 = other.m[11];
- var om12 = other.m[12];
- var om13 = other.m[13];
- var om14 = other.m[14];
- var om15 = other.m[15];
- result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
- result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
- result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
- result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
- result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
- result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
- result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
- result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
- result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
- result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
- result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
- result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
- result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
- result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
- result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
- result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
- return this;
- };
- Matrix.prototype.equals = function (value) {
- return value &&
- (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
- this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
- this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
- this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
- };
- Matrix.prototype.clone = function () {
- 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]);
- };
- Matrix.prototype.decompose = function (scale, rotation, translation) {
- translation.x = this.m[12];
- translation.y = this.m[13];
- translation.z = this.m[14];
- var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
- var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
- var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
- scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
- scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
- scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
- if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
- rotation.x = 0;
- rotation.y = 0;
- rotation.z = 0;
- rotation.w = 1;
- return false;
- }
- var rotationMatrix = Matrix.FromValues(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);
- Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
- return true;
- };
- // Statics
- Matrix.FromArray = function (array, offset) {
- var result = new Matrix();
- if (!offset) {
- offset = 0;
- }
- Matrix.FromArrayToRef(array, offset, result);
- return result;
- };
- Matrix.FromArrayToRef = function (array, offset, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset];
- }
- };
- Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset] * scale;
- }
- };
- Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
- result.m[0] = initialM11;
- result.m[1] = initialM12;
- result.m[2] = initialM13;
- result.m[3] = initialM14;
- result.m[4] = initialM21;
- result.m[5] = initialM22;
- result.m[6] = initialM23;
- result.m[7] = initialM24;
- result.m[8] = initialM31;
- result.m[9] = initialM32;
- result.m[10] = initialM33;
- result.m[11] = initialM34;
- result.m[12] = initialM41;
- result.m[13] = initialM42;
- result.m[14] = initialM43;
- result.m[15] = initialM44;
- };
- Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
- var result = new Matrix();
- result.m[0] = initialM11;
- result.m[1] = initialM12;
- result.m[2] = initialM13;
- result.m[3] = initialM14;
- result.m[4] = initialM21;
- result.m[5] = initialM22;
- result.m[6] = initialM23;
- result.m[7] = initialM24;
- result.m[8] = initialM31;
- result.m[9] = initialM32;
- result.m[10] = initialM33;
- result.m[11] = initialM34;
- result.m[12] = initialM41;
- result.m[13] = initialM42;
- result.m[14] = initialM43;
- result.m[15] = initialM44;
- return result;
- };
- Matrix.Compose = function (scale, rotation, translation) {
- var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
- var rotationMatrix = Matrix.Identity();
- rotation.toRotationMatrix(rotationMatrix);
- result = result.multiply(rotationMatrix);
- result.setTranslation(translation);
- return result;
- };
- Matrix.Identity = function () {
- return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
- };
- Matrix.IdentityToRef = function (result) {
- Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
- };
- Matrix.Zero = function () {
- return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
- };
- Matrix.RotationX = function (angle) {
- var result = new Matrix();
- Matrix.RotationXToRef(angle, result);
- return result;
- };
- Matrix.Invert = function (source) {
- var result = new Matrix();
- source.invertToRef(result);
- return result;
- };
- Matrix.RotationXToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[0] = 1.0;
- result.m[15] = 1.0;
- result.m[5] = c;
- result.m[10] = c;
- result.m[9] = -s;
- result.m[6] = s;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationY = function (angle) {
- var result = new Matrix();
- Matrix.RotationYToRef(angle, result);
- return result;
- };
- Matrix.RotationYToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[5] = 1.0;
- result.m[15] = 1.0;
- result.m[0] = c;
- result.m[2] = -s;
- result.m[8] = s;
- result.m[10] = c;
- result.m[1] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[9] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationZ = function (angle) {
- var result = new Matrix();
- Matrix.RotationZToRef(angle, result);
- return result;
- };
- Matrix.RotationZToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[10] = 1.0;
- result.m[15] = 1.0;
- result.m[0] = c;
- result.m[1] = s;
- result.m[4] = -s;
- result.m[5] = c;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[9] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationAxis = function (axis, angle) {
- var result = Matrix.Zero();
- Matrix.RotationAxisToRef(axis, angle, result);
- return result;
- };
- Matrix.RotationAxisToRef = function (axis, angle, result) {
- var s = Math.sin(-angle);
- var c = Math.cos(-angle);
- var c1 = 1 - c;
- axis.normalize();
- result.m[0] = (axis.x * axis.x) * c1 + c;
- result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
- result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
- result.m[3] = 0.0;
- result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
- result.m[5] = (axis.y * axis.y) * c1 + c;
- result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
- result.m[7] = 0.0;
- result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
- result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
- result.m[10] = (axis.z * axis.z) * c1 + c;
- result.m[11] = 0.0;
- result.m[15] = 1.0;
- };
- Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var result = new Matrix();
- Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- };
- Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
- this._tempQuaternion.toRotationMatrix(result);
- };
- Matrix.Scaling = function (x, y, z) {
- var result = Matrix.Zero();
- Matrix.ScalingToRef(x, y, z, result);
- return result;
- };
- Matrix.ScalingToRef = function (x, y, z, result) {
- result.m[0] = x;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[5] = y;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[9] = 0;
- result.m[10] = z;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- result.m[15] = 1.0;
- };
- Matrix.Translation = function (x, y, z) {
- var result = Matrix.Identity();
- Matrix.TranslationToRef(x, y, z, result);
- return result;
- };
- Matrix.TranslationToRef = function (x, y, z, result) {
- Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
- };
- Matrix.Lerp = function (startValue, endValue, gradient) {
- var startScale = new Vector3(0, 0, 0);
- var startRotation = new Quaternion();
- var startTranslation = new Vector3(0, 0, 0);
- startValue.decompose(startScale, startRotation, startTranslation);
- var endScale = new Vector3(0, 0, 0);
- var endRotation = new Quaternion();
- var endTranslation = new Vector3(0, 0, 0);
- endValue.decompose(endScale, endRotation, endTranslation);
- var resultScale = Vector3.Lerp(startScale, endScale, gradient);
- var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
- var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
- return Matrix.Compose(resultScale, resultRotation, resultTranslation);
- };
- Matrix.LookAtLH = function (eye, target, up) {
- var result = Matrix.Zero();
- Matrix.LookAtLHToRef(eye, target, up, result);
- return result;
- };
- Matrix.LookAtLHToRef = function (eye, target, up, result) {
- // Z axis
- target.subtractToRef(eye, this._zAxis);
- this._zAxis.normalize();
- // X axis
- Vector3.CrossToRef(up, this._zAxis, this._xAxis);
- if (this._xAxis.lengthSquared() === 0) {
- this._xAxis.x = 1.0;
- }
- else {
- this._xAxis.normalize();
- }
- // Y axis
- Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
- this._yAxis.normalize();
- // Eye angles
- var ex = -Vector3.Dot(this._xAxis, eye);
- var ey = -Vector3.Dot(this._yAxis, eye);
- var ez = -Vector3.Dot(this._zAxis, eye);
- 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);
- };
- Matrix.OrthoLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
- return matrix;
- };
- Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
- var hw = 2.0 / width;
- var hh = 2.0 / height;
- var id = 1.0 / (zfar - znear);
- var nid = znear / (znear - zfar);
- Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
- };
- Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
- return matrix;
- };
- Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
- result.m[0] = 2.0 / (right - left);
- result.m[1] = result.m[2] = result.m[3] = 0;
- result.m[5] = 2.0 / (top - bottom);
- result.m[4] = result.m[6] = result.m[7] = 0;
- result.m[10] = -1.0 / (znear - zfar);
- result.m[8] = result.m[9] = result.m[11] = 0;
- result.m[12] = (left + right) / (left - right);
- result.m[13] = (top + bottom) / (bottom - top);
- result.m[14] = znear / (znear - zfar);
- result.m[15] = 1.0;
- };
- Matrix.PerspectiveLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- matrix.m[0] = (2.0 * znear) / width;
- matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
- matrix.m[5] = (2.0 * znear) / height;
- matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
- matrix.m[10] = -zfar / (znear - zfar);
- matrix.m[8] = matrix.m[9] = 0.0;
- matrix.m[11] = 1.0;
- matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
- matrix.m[14] = (znear * zfar) / (znear - zfar);
- return matrix;
- };
- Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
- return matrix;
- };
- Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
- if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
- var tan = 1.0 / (Math.tan(fov * 0.5));
- var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
- if (v_fixed) {
- result.m[0] = tan / aspect;
- }
- else {
- result.m[0] = tan;
- }
- result.m[1] = result.m[2] = result.m[3] = 0.0;
- if (v_fixed) {
- result.m[5] = tan;
- }
- else {
- result.m[5] = tan * aspect;
- }
- result.m[4] = result.m[6] = result.m[7] = 0.0;
- result.m[8] = result.m[9] = 0.0;
- result.m[10] = -zfar / (znear - zfar);
- result.m[11] = 1.0;
- result.m[12] = result.m[13] = result.m[15] = 0.0;
- result.m[14] = (znear * zfar) / (znear - zfar);
- };
- Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
- var cw = viewport.width;
- var ch = viewport.height;
- var cx = viewport.x;
- var cy = viewport.y;
- var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
- return world.multiply(view).multiply(projection).multiply(viewportMatrix);
- };
- Matrix.GetAsMatrix2x2 = function (matrix) {
- return new Float32Array([
- matrix.m[0], matrix.m[1],
- matrix.m[4], matrix.m[5]
- ]);
- };
- Matrix.GetAsMatrix3x3 = function (matrix) {
- return new Float32Array([
- matrix.m[0], matrix.m[1], matrix.m[2],
- matrix.m[4], matrix.m[5], matrix.m[6],
- matrix.m[8], matrix.m[9], matrix.m[10]
- ]);
- };
- Matrix.Transpose = function (matrix) {
- var result = new Matrix();
- result.m[0] = matrix.m[0];
- result.m[1] = matrix.m[4];
- result.m[2] = matrix.m[8];
- result.m[3] = matrix.m[12];
- result.m[4] = matrix.m[1];
- result.m[5] = matrix.m[5];
- result.m[6] = matrix.m[9];
- result.m[7] = matrix.m[13];
- result.m[8] = matrix.m[2];
- result.m[9] = matrix.m[6];
- result.m[10] = matrix.m[10];
- result.m[11] = matrix.m[14];
- result.m[12] = matrix.m[3];
- result.m[13] = matrix.m[7];
- result.m[14] = matrix.m[11];
- result.m[15] = matrix.m[15];
- return result;
- };
- Matrix.Reflection = function (plane) {
- var matrix = new Matrix();
- Matrix.ReflectionToRef(plane, matrix);
- return matrix;
- };
- Matrix.ReflectionToRef = function (plane, result) {
- plane.normalize();
- var x = plane.normal.x;
- var y = plane.normal.y;
- var z = plane.normal.z;
- var temp = -2 * x;
- var temp2 = -2 * y;
- var temp3 = -2 * z;
- result.m[0] = (temp * x) + 1;
- result.m[1] = temp2 * x;
- result.m[2] = temp3 * x;
- result.m[3] = 0.0;
- result.m[4] = temp * y;
- result.m[5] = (temp2 * y) + 1;
- result.m[6] = temp3 * y;
- result.m[7] = 0.0;
- result.m[8] = temp * z;
- result.m[9] = temp2 * z;
- result.m[10] = (temp3 * z) + 1;
- result.m[11] = 0.0;
- result.m[12] = temp * plane.d;
- result.m[13] = temp2 * plane.d;
- result.m[14] = temp3 * plane.d;
- result.m[15] = 1.0;
- };
- Matrix._tempQuaternion = new Quaternion();
- Matrix._xAxis = Vector3.Zero();
- Matrix._yAxis = Vector3.Zero();
- Matrix._zAxis = Vector3.Zero();
- return Matrix;
- })();
- BABYLON.Matrix = Matrix;
- var Plane = (function () {
- function Plane(a, b, c, d) {
- this.normal = new Vector3(a, b, c);
- this.d = d;
- }
- Plane.prototype.asArray = function () {
- return [this.normal.x, this.normal.y, this.normal.z, this.d];
- };
- // Methods
- Plane.prototype.clone = function () {
- return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
- };
- Plane.prototype.normalize = function () {
- var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
- var magnitude = 0;
- if (norm !== 0) {
- magnitude = 1.0 / norm;
- }
- this.normal.x *= magnitude;
- this.normal.y *= magnitude;
- this.normal.z *= magnitude;
- this.d *= magnitude;
- return this;
- };
- Plane.prototype.transform = function (transformation) {
- var transposedMatrix = Matrix.Transpose(transformation);
- var x = this.normal.x;
- var y = this.normal.y;
- var z = this.normal.z;
- var d = this.d;
- var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
- var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
- var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
- var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
- return new Plane(normalX, normalY, normalZ, finalD);
- };
- Plane.prototype.dotCoordinate = function (point) {
- return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
- };
- Plane.prototype.copyFromPoints = function (point1, point2, point3) {
- var x1 = point2.x - point1.x;
- var y1 = point2.y - point1.y;
- var z1 = point2.z - point1.z;
- var x2 = point3.x - point1.x;
- var y2 = point3.y - point1.y;
- var z2 = point3.z - point1.z;
- var yz = (y1 * z2) - (z1 * y2);
- var xz = (z1 * x2) - (x1 * z2);
- var xy = (x1 * y2) - (y1 * x2);
- var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
- var invPyth;
- if (pyth !== 0) {
- invPyth = 1.0 / pyth;
- }
- else {
- invPyth = 0;
- }
- this.normal.x = yz * invPyth;
- this.normal.y = xz * invPyth;
- this.normal.z = xy * invPyth;
- this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
- return this;
- };
- Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
- var dot = Vector3.Dot(this.normal, direction);
- return (dot <= epsilon);
- };
- Plane.prototype.signedDistanceTo = function (point) {
- return Vector3.Dot(point, this.normal) + this.d;
- };
- // Statics
- Plane.FromArray = function (array) {
- return new Plane(array[0], array[1], array[2], array[3]);
- };
- Plane.FromPoints = function (point1, point2, point3) {
- var result = new Plane(0, 0, 0, 0);
- result.copyFromPoints(point1, point2, point3);
- return result;
- };
- Plane.FromPositionAndNormal = function (origin, normal) {
- var result = new Plane(0, 0, 0, 0);
- normal.normalize();
- result.normal = normal;
- result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
- return result;
- };
- Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
- var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
- return Vector3.Dot(point, normal) + d;
- };
- return Plane;
- })();
- BABYLON.Plane = Plane;
- var Viewport = (function () {
- function Viewport(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- }
- Viewport.prototype.toGlobal = function (engine) {
- var width = engine.getRenderWidth();
- var height = engine.getRenderHeight();
- return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
- };
- Viewport.prototype.toScreenGlobal = function (engine) {
- var width = engine.getRenderWidth(true);
- var height = engine.getRenderHeight(true);
- return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
- };
- return Viewport;
- })();
- BABYLON.Viewport = Viewport;
- var Frustum = (function () {
- function Frustum() {
- }
- Frustum.GetPlanes = function (transform) {
- var frustumPlanes = [];
- for (var index = 0; index < 6; index++) {
- frustumPlanes.push(new Plane(0, 0, 0, 0));
- }
- Frustum.GetPlanesToRef(transform, frustumPlanes);
- return frustumPlanes;
- };
- Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
- // Near
- frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
- frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
- frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
- frustumPlanes[0].d = transform.m[15] + transform.m[14];
- frustumPlanes[0].normalize();
- // Far
- frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
- frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
- frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
- frustumPlanes[1].d = transform.m[15] - transform.m[14];
- frustumPlanes[1].normalize();
- // Left
- frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
- frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
- frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
- frustumPlanes[2].d = transform.m[15] + transform.m[12];
- frustumPlanes[2].normalize();
- // Right
- frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
- frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
- frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
- frustumPlanes[3].d = transform.m[15] - transform.m[12];
- frustumPlanes[3].normalize();
- // Top
- frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
- frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
- frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
- frustumPlanes[4].d = transform.m[15] - transform.m[13];
- frustumPlanes[4].normalize();
- // Bottom
- frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
- frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
- frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
- frustumPlanes[5].d = transform.m[15] + transform.m[13];
- frustumPlanes[5].normalize();
- };
- return Frustum;
- })();
- BABYLON.Frustum = Frustum;
- var Ray = (function () {
- function Ray(origin, direction, length) {
- if (length === void 0) { length = Number.MAX_VALUE; }
- this.origin = origin;
- this.direction = direction;
- this.length = length;
- }
- // Methods
- Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
- var d = 0.0;
- var maxValue = Number.MAX_VALUE;
- var inv;
- var min;
- var max;
- var temp;
- if (Math.abs(this.direction.x) < 0.0000001) {
- if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.x;
- min = (minimum.x - this.origin.x) * inv;
- max = (maximum.x - this.origin.x) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- if (Math.abs(this.direction.y) < 0.0000001) {
- if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.y;
- min = (minimum.y - this.origin.y) * inv;
- max = (maximum.y - this.origin.y) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- if (Math.abs(this.direction.z) < 0.0000001) {
- if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.z;
- min = (minimum.z - this.origin.z) * inv;
- max = (maximum.z - this.origin.z) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- return true;
- };
- Ray.prototype.intersectsBox = function (box) {
- return this.intersectsBoxMinMax(box.minimum, box.maximum);
- };
- Ray.prototype.intersectsSphere = function (sphere) {
- var x = sphere.center.x - this.origin.x;
- var y = sphere.center.y - this.origin.y;
- var z = sphere.center.z - this.origin.z;
- var pyth = (x * x) + (y * y) + (z * z);
- var rr = sphere.radius * sphere.radius;
- if (pyth <= rr) {
- return true;
- }
- var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
- if (dot < 0.0) {
- return false;
- }
- var temp = pyth - (dot * dot);
- return temp <= rr;
- };
- Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
- if (!this._edge1) {
- this._edge1 = Vector3.Zero();
- this._edge2 = Vector3.Zero();
- this._pvec = Vector3.Zero();
- this._tvec = Vector3.Zero();
- this._qvec = Vector3.Zero();
- }
- vertex1.subtractToRef(vertex0, this._edge1);
- vertex2.subtractToRef(vertex0, this._edge2);
- Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
- var det = Vector3.Dot(this._edge1, this._pvec);
- if (det === 0) {
- return null;
- }
- var invdet = 1 / det;
- this.origin.subtractToRef(vertex0, this._tvec);
- var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
- if (bu < 0 || bu > 1.0) {
- return null;
- }
- Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
- var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
- if (bv < 0 || bu + bv > 1.0) {
- return null;
- }
- //check if the distance is longer than the predefined length.
- var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
- if (distance > this.length) {
- return null;
- }
- return new BABYLON.IntersectionInfo(bu, bv, distance);
- };
- // Statics
- Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
- var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
- var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
- var direction = end.subtract(start);
- direction.normalize();
- return new Ray(start, direction);
- };
- /**
- * 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
- * transformed to the given world matrix.
- * @param origin The origin point
- * @param end The end point
- * @param world a matrix to transform the ray to. Default is the identity matrix.
- */
- Ray.CreateNewFromTo = function (origin, end, world) {
- if (world === void 0) { world = Matrix.Identity(); }
- var direction = end.subtract(origin);
- var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
- direction.normalize();
- return Ray.Transform(new Ray(origin, direction, length), world);
- };
- Ray.Transform = function (ray, matrix) {
- var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
- var newDirection = Vector3.TransformNormal(ray.direction, matrix);
- return new Ray(newOrigin, newDirection, ray.length);
- };
- return Ray;
- })();
- BABYLON.Ray = Ray;
- (function (Space) {
- Space[Space["LOCAL"] = 0] = "LOCAL";
- Space[Space["WORLD"] = 1] = "WORLD";
- })(BABYLON.Space || (BABYLON.Space = {}));
- var Space = BABYLON.Space;
- var Axis = (function () {
- function Axis() {
- }
- Axis.X = new Vector3(1, 0, 0);
- Axis.Y = new Vector3(0, 1, 0);
- Axis.Z = new Vector3(0, 0, 1);
- return Axis;
- })();
- BABYLON.Axis = Axis;
- ;
- var BezierCurve = (function () {
- function BezierCurve() {
- }
- BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
- // Extract X (which is equal to time here)
- var f0 = 1 - 3 * x2 + 3 * x1;
- var f1 = 3 * x2 - 6 * x1;
- var f2 = 3 * x1;
- var refinedT = t;
- for (var i = 0; i < 5; i++) {
- var refinedT2 = refinedT * refinedT;
- var refinedT3 = refinedT2 * refinedT;
- var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
- var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
- refinedT -= (x - t) * slope;
- refinedT = Math.min(1, Math.max(0, refinedT));
- }
- // Resolve cubic bezier for the given x
- return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
- 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
- Math.pow(refinedT, 3);
- };
- return BezierCurve;
- })();
- BABYLON.BezierCurve = BezierCurve;
- (function (Orientation) {
- Orientation[Orientation["CW"] = 0] = "CW";
- Orientation[Orientation["CCW"] = 1] = "CCW";
- })(BABYLON.Orientation || (BABYLON.Orientation = {}));
- var Orientation = BABYLON.Orientation;
- var Angle = (function () {
- function Angle(radians) {
- var _this = this;
- this.degrees = function () { return _this._radians * 180 / Math.PI; };
- this.radians = function () { return _this._radians; };
- this._radians = radians;
- if (this._radians < 0)
- this._radians += (2 * Math.PI);
- }
- Angle.BetweenTwoPoints = function (a, b) {
- var delta = b.subtract(a);
- var theta = Math.atan2(delta.y, delta.x);
- return new Angle(theta);
- };
- Angle.FromRadians = function (radians) {
- return new Angle(radians);
- };
- Angle.FromDegrees = function (degrees) {
- return new Angle(degrees * Math.PI / 180);
- };
- return Angle;
- })();
- BABYLON.Angle = Angle;
- var Arc2 = (function () {
- function Arc2(startPoint, midPoint, endPoint) {
- this.startPoint = startPoint;
- this.midPoint = midPoint;
- this.endPoint = endPoint;
- var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
- var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
- var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
- var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
- 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);
- this.radius = this.centerPoint.subtract(this.startPoint).length();
- this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
- var a1 = this.startAngle.degrees();
- var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
- var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
- // angles correction
- if (a2 - a1 > +180.0)
- a2 -= 360.0;
- if (a2 - a1 < -180.0)
- a2 += 360.0;
- if (a3 - a2 > +180.0)
- a3 -= 360.0;
- if (a3 - a2 < -180.0)
- a3 += 360.0;
- this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
- this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
- }
- return Arc2;
- })();
- BABYLON.Arc2 = Arc2;
- var PathCursor = (function () {
- function PathCursor(path) {
- this.path = path;
- this._onchange = new Array();
- this.value = 0;
- this.animations = new Array();
- }
- PathCursor.prototype.getPoint = function () {
- var point = this.path.getPointAtLengthPosition(this.value);
- return new Vector3(point.x, 0, point.y);
- };
- PathCursor.prototype.moveAhead = function (step) {
- if (step === void 0) { step = 0.002; }
- this.move(step);
- return this;
- };
- PathCursor.prototype.moveBack = function (step) {
- if (step === void 0) { step = 0.002; }
- this.move(-step);
- return this;
- };
- PathCursor.prototype.move = function (step) {
- if (Math.abs(step) > 1) {
- throw "step size should be less than 1.";
- }
- this.value += step;
- this.ensureLimits();
- this.raiseOnChange();
- return this;
- };
- PathCursor.prototype.ensureLimits = function () {
- while (this.value > 1) {
- this.value -= 1;
- }
- while (this.value < 0) {
- this.value += 1;
- }
- return this;
- };
- // used by animation engine
- PathCursor.prototype.markAsDirty = function (propertyName) {
- this.ensureLimits();
- this.raiseOnChange();
- return this;
- };
- PathCursor.prototype.raiseOnChange = function () {
- var _this = this;
- this._onchange.forEach(function (f) { return f(_this); });
- return this;
- };
- PathCursor.prototype.onchange = function (f) {
- this._onchange.push(f);
- return this;
- };
- return PathCursor;
- })();
- BABYLON.PathCursor = PathCursor;
- var Path2 = (function () {
- function Path2(x, y) {
- this._points = new Array();
- this._length = 0;
- this.closed = false;
- this._points.push(new Vector2(x, y));
- }
- Path2.prototype.addLineTo = function (x, y) {
- if (closed) {
- BABYLON.Tools.Error("cannot add lines to closed paths");
- return this;
- }
- var newPoint = new Vector2(x, y);
- var previousPoint = this._points[this._points.length - 1];
- this._points.push(newPoint);
- this._length += newPoint.subtract(previousPoint).length();
- return this;
- };
- Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
- if (numberOfSegments === void 0) { numberOfSegments = 36; }
- if (closed) {
- BABYLON.Tools.Error("cannot add arcs to closed paths");
- return this;
- }
- var startPoint = this._points[this._points.length - 1];
- var midPoint = new Vector2(midX, midY);
- var endPoint = new Vector2(endX, endY);
- var arc = new Arc2(startPoint, midPoint, endPoint);
- var increment = arc.angle.radians() / numberOfSegments;
- if (arc.orientation === Orientation.CW)
- increment *= -1;
- var currentAngle = arc.startAngle.radians() + increment;
- for (var i = 0; i < numberOfSegments; i++) {
- var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
- var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
- this.addLineTo(x, y);
- currentAngle += increment;
- }
- return this;
- };
- Path2.prototype.close = function () {
- this.closed = true;
- return this;
- };
- Path2.prototype.length = function () {
- var result = this._length;
- if (!this.closed) {
- var lastPoint = this._points[this._points.length - 1];
- var firstPoint = this._points[0];
- result += (firstPoint.subtract(lastPoint).length());
- }
- return result;
- };
- Path2.prototype.getPoints = function () {
- return this._points;
- };
- Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
- if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
- BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
- return Vector2.Zero();
- }
- var lengthPosition = normalizedLengthPosition * this.length();
- var previousOffset = 0;
- for (var i = 0; i < this._points.length; i++) {
- var j = (i + 1) % this._points.length;
- var a = this._points[i];
- var b = this._points[j];
- var bToA = b.subtract(a);
- var nextOffset = (bToA.length() + previousOffset);
- if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
- var dir = bToA.normalize();
- var localOffset = lengthPosition - previousOffset;
- return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
- }
- previousOffset = nextOffset;
- }
- BABYLON.Tools.Error("internal error");
- return Vector2.Zero();
- };
- Path2.StartingAt = function (x, y) {
- return new Path2(x, y);
- };
- return Path2;
- })();
- BABYLON.Path2 = Path2;
- var Path3D = (function () {
- /**
- * new Path3D(path, normal, raw)
- * path : an array of Vector3, the curve axis of the Path3D
- * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
- * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
- */
- function Path3D(path, firstNormal, raw) {
- this.path = path;
- this._curve = new Array();
- this._distances = new Array();
- this._tangents = new Array();
- this._normals = new Array();
- this._binormals = new Array();
- for (var p = 0; p < path.length; p++) {
- this._curve[p] = path[p].clone(); // hard copy
- }
- this._raw = raw || false;
- this._compute(firstNormal);
- }
- Path3D.prototype.getCurve = function () {
- return this._curve;
- };
- Path3D.prototype.getTangents = function () {
- return this._tangents;
- };
- Path3D.prototype.getNormals = function () {
- return this._normals;
- };
- Path3D.prototype.getBinormals = function () {
- return this._binormals;
- };
- Path3D.prototype.getDistances = function () {
- return this._distances;
- };
- Path3D.prototype.update = function (path, firstNormal) {
- for (var p = 0; p < path.length; p++) {
- this._curve[p].x = path[p].x;
- this._curve[p].y = path[p].y;
- this._curve[p].z = path[p].z;
- }
- this._compute(firstNormal);
- return this;
- };
- // private function compute() : computes tangents, normals and binormals
- Path3D.prototype._compute = function (firstNormal) {
- var l = this._curve.length;
- // first and last tangents
- this._tangents[0] = this._getFirstNonNullVector(0);
- if (!this._raw) {
- this._tangents[0].normalize();
- }
- this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
- if (!this._raw) {
- this._tangents[l - 1].normalize();
- }
- // normals and binormals at first point : arbitrary vector with _normalVector()
- var tg0 = this._tangents[0];
- var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
- this._normals[0] = pp0;
- if (!this._raw) {
- this._normals[0].normalize();
- }
- this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
- if (!this._raw) {
- this._binormals[0].normalize();
- }
- this._distances[0] = 0;
- // normals and binormals : next points
- var prev; // previous vector (segment)
- var cur; // current vector (segment)
- var curTang; // current tangent
- // previous normal
- var prevBinor; // previous binormal
- for (var i = 1; i < l; i++) {
- // tangents
- prev = this._getLastNonNullVector(i);
- if (i < l - 1) {
- cur = this._getFirstNonNullVector(i);
- this._tangents[i] = prev.add(cur);
- this._tangents[i].normalize();
- }
- this._distances[i] = this._distances[i - 1] + prev.length();
- // normals and binormals
- // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
- curTang = this._tangents[i];
- prevBinor = this._binormals[i - 1];
- this._normals[i] = Vector3.Cross(prevBinor, curTang);
- if (!this._raw) {
- this._normals[i].normalize();
- }
- this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
- if (!this._raw) {
- this._binormals[i].normalize();
- }
- }
- };
- // private function getFirstNonNullVector(index)
- // returns the first non null vector from index : curve[index + N].subtract(curve[index])
- Path3D.prototype._getFirstNonNullVector = function (index) {
- var i = 1;
- var nNVector = this._curve[index + i].subtract(this._curve[index]);
- while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
- i++;
- nNVector = this._curve[index + i].subtract(this._curve[index]);
- }
- return nNVector;
- };
- // private function getLastNonNullVector(index)
- // returns the last non null vector from index : curve[index].subtract(curve[index - N])
- Path3D.prototype._getLastNonNullVector = function (index) {
- var i = 1;
- var nLVector = this._curve[index].subtract(this._curve[index - i]);
- while (nLVector.length() === 0 && index > i + 1) {
- i++;
- nLVector = this._curve[index].subtract(this._curve[index - i]);
- }
- return nLVector;
- };
- // private function normalVector(v0, vt, va) :
- // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
- // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
- Path3D.prototype._normalVector = function (v0, vt, va) {
- var normal0;
- if (va === undefined || va === null) {
- var point;
- if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
- point = new Vector3(0, -1, 0);
- }
- else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
- point = new Vector3(1, 0, 0);
- }
- else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
- point = new Vector3(0, 0, 1);
- }
- normal0 = Vector3.Cross(vt, point);
- }
- else {
- normal0 = Vector3.Cross(vt, va);
- Vector3.CrossToRef(normal0, vt, normal0);
- }
- normal0.normalize();
- return normal0;
- };
- return Path3D;
- })();
- BABYLON.Path3D = Path3D;
- var Curve3 = (function () {
- function Curve3(points) {
- this._length = 0;
- this._points = points;
- this._length = this._computeLength(points);
- }
- // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
- Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
- nbPoints = nbPoints > 2 ? nbPoints : 3;
- var bez = new Array();
- var equation = function (t, val0, val1, val2) {
- var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
- return res;
- };
- for (var i = 0; i <= nbPoints; i++) {
- 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)));
- }
- return new Curve3(bez);
- };
- // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
- Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
- nbPoints = nbPoints > 3 ? nbPoints : 4;
- var bez = new Array();
- var equation = function (t, val0, val1, val2, val3) {
- var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
- return res;
- };
- for (var i = 0; i <= nbPoints; i++) {
- 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)));
- }
- return new Curve3(bez);
- };
- // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
- Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
- var hermite = new Array();
- var step = 1 / nbPoints;
- for (var i = 0; i <= nbPoints; i++) {
- hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
- }
- return new Curve3(hermite);
- };
- Curve3.prototype.getPoints = function () {
- return this._points;
- };
- Curve3.prototype.length = function () {
- return this._length;
- };
- Curve3.prototype.continue = function (curve) {
- var lastPoint = this._points[this._points.length - 1];
- var continuedPoints = this._points.slice();
- var curvePoints = curve.getPoints();
- for (var i = 1; i < curvePoints.length; i++) {
- continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
- }
- var continuedCurve = new Curve3(continuedPoints);
- return continuedCurve;
- };
- Curve3.prototype._computeLength = function (path) {
- var l = 0;
- for (var i = 1; i < path.length; i++) {
- l += (path[i].subtract(path[i - 1])).length();
- }
- return l;
- };
- return Curve3;
- })();
- BABYLON.Curve3 = Curve3;
- // SphericalHarmonics
- var SphericalHarmonics = (function () {
- function SphericalHarmonics() {
- this.L00 = Vector3.Zero();
- this.L1_1 = Vector3.Zero();
- this.L10 = Vector3.Zero();
- this.L11 = Vector3.Zero();
- this.L2_2 = Vector3.Zero();
- this.L2_1 = Vector3.Zero();
- this.L20 = Vector3.Zero();
- this.L21 = Vector3.Zero();
- this.L22 = Vector3.Zero();
- }
- SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
- var colorVector = new Vector3(color.r, color.g, color.b);
- var c = colorVector.scale(deltaSolidAngle);
- this.L00 = this.L00.add(c.scale(0.282095));
- this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
- this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
- this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
- this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
- this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
- this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
- this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
- this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
- };
- SphericalHarmonics.prototype.scale = function (scale) {
- this.L00 = this.L00.scale(scale);
- this.L1_1 = this.L1_1.scale(scale);
- this.L10 = this.L10.scale(scale);
- this.L11 = this.L11.scale(scale);
- this.L2_2 = this.L2_2.scale(scale);
- this.L2_1 = this.L2_1.scale(scale);
- this.L20 = this.L20.scale(scale);
- this.L21 = this.L21.scale(scale);
- this.L22 = this.L22.scale(scale);
- };
- return SphericalHarmonics;
- })();
- BABYLON.SphericalHarmonics = SphericalHarmonics;
- // SphericalPolynomial
- var SphericalPolynomial = (function () {
- function SphericalPolynomial() {
- this.x = Vector3.Zero();
- this.y = Vector3.Zero();
- this.z = Vector3.Zero();
- this.xx = Vector3.Zero();
- this.yy = Vector3.Zero();
- this.zz = Vector3.Zero();
- this.xy = Vector3.Zero();
- this.yz = Vector3.Zero();
- this.zx = Vector3.Zero();
- }
- SphericalPolynomial.prototype.addAmbient = function (color) {
- var colorVector = new Vector3(color.r, color.g, color.b);
- this.xx = this.xx.add(colorVector);
- this.yy = this.yy.add(colorVector);
- this.zz = this.zz.add(colorVector);
- };
- SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
- var result = new SphericalPolynomial();
- result.x = harmonics.L11.scale(1.02333);
- result.y = harmonics.L1_1.scale(1.02333);
- result.z = harmonics.L10.scale(1.02333);
- result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
- result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
- result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
- result.yz = harmonics.L2_1.scale(0.858086);
- result.zx = harmonics.L21.scale(0.858086);
- result.xy = harmonics.L2_2.scale(0.858086);
- return result;
- };
- return SphericalPolynomial;
- })();
- BABYLON.SphericalPolynomial = SphericalPolynomial;
- // Vertex formats
- var PositionNormalVertex = (function () {
- function PositionNormalVertex(position, normal) {
- if (position === void 0) { position = Vector3.Zero(); }
- if (normal === void 0) { normal = Vector3.Up(); }
- this.position = position;
- this.normal = normal;
- }
- PositionNormalVertex.prototype.clone = function () {
- return new PositionNormalVertex(this.position.clone(), this.normal.clone());
- };
- return PositionNormalVertex;
- })();
- BABYLON.PositionNormalVertex = PositionNormalVertex;
- var PositionNormalTextureVertex = (function () {
- function PositionNormalTextureVertex(position, normal, uv) {
- if (position === void 0) { position = Vector3.Zero(); }
- if (normal === void 0) { normal = Vector3.Up(); }
- if (uv === void 0) { uv = Vector2.Zero(); }
- this.position = position;
- this.normal = normal;
- this.uv = uv;
- }
- PositionNormalTextureVertex.prototype.clone = function () {
- return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
- };
- return PositionNormalTextureVertex;
- })();
- BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
- // Temporary pre-allocated objects for engine internal use
- // usage in any internal function :
- // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
- // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
- var Tmp = (function () {
- function Tmp() {
- }
- Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
- Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
- Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
- Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
- Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
- Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
- return Tmp;
- })();
- BABYLON.Tmp = Tmp;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Database = (function () {
- function Database(urlToScene, callbackManifestChecked) {
- // Handling various flavors of prefixed version of IndexedDB
- this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
- this.callbackManifestChecked = callbackManifestChecked;
- this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
- this.db = null;
- this.enableSceneOffline = false;
- this.enableTexturesOffline = false;
- this.manifestVersionFound = 0;
- this.mustUpdateRessources = false;
- this.hasReachedQuota = false;
- if (!Database.IDBStorageEnabled) {
- this.callbackManifestChecked(true);
- }
- else {
- this.checkManifestFile();
- }
- }
- Database.prototype.checkManifestFile = function () {
- var _this = this;
- function noManifestFile() {
- that.enableSceneOffline = false;
- that.enableTexturesOffline = false;
- that.callbackManifestChecked(false);
- }
- var that = this;
- var timeStampUsed = false;
- var manifestURL = this.currentSceneUrl + ".manifest";
- var xhr = new XMLHttpRequest();
- if (navigator.onLine) {
- // Adding a timestamp to by-pass browsers' cache
- timeStampUsed = true;
- manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
- }
- xhr.open("GET", manifestURL, true);
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
- try {
- var manifestFile = JSON.parse(xhr.response);
- _this.enableSceneOffline = manifestFile.enableSceneOffline;
- _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
- if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
- _this.manifestVersionFound = manifestFile.version;
- }
- if (_this.callbackManifestChecked) {
- _this.callbackManifestChecked(true);
- }
- }
- catch (ex) {
- noManifestFile();
- }
- }
- else {
- noManifestFile();
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- if (timeStampUsed) {
- timeStampUsed = false;
- // Let's retry without the timeStamp
- // It could fail when coupled with HTML5 Offline API
- var retryManifestURL = _this.currentSceneUrl + ".manifest";
- xhr.open("GET", retryManifestURL, true);
- xhr.send();
- }
- else {
- noManifestFile();
- }
- }, false);
- try {
- xhr.send();
- }
- catch (ex) {
- BABYLON.Tools.Error("Error on XHR send request.");
- that.callbackManifestChecked(false);
- }
- };
- Database.prototype.openAsync = function (successCallback, errorCallback) {
- var _this = this;
- function handleError() {
- that.isSupported = false;
- if (errorCallback)
- errorCallback();
- }
- var that = this;
- if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
- // Your browser doesn't support IndexedDB
- this.isSupported = false;
- if (errorCallback)
- errorCallback();
- }
- else {
- // If the DB hasn't been opened or created yet
- if (!this.db) {
- this.hasReachedQuota = false;
- this.isSupported = true;
- var request = this.idbFactory.open("babylonjs", 1);
- // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
- request.onerror = function (event) {
- handleError();
- };
- // executes when a version change transaction cannot complete due to other active transactions
- request.onblocked = function (event) {
- BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
- handleError();
- };
- // DB has been opened successfully
- request.onsuccess = function (event) {
- _this.db = request.result;
- successCallback();
- };
- // Initialization of the DB. Creating Scenes & Textures stores
- request.onupgradeneeded = function (event) {
- _this.db = (event.target).result;
- try {
- var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
- var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
- var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
- handleError();
- }
- };
- }
- else {
- if (successCallback)
- successCallback();
- }
- }
- };
- Database.prototype.loadImageFromDB = function (url, image) {
- var _this = this;
- var completeURL = Database.ReturnFullUrlLocation(url);
- var saveAndLoadImage = function () {
- if (!_this.hasReachedQuota && _this.db !== null) {
- // the texture is not yet in the DB, let's try to save it
- _this._saveImageIntoDBAsync(completeURL, image);
- }
- else {
- image.src = url;
- }
- };
- if (!this.mustUpdateRessources) {
- this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
- }
- else {
- saveAndLoadImage();
- }
- };
- Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
- if (this.isSupported && this.db !== null) {
- var texture;
- var transaction = this.db.transaction(["textures"]);
- transaction.onabort = function (event) {
- image.src = url;
- };
- transaction.oncomplete = function (event) {
- var blobTextureURL;
- if (texture) {
- var URL = window.URL || window.webkitURL;
- blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
- image.onerror = function () {
- BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
- image.src = url;
- };
- image.src = blobTextureURL;
- }
- else {
- notInDBCallback();
- }
- };
- var getRequest = transaction.objectStore("textures").get(url);
- getRequest.onsuccess = function (event) {
- texture = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
- image.src = url;
- };
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- image.src = url;
- }
- };
- Database.prototype._saveImageIntoDBAsync = function (url, image) {
- var _this = this;
- if (this.isSupported) {
- // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
- var generateBlobUrl = function () {
- var blobTextureURL;
- if (blob) {
- var URL = window.URL || window.webkitURL;
- try {
- blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
- }
- // Chrome is raising a type error if we're setting the oneTimeOnly parameter
- catch (ex) {
- blobTextureURL = URL.createObjectURL(blob);
- }
- }
- image.src = blobTextureURL;
- };
- if (Database.IsUASupportingBlobStorage) {
- var xhr = new XMLHttpRequest(), blob;
- xhr.open("GET", url, true);
- xhr.responseType = "blob";
- xhr.addEventListener("load", function () {
- if (xhr.status === 200) {
- // Blob as response (XHR2)
- blob = xhr.response;
- var transaction = _this.db.transaction(["textures"], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- generateBlobUrl();
- };
- transaction.oncomplete = function (event) {
- generateBlobUrl();
- };
- var newTexture = { textureUrl: url, data: blob };
- try {
- // Put the blob into the dabase
- var addRequest = transaction.objectStore("textures").put(newTexture);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- generateBlobUrl();
- };
- }
- catch (ex) {
- // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
- if (ex.code === 25) {
- Database.IsUASupportingBlobStorage = false;
- }
- image.src = url;
- }
- }
- else {
- image.src = url;
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
- image.src = url;
- }, false);
- xhr.send();
- }
- else {
- image.src = url;
- }
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- image.src = url;
- }
- };
- Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
- var _this = this;
- var updateVersion = function (event) {
- // the version is not yet in the DB or we need to update it
- _this._saveVersionIntoDBAsync(url, versionLoaded);
- };
- this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
- };
- Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
- var _this = this;
- if (this.isSupported) {
- var version;
- try {
- var transaction = this.db.transaction(["versions"]);
- transaction.oncomplete = function (event) {
- if (version) {
- // If the version in the JSON file is > than the version in DB
- if (_this.manifestVersionFound > version.data) {
- _this.mustUpdateRessources = true;
- updateInDBCallback();
- }
- else {
- callback(version.data);
- }
- }
- else {
- _this.mustUpdateRessources = true;
- updateInDBCallback();
- }
- };
- transaction.onabort = function (event) {
- callback(-1);
- };
- var getRequest = transaction.objectStore("versions").get(url);
- getRequest.onsuccess = function (event) {
- version = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
- callback(-1);
- };
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
- callback(-1);
- }
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback(-1);
- }
- };
- Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
- var _this = this;
- if (this.isSupported && !this.hasReachedQuota) {
- try {
- // Open a transaction to the database
- var transaction = this.db.transaction(["versions"], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- _this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- callback(-1);
- };
- transaction.oncomplete = function (event) {
- callback(_this.manifestVersionFound);
- };
- var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
- // Put the scene into the database
- var addRequest = transaction.objectStore("versions").put(newVersion);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
- };
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
- callback(-1);
- }
- }
- else {
- callback(-1);
- }
- };
- Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
- var _this = this;
- var completeUrl = Database.ReturnFullUrlLocation(url);
- var saveAndLoadFile = function (event) {
- // the scene is not yet in the DB, let's try to save it
- _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
- };
- this._checkVersionFromDB(completeUrl, function (version) {
- if (version !== -1) {
- if (!_this.mustUpdateRessources) {
- _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
- }
- else {
- _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
- }
- }
- else {
- errorCallback();
- }
- });
- };
- Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
- if (this.isSupported) {
- var targetStore;
- if (url.indexOf(".babylon") !== -1) {
- targetStore = "scenes";
- }
- else {
- targetStore = "textures";
- }
- var file;
- var transaction = this.db.transaction([targetStore]);
- transaction.oncomplete = function (event) {
- if (file) {
- callback(file.data);
- }
- else {
- notInDBCallback();
- }
- };
- transaction.onabort = function (event) {
- notInDBCallback();
- };
- var getRequest = transaction.objectStore(targetStore).get(url);
- getRequest.onsuccess = function (event) {
- file = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading file " + url + " from DB.");
- notInDBCallback();
- };
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback();
- }
- };
- Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
- var _this = this;
- if (this.isSupported) {
- var targetStore;
- if (url.indexOf(".babylon") !== -1) {
- targetStore = "scenes";
- }
- else {
- targetStore = "textures";
- }
- // Create XHR
- var xhr = new XMLHttpRequest(), fileData;
- xhr.open("GET", url, true);
- if (useArrayBuffer) {
- xhr.responseType = "arraybuffer";
- }
- xhr.onprogress = progressCallback;
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
- // Blob as response (XHR2)
- //fileData = xhr.responseText;
- fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
- if (!_this.hasReachedQuota) {
- // Open a transaction to the database
- var transaction = _this.db.transaction([targetStore], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- callback(fileData);
- };
- transaction.oncomplete = function (event) {
- callback(fileData);
- };
- var newFile;
- if (targetStore === "scenes") {
- newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
- }
- else {
- newFile = { textureUrl: url, data: fileData };
- }
- try {
- // Put the scene into the database
- var addRequest = transaction.objectStore(targetStore).put(newFile);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
- };
- }
- catch (ex) {
- callback(fileData);
- }
- }
- else {
- callback(fileData);
- }
- }
- else {
- callback();
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- BABYLON.Tools.Error("error on XHR request.");
- callback();
- }, false);
- xhr.send();
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback();
- }
- };
- Database.IsUASupportingBlobStorage = true;
- Database.IDBStorageEnabled = true;
- Database.parseURL = function (url) {
- var a = document.createElement('a');
- a.href = url;
- var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
- var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
- var absLocation = url.substring(0, url.indexOf(fileName, 0));
- return absLocation;
- };
- Database.ReturnFullUrlLocation = function (url) {
- if (url.indexOf("http:/") === -1) {
- return (Database.parseURL(window.location.href) + url);
- }
- else {
- return url;
- }
- };
- return Database;
- })();
- BABYLON.Database = Database;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- /*
- * Based on jsTGALoader - Javascript loader for TGA file
- * By Vincent Thibault
- * @blog http://blog.robrowser.com/javascript-tga-loader.html
- */
- var TGATools = (function () {
- function TGATools() {
- }
- TGATools.GetTGAHeader = function (data) {
- var offset = 0;
- var header = {
- id_length: data[offset++],
- colormap_type: data[offset++],
- image_type: data[offset++],
- colormap_index: data[offset++] | data[offset++] << 8,
- colormap_length: data[offset++] | data[offset++] << 8,
- colormap_size: data[offset++],
- origin: [
- data[offset++] | data[offset++] << 8,
- data[offset++] | data[offset++] << 8
- ],
- width: data[offset++] | data[offset++] << 8,
- height: data[offset++] | data[offset++] << 8,
- pixel_size: data[offset++],
- flags: data[offset++]
- };
- return header;
- };
- TGATools.UploadContent = function (gl, data) {
- // Not enough data to contain header ?
- if (data.length < 19) {
- BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
- return;
- }
- // Read Header
- var offset = 18;
- var header = TGATools.GetTGAHeader(data);
- // Assume it's a valid Targa file.
- if (header.id_length + offset > data.length) {
- BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
- return;
- }
- // Skip not needed data
- offset += header.id_length;
- var use_rle = false;
- var use_pal = false;
- var use_rgb = false;
- var use_grey = false;
- // Get some informations.
- switch (header.image_type) {
- case TGATools._TYPE_RLE_INDEXED:
- use_rle = true;
- case TGATools._TYPE_INDEXED:
- use_pal = true;
- break;
- case TGATools._TYPE_RLE_RGB:
- use_rle = true;
- case TGATools._TYPE_RGB:
- use_rgb = true;
- break;
- case TGATools._TYPE_RLE_GREY:
- use_rle = true;
- case TGATools._TYPE_GREY:
- use_grey = true;
- break;
- }
- var pixel_data;
- var numAlphaBits = header.flags & 0xf;
- var pixel_size = header.pixel_size >> 3;
- var pixel_total = header.width * header.height * pixel_size;
- // Read palettes
- var palettes;
- if (use_pal) {
- palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
- }
- // Read LRE
- if (use_rle) {
- pixel_data = new Uint8Array(pixel_total);
- var c, count, i;
- var localOffset = 0;
- var pixels = new Uint8Array(pixel_size);
- while (offset < pixel_total && localOffset < pixel_total) {
- c = data[offset++];
- count = (c & 0x7f) + 1;
- // RLE pixels
- if (c & 0x80) {
- // Bind pixel tmp array
- for (i = 0; i < pixel_size; ++i) {
- pixels[i] = data[offset++];
- }
- // Copy pixel array
- for (i = 0; i < count; ++i) {
- pixel_data.set(pixels, localOffset + i * pixel_size);
- }
- localOffset += pixel_size * count;
- }
- else {
- count *= pixel_size;
- for (i = 0; i < count; ++i) {
- pixel_data[localOffset + i] = data[offset++];
- }
- localOffset += count;
- }
- }
- }
- else {
- pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
- }
- // Load to texture
- var x_start, y_start, x_step, y_step, y_end, x_end;
- switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
- default:
- case TGATools._ORIGIN_UL:
- x_start = 0;
- x_step = 1;
- x_end = header.width;
- y_start = 0;
- y_step = 1;
- y_end = header.height;
- break;
- case TGATools._ORIGIN_BL:
- x_start = 0;
- x_step = 1;
- x_end = header.width;
- y_start = header.height - 1;
- y_step = -1;
- y_end = -1;
- break;
- case TGATools._ORIGIN_UR:
- x_start = header.width - 1;
- x_step = -1;
- x_end = -1;
- y_start = 0;
- y_step = 1;
- y_end = header.height;
- break;
- case TGATools._ORIGIN_BR:
- x_start = header.width - 1;
- x_step = -1;
- x_end = -1;
- y_start = header.height - 1;
- y_step = -1;
- y_end = -1;
- break;
- }
- // Load the specify method
- var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
- var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
- };
- TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data, colormap = palettes;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i++) {
- color = image[i];
- imageData[(x + width * y) * 4 + 3] = 255;
- imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
- imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
- imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
- }
- }
- return imageData;
- };
- TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 2) {
- color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
- imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
- imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
- imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
- imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
- }
- }
- return imageData;
- };
- TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 3) {
- imageData[(x + width * y) * 4 + 3] = 255;
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 1];
- imageData[(x + width * y) * 4 + 0] = image[i + 2];
- }
- }
- return imageData;
- };
- TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 4) {
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 1];
- imageData[(x + width * y) * 4 + 0] = image[i + 2];
- imageData[(x + width * y) * 4 + 3] = image[i + 3];
- }
- }
- return imageData;
- };
- TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i++) {
- color = image[i];
- imageData[(x + width * y) * 4 + 0] = color;
- imageData[(x + width * y) * 4 + 1] = color;
- imageData[(x + width * y) * 4 + 2] = color;
- imageData[(x + width * y) * 4 + 3] = 255;
- }
- }
- return imageData;
- };
- TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 2) {
- imageData[(x + width * y) * 4 + 0] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 0];
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 3] = image[i + 1];
- }
- }
- return imageData;
- };
- TGATools._TYPE_NO_DATA = 0;
- TGATools._TYPE_INDEXED = 1;
- TGATools._TYPE_RGB = 2;
- TGATools._TYPE_GREY = 3;
- TGATools._TYPE_RLE_INDEXED = 9;
- TGATools._TYPE_RLE_RGB = 10;
- TGATools._TYPE_RLE_GREY = 11;
- TGATools._ORIGIN_MASK = 0x30;
- TGATools._ORIGIN_SHIFT = 0x04;
- TGATools._ORIGIN_BL = 0x00;
- TGATools._ORIGIN_BR = 0x01;
- TGATools._ORIGIN_UL = 0x02;
- TGATools._ORIGIN_UR = 0x03;
- return TGATools;
- })();
- Internals.TGATools = TGATools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SmartArray = (function () {
- function SmartArray(capacity) {
- this.length = 0;
- this._duplicateId = 0;
- this.data = new Array(capacity);
- this._id = SmartArray._GlobalId++;
- }
- SmartArray.prototype.push = function (value) {
- this.data[this.length++] = value;
- if (this.length > this.data.length) {
- this.data.length *= 2;
- }
- if (!value.__smartArrayFlags) {
- value.__smartArrayFlags = {};
- }
- value.__smartArrayFlags[this._id] = this._duplicateId;
- };
- SmartArray.prototype.pushNoDuplicate = function (value) {
- if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
- return;
- }
- this.push(value);
- };
- SmartArray.prototype.sort = function (compareFn) {
- this.data.sort(compareFn);
- };
- SmartArray.prototype.reset = function () {
- this.length = 0;
- this._duplicateId++;
- };
- SmartArray.prototype.concat = function (array) {
- if (array.length === 0) {
- return;
- }
- if (this.length + array.length > this.data.length) {
- this.data.length = (this.length + array.length) * 2;
- }
- for (var index = 0; index < array.length; index++) {
- this.data[this.length++] = (array.data || array)[index];
- }
- };
- SmartArray.prototype.concatWithNoDuplicate = function (array) {
- if (array.length === 0) {
- return;
- }
- if (this.length + array.length > this.data.length) {
- this.data.length = (this.length + array.length) * 2;
- }
- for (var index = 0; index < array.length; index++) {
- var item = (array.data || array)[index];
- this.pushNoDuplicate(item);
- }
- };
- SmartArray.prototype.indexOf = function (value) {
- var position = this.data.indexOf(value);
- if (position >= this.length) {
- return -1;
- }
- return position;
- };
- // Statics
- SmartArray._GlobalId = 0;
- return SmartArray;
- })();
- BABYLON.SmartArray = SmartArray;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SmartCollection = (function () {
- function SmartCollection(capacity) {
- if (capacity === void 0) { capacity = 10; }
- this.count = 0;
- this._initialCapacity = capacity;
- this.items = {};
- this._keys = new Array(this._initialCapacity);
- }
- SmartCollection.prototype.add = function (key, item) {
- if (this.items[key] != undefined) {
- return -1;
- }
- this.items[key] = item;
- //literal keys are always strings, but we keep source type of key in _keys array
- this._keys[this.count++] = key;
- if (this.count > this._keys.length) {
- this._keys.length *= 2;
- }
- return this.count;
- };
- SmartCollection.prototype.remove = function (key) {
- if (this.items[key] == undefined) {
- return -1;
- }
- return this.removeItemOfIndex(this.indexOf(key));
- };
- SmartCollection.prototype.removeItemOfIndex = function (index) {
- if (index < this.count && index > -1) {
- delete this.items[this._keys[index]];
- //here, shifting by hand is better optimised than .splice
- while (index < this.count) {
- this._keys[index] = this._keys[index + 1];
- index++;
- }
- }
- else {
- return -1;
- }
- return --this.count;
- };
- SmartCollection.prototype.indexOf = function (key) {
- for (var i = 0; i !== this.count; i++) {
- if (this._keys[i] === key) {
- return i;
- }
- }
- return -1;
- };
- SmartCollection.prototype.item = function (key) {
- return this.items[key];
- };
- SmartCollection.prototype.getAllKeys = function () {
- if (this.count > 0) {
- var keys = new Array(this.count);
- for (var i = 0; i < this.count; i++) {
- keys[i] = this._keys[i];
- }
- return keys;
- }
- else {
- return undefined;
- }
- };
- SmartCollection.prototype.getKeyByIndex = function (index) {
- if (index < this.count && index > -1) {
- return this._keys[index];
- }
- else {
- return undefined;
- }
- };
- SmartCollection.prototype.getItemByIndex = function (index) {
- if (index < this.count && index > -1) {
- return this.items[this._keys[index]];
- }
- else {
- return undefined;
- }
- };
- SmartCollection.prototype.empty = function () {
- if (this.count > 0) {
- this.count = 0;
- this.items = {};
- this._keys = new Array(this._initialCapacity);
- }
- };
- SmartCollection.prototype.forEach = function (block) {
- var key;
- for (key in this.items) {
- if (this.items.hasOwnProperty(key)) {
- block(this.items[key]);
- }
- }
- };
- return SmartCollection;
- })();
- BABYLON.SmartCollection = SmartCollection;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Screenshots
- var screenshotCanvas;
- var cloneValue = function (source, destinationObject) {
- if (!source)
- return null;
- if (source instanceof BABYLON.Mesh) {
- return null;
- }
- if (source instanceof BABYLON.SubMesh) {
- return source.clone(destinationObject);
- }
- else if (source.clone) {
- return source.clone();
- }
- return null;
- };
- var Tools = (function () {
- function Tools() {
- }
- Tools.Instantiate = function (className) {
- var arr = className.split(".");
- var fn = (window || this);
- for (var i = 0, len = arr.length; i < len; i++) {
- fn = fn[arr[i]];
- }
- if (typeof fn !== "function") {
- return null;
- }
- return fn;
- };
- Tools.GetConstructorName = function (obj) {
- var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
- var cname = str.match(/function\s(\w*)/)[1];
- var aliases = ["", "anonymous", "Anonymous"];
- return aliases.indexOf(cname) > -1 ? "Function" : cname;
- };
- Tools.ToHex = function (i) {
- var str = i.toString(16);
- if (i <= 15) {
- return ("0" + str).toUpperCase();
- }
- return str.toUpperCase();
- };
- Tools.SetImmediate = function (action) {
- if (window.setImmediate) {
- window.setImmediate(action);
- }
- else {
- setTimeout(action, 1);
- }
- };
- Tools.IsExponentOfTwo = function (value) {
- var count = 1;
- do {
- count *= 2;
- } while (count < value);
- return count === value;
- };
- Tools.GetExponentOfTwo = function (value, max) {
- var count = 1;
- do {
- count *= 2;
- } while (count < value);
- if (count > max)
- count = max;
- return count;
- };
- Tools.GetFilename = function (path) {
- var index = path.lastIndexOf("/");
- if (index < 0)
- return path;
- return path.substring(index + 1);
- };
- Tools.GetDOMTextContent = function (element) {
- var result = "";
- var child = element.firstChild;
- while (child) {
- if (child.nodeType === 3) {
- result += child.textContent;
- }
- child = child.nextSibling;
- }
- return result;
- };
- Tools.ToDegrees = function (angle) {
- return angle * 180 / Math.PI;
- };
- Tools.ToRadians = function (angle) {
- return angle * Math.PI / 180;
- };
- Tools.EncodeArrayBufferTobase64 = function (buffer) {
- var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- var bytes = new Uint8Array(buffer);
- while (i < bytes.length) {
- chr1 = bytes[i++];
- chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
- chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- }
- else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
- keyStr.charAt(enc3) + keyStr.charAt(enc4);
- }
- return "data:image/png;base64," + output;
- };
- Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
- var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = indexStart; index < indexStart + indexCount; index++) {
- var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
- minimum = BABYLON.Vector3.Minimize(current, minimum);
- maximum = BABYLON.Vector3.Maximize(current, maximum);
- }
- return {
- minimum: minimum,
- maximum: maximum
- };
- };
- Tools.ExtractMinAndMax = function (positions, start, count) {
- var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = start; index < start + count; index++) {
- var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
- minimum = BABYLON.Vector3.Minimize(current, minimum);
- maximum = BABYLON.Vector3.Maximize(current, maximum);
- }
- return {
- minimum: minimum,
- maximum: maximum
- };
- };
- Tools.MakeArray = function (obj, allowsNullUndefined) {
- if (allowsNullUndefined !== true && (obj === undefined || obj == null))
- return undefined;
- return Array.isArray(obj) ? obj : [obj];
- };
- // Misc.
- Tools.GetPointerPrefix = function () {
- var eventPrefix = "pointer";
- // Check if pointer events are supported
- if (!window.PointerEvent && !navigator.pointerEnabled) {
- eventPrefix = "mouse";
- }
- return eventPrefix;
- };
- Tools.QueueNewFrame = function (func) {
- if (window.requestAnimationFrame)
- window.requestAnimationFrame(func);
- else if (window.msRequestAnimationFrame)
- window.msRequestAnimationFrame(func);
- else if (window.webkitRequestAnimationFrame)
- window.webkitRequestAnimationFrame(func);
- else if (window.mozRequestAnimationFrame)
- window.mozRequestAnimationFrame(func);
- else if (window.oRequestAnimationFrame)
- window.oRequestAnimationFrame(func);
- else {
- window.setTimeout(func, 16);
- }
- };
- Tools.RequestFullscreen = function (element) {
- if (element.requestFullscreen)
- element.requestFullscreen();
- else if (element.msRequestFullscreen)
- element.msRequestFullscreen();
- else if (element.webkitRequestFullscreen)
- element.webkitRequestFullscreen();
- else if (element.mozRequestFullScreen)
- element.mozRequestFullScreen();
- };
- Tools.ExitFullscreen = function () {
- if (document.exitFullscreen) {
- document.exitFullscreen();
- }
- else if (document.mozCancelFullScreen) {
- document.mozCancelFullScreen();
- }
- else if (document.webkitCancelFullScreen) {
- document.webkitCancelFullScreen();
- }
- else if (document.msCancelFullScreen) {
- document.msCancelFullScreen();
- }
- };
- // External files
- Tools.CleanUrl = function (url) {
- url = url.replace(/#/mg, "%23");
- return url;
- };
- Tools.LoadImage = function (url, onload, onerror, database) {
- if (url instanceof ArrayBuffer) {
- url = Tools.EncodeArrayBufferTobase64(url);
- }
- url = Tools.CleanUrl(url);
- var img = new Image();
- if (url.substr(0, 5) !== "data:") {
- if (Tools.CorsBehavior) {
- switch (typeof (Tools.CorsBehavior)) {
- case "function":
- var result = Tools.CorsBehavior(url);
- if (result) {
- img.crossOrigin = result;
- }
- break;
- case "string":
- default:
- img.crossOrigin = Tools.CorsBehavior;
- break;
- }
- }
- }
- img.onload = function () {
- onload(img);
- };
- img.onerror = function (err) {
- Tools.Error("Error while trying to load texture: " + url);
- if (Tools.UseFallbackTexture) {
- img.src = "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";
- onload(img);
- }
- else {
- onerror();
- }
- };
- var noIndexedDB = function () {
- img.src = url;
- };
- var loadFromIndexedDB = function () {
- database.loadImageFromDB(url, img);
- };
- //ANY database to do!
- if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
- database.openAsync(loadFromIndexedDB, noIndexedDB);
- }
- else {
- if (url.indexOf("file:") === -1) {
- noIndexedDB();
- }
- else {
- try {
- var textureName = url.substring(5);
- var blobURL;
- try {
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
- }
- catch (ex) {
- // Chrome doesn't support oneTimeOnly parameter
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
- }
- img.src = blobURL;
- }
- catch (e) {
- img.src = null;
- }
- }
- }
- return img;
- };
- //ANY
- Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
- url = Tools.CleanUrl(url);
- var noIndexedDB = function () {
- var request = new XMLHttpRequest();
- var loadUrl = Tools.BaseUrl + url;
- request.open('GET', loadUrl, true);
- if (useArrayBuffer) {
- request.responseType = "arraybuffer";
- }
- request.onprogress = progressCallBack;
- request.onreadystatechange = function () {
- if (request.readyState === 4) {
- if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
- callback(!useArrayBuffer ? request.responseText : request.response);
- }
- else {
- if (onError) {
- onError();
- }
- else {
- throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
- }
- }
- }
- };
- request.send(null);
- };
- var loadFromIndexedDB = function () {
- database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
- };
- if (url.indexOf("file:") !== -1) {
- var fileName = url.substring(5);
- Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
- }
- else {
- // Caching all files
- if (database && database.enableSceneOffline) {
- database.openAsync(loadFromIndexedDB, noIndexedDB);
- }
- else {
- noIndexedDB();
- }
- }
- };
- Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
- var reader = new FileReader();
- reader.onload = function (e) {
- //target doesn't have result from ts 1.3
- callback(e.target['result']);
- };
- reader.onprogress = progressCallback;
- reader.readAsDataURL(fileToLoad);
- };
- Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
- var reader = new FileReader();
- reader.onerror = function (e) {
- Tools.Log("Error while reading file: " + fileToLoad.name);
- callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
- };
- reader.onload = function (e) {
- //target doesn't have result from ts 1.3
- callback(e.target['result']);
- };
- reader.onprogress = progressCallBack;
- if (!useArrayBuffer) {
- // Asynchronous read
- reader.readAsText(fileToLoad);
- }
- else {
- reader.readAsArrayBuffer(fileToLoad);
- }
- };
- //returns a downloadable url to a file content.
- Tools.FileAsURL = function (content) {
- var fileBlob = new Blob([content]);
- var url = window.URL || window.webkitURL;
- var link = url.createObjectURL(fileBlob);
- return link;
- };
- // Misc.
- Tools.Clamp = function (value, min, max) {
- if (min === void 0) { min = 0; }
- if (max === void 0) { max = 1; }
- return Math.min(max, Math.max(min, value));
- };
- // Returns -1 when value is a negative number and
- // +1 when value is a positive number.
- Tools.Sign = function (value) {
- value = +value; // convert to a number
- if (value === 0 || isNaN(value))
- return value;
- return value > 0 ? 1 : -1;
- };
- Tools.Format = function (value, decimals) {
- if (decimals === void 0) { decimals = 2; }
- return value.toFixed(decimals);
- };
- Tools.CheckExtends = function (v, min, max) {
- if (v.x < min.x)
- min.x = v.x;
- if (v.y < min.y)
- min.y = v.y;
- if (v.z < min.z)
- min.z = v.z;
- if (v.x > max.x)
- max.x = v.x;
- if (v.y > max.y)
- max.y = v.y;
- if (v.z > max.z)
- max.z = v.z;
- };
- Tools.WithinEpsilon = function (a, b, epsilon) {
- if (epsilon === void 0) { epsilon = 1.401298E-45; }
- var num = a - b;
- return -epsilon <= num && num <= epsilon;
- };
- Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
- for (var prop in source) {
- if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
- continue;
- }
- if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
- continue;
- }
- var sourceValue = source[prop];
- var typeOfSourceValue = typeof sourceValue;
- if (typeOfSourceValue === "function") {
- continue;
- }
- if (typeOfSourceValue === "object") {
- if (sourceValue instanceof Array) {
- destination[prop] = [];
- if (sourceValue.length > 0) {
- if (typeof sourceValue[0] == "object") {
- for (var index = 0; index < sourceValue.length; index++) {
- var clonedValue = cloneValue(sourceValue[index], destination);
- if (destination[prop].indexOf(clonedValue) === -1) {
- destination[prop].push(clonedValue);
- }
- }
- }
- else {
- destination[prop] = sourceValue.slice(0);
- }
- }
- }
- else {
- destination[prop] = cloneValue(sourceValue, destination);
- }
- }
- else {
- destination[prop] = sourceValue;
- }
- }
- };
- Tools.IsEmpty = function (obj) {
- for (var i in obj) {
- return false;
- }
- return true;
- };
- Tools.RegisterTopRootEvents = function (events) {
- for (var index = 0; index < events.length; index++) {
- var event = events[index];
- window.addEventListener(event.name, event.handler, false);
- try {
- if (window.parent) {
- window.parent.addEventListener(event.name, event.handler, false);
- }
- }
- catch (e) {
- }
- }
- };
- Tools.UnregisterTopRootEvents = function (events) {
- for (var index = 0; index < events.length; index++) {
- var event = events[index];
- window.removeEventListener(event.name, event.handler);
- try {
- if (window.parent) {
- window.parent.removeEventListener(event.name, event.handler);
- }
- }
- catch (e) {
- }
- }
- };
- Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
- // Read the contents of the framebuffer
- var numberOfChannelsByLine = width * 4;
- var halfHeight = height / 2;
- //Reading datas from WebGL
- var data = engine.readPixels(0, 0, width, height);
- //To flip image on Y axis.
- for (var i = 0; i < halfHeight; i++) {
- for (var j = 0; j < numberOfChannelsByLine; j++) {
- var currentCell = j + i * numberOfChannelsByLine;
- var targetLine = height - i - 1;
- var targetCell = j + targetLine * numberOfChannelsByLine;
- var temp = data[currentCell];
- data[currentCell] = data[targetCell];
- data[targetCell] = temp;
- }
- }
- // Create a 2D canvas to store the result
- if (!screenshotCanvas) {
- screenshotCanvas = document.createElement('canvas');
- }
- screenshotCanvas.width = width;
- screenshotCanvas.height = height;
- var context = screenshotCanvas.getContext('2d');
- // Copy the pixels to a 2D canvas
- var imageData = context.createImageData(width, height);
- //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
- var castData = imageData.data;
- castData.set(data);
- context.putImageData(imageData, 0, 0);
- var base64Image = screenshotCanvas.toDataURL();
- if (successCallback) {
- successCallback(base64Image);
- }
- else {
- //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
- if (("download" in document.createElement("a"))) {
- var a = window.document.createElement("a");
- a.href = base64Image;
- var date = new Date();
- var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
- a.setAttribute("download", "screenshot_" + stringDate + ".png");
- window.document.body.appendChild(a);
- a.addEventListener("click", function () {
- a.parentElement.removeChild(a);
- });
- a.click();
- }
- else {
- var newWindow = window.open("");
- var img = newWindow.document.createElement("img");
- img.src = base64Image;
- newWindow.document.body.appendChild(img);
- }
- }
- };
- Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
- var width;
- var height;
- //If a precision value is specified
- if (size.precision) {
- width = Math.round(engine.getRenderWidth() * size.precision);
- height = Math.round(width / engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (size.width && size.height) {
- width = size.width;
- height = size.height;
- }
- else if (size.width && !size.height) {
- width = size.width;
- height = Math.round(width / engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (size.height && !size.width) {
- height = size.height;
- width = Math.round(height * engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (!isNaN(size)) {
- height = size;
- width = size;
- }
- else {
- Tools.Error("Invalid 'size' parameter !");
- return;
- }
- var scene = camera.getScene();
- var previousCamera = null;
- if (scene.activeCamera !== camera) {
- previousCamera = scene.activeCamera;
- scene.activeCamera = camera;
- }
- //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
- var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
- texture.renderList = scene.meshes;
- texture.onAfterRender = function () {
- Tools.DumpFramebuffer(width, height, engine, successCallback);
- };
- scene.incrementRenderId();
- texture.render(true);
- texture.dispose();
- if (previousCamera) {
- scene.activeCamera = previousCamera;
- }
- camera.getProjectionMatrix(true); // Force cache refresh;
- };
- // XHR response validator for local file scenario
- Tools.ValidateXHRData = function (xhr, dataType) {
- // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
- if (dataType === void 0) { dataType = 7; }
- try {
- if (dataType & 1) {
- if (xhr.responseText && xhr.responseText.length > 0) {
- return true;
- }
- else if (dataType === 1) {
- return false;
- }
- }
- if (dataType & 2) {
- // Check header width and height since there is no "TGA" magic number
- var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
- if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
- return true;
- }
- else if (dataType === 2) {
- return false;
- }
- }
- if (dataType & 4) {
- // Check for the "DDS" magic number
- var ddsHeader = new Uint8Array(xhr.response, 0, 3);
- if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
- return true;
- }
- else {
- return false;
- }
- }
- }
- catch (e) {
- }
- return false;
- };
- Object.defineProperty(Tools, "NoneLogLevel", {
- get: function () {
- return Tools._NoneLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "MessageLogLevel", {
- get: function () {
- return Tools._MessageLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "WarningLogLevel", {
- get: function () {
- return Tools._WarningLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "ErrorLogLevel", {
- get: function () {
- return Tools._ErrorLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "AllLogLevel", {
- get: function () {
- return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Tools._AddLogEntry = function (entry) {
- Tools._LogCache = entry + Tools._LogCache;
- if (Tools.OnNewCacheEntry) {
- Tools.OnNewCacheEntry(entry);
- }
- };
- Tools._FormatMessage = function (message) {
- var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
- var date = new Date();
- return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
- };
- Tools._LogDisabled = function (message) {
- // nothing to do
- };
- Tools._LogEnabled = function (message) {
- var formattedMessage = Tools._FormatMessage(message);
- console.log("BJS - " + formattedMessage);
- var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Tools._WarnDisabled = function (message) {
- // nothing to do
- };
- Tools._WarnEnabled = function (message) {
- var formattedMessage = Tools._FormatMessage(message);
- console.warn("BJS - " + formattedMessage);
- var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Tools._ErrorDisabled = function (message) {
- // nothing to do
- };
- Tools._ErrorEnabled = function (message) {
- Tools.errorsCount++;
- var formattedMessage = Tools._FormatMessage(message);
- console.error("BJS - " + formattedMessage);
- var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Object.defineProperty(Tools, "LogCache", {
- get: function () {
- return Tools._LogCache;
- },
- enumerable: true,
- configurable: true
- });
- Tools.ClearLogCache = function () {
- Tools._LogCache = "";
- Tools.errorsCount = 0;
- };
- Object.defineProperty(Tools, "LogLevels", {
- set: function (level) {
- if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
- Tools.Log = Tools._LogEnabled;
- }
- else {
- Tools.Log = Tools._LogDisabled;
- }
- if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
- Tools.Warn = Tools._WarnEnabled;
- }
- else {
- Tools.Warn = Tools._WarnDisabled;
- }
- if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
- Tools.Error = Tools._ErrorEnabled;
- }
- else {
- Tools.Error = Tools._ErrorDisabled;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
- get: function () {
- return Tools._PerformanceNoneLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
- get: function () {
- return Tools._PerformanceUserMarkLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
- get: function () {
- return Tools._PerformanceConsoleLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceLogLevel", {
- set: function (level) {
- if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
- Tools.StartPerformanceCounter = Tools._StartUserMark;
- Tools.EndPerformanceCounter = Tools._EndUserMark;
- return;
- }
- if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
- Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
- Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
- return;
- }
- Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- },
- enumerable: true,
- configurable: true
- });
- Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
- };
- Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
- };
- Tools._StartUserMark = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition || !Tools._performance.mark) {
- return;
- }
- Tools._performance.mark(counterName + "-Begin");
- };
- Tools._EndUserMark = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition || !Tools._performance.mark) {
- return;
- }
- Tools._performance.mark(counterName + "-End");
- Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
- };
- Tools._StartPerformanceConsole = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition) {
- return;
- }
- Tools._StartUserMark(counterName, condition);
- if (console.time) {
- console.time(counterName);
- }
- };
- Tools._EndPerformanceConsole = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition) {
- return;
- }
- Tools._EndUserMark(counterName, condition);
- if (console.time) {
- console.timeEnd(counterName);
- }
- };
- Object.defineProperty(Tools, "Now", {
- get: function () {
- if (window.performance && window.performance.now) {
- return window.performance.now();
- }
- return new Date().getTime();
- },
- enumerable: true,
- configurable: true
- });
- Tools.BaseUrl = "";
- Tools.CorsBehavior = "anonymous";
- Tools.UseFallbackTexture = true;
- // Logs
- Tools._NoneLogLevel = 0;
- Tools._MessageLogLevel = 1;
- Tools._WarningLogLevel = 2;
- Tools._ErrorLogLevel = 4;
- Tools._LogCache = "";
- Tools.errorsCount = 0;
- Tools.Log = Tools._LogEnabled;
- Tools.Warn = Tools._WarnEnabled;
- Tools.Error = Tools._ErrorEnabled;
- // Performances
- Tools._PerformanceNoneLogLevel = 0;
- Tools._PerformanceUserMarkLogLevel = 1;
- Tools._PerformanceConsoleLogLevel = 2;
- Tools._performance = window.performance;
- Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- return Tools;
- })();
- BABYLON.Tools = Tools;
- /**
- * An implementation of a loop for asynchronous functions.
- */
- var AsyncLoop = (function () {
- /**
- * Constroctor.
- * @param iterations the number of iterations.
- * @param _fn the function to run each iteration
- * @param _successCallback the callback that will be called upon succesful execution
- * @param offset starting offset.
- */
- function AsyncLoop(iterations, _fn, _successCallback, offset) {
- if (offset === void 0) { offset = 0; }
- this.iterations = iterations;
- this._fn = _fn;
- this._successCallback = _successCallback;
- this.index = offset - 1;
- this._done = false;
- }
- /**
- * Execute the next iteration. Must be called after the last iteration was finished.
- */
- AsyncLoop.prototype.executeNext = function () {
- if (!this._done) {
- if (this.index + 1 < this.iterations) {
- ++this.index;
- this._fn(this);
- }
- else {
- this.breakLoop();
- }
- }
- };
- /**
- * Break the loop and run the success callback.
- */
- AsyncLoop.prototype.breakLoop = function () {
- this._done = true;
- this._successCallback();
- };
- /**
- * Helper function
- */
- AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
- if (offset === void 0) { offset = 0; }
- var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
- loop.executeNext();
- return loop;
- };
- /**
- * A for-loop that will run a given number of iterations synchronous and the rest async.
- * @param iterations total number of iterations
- * @param syncedIterations number of synchronous iterations in each async iteration.
- * @param fn the function to call each iteration.
- * @param callback a success call back that will be called when iterating stops.
- * @param breakFunction a break condition (optional)
- * @param timeout timeout settings for the setTimeout function. default - 0.
- * @constructor
- */
- AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
- if (timeout === void 0) { timeout = 0; }
- AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
- if (breakFunction && breakFunction())
- loop.breakLoop();
- else {
- setTimeout(function () {
- for (var i = 0; i < syncedIterations; ++i) {
- var iteration = (loop.index * syncedIterations) + i;
- if (iteration >= iterations)
- break;
- fn(iteration);
- if (breakFunction && breakFunction()) {
- loop.breakLoop();
- break;
- }
- }
- loop.executeNext();
- }, timeout);
- }
- }, callback);
- };
- return AsyncLoop;
- })();
- BABYLON.AsyncLoop = AsyncLoop;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var _DepthCullingState = (function () {
- function _DepthCullingState() {
- this._isDepthTestDirty = false;
- this._isDepthMaskDirty = false;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- }
- Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
- get: function () {
- return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
- get: function () {
- return this._zOffset;
- },
- set: function (value) {
- if (this._zOffset === value) {
- return;
- }
- this._zOffset = value;
- this._isZOffsetDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
- get: function () {
- return this._cullFace;
- },
- set: function (value) {
- if (this._cullFace === value) {
- return;
- }
- this._cullFace = value;
- this._isCullFaceDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "cull", {
- get: function () {
- return this._cull;
- },
- set: function (value) {
- if (this._cull === value) {
- return;
- }
- this._cull = value;
- this._isCullDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
- get: function () {
- return this._depthFunc;
- },
- set: function (value) {
- if (this._depthFunc === value) {
- return;
- }
- this._depthFunc = value;
- this._isDepthFuncDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
- get: function () {
- return this._depthMask;
- },
- set: function (value) {
- if (this._depthMask === value) {
- return;
- }
- this._depthMask = value;
- this._isDepthMaskDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
- get: function () {
- return this._depthTest;
- },
- set: function (value) {
- if (this._depthTest === value) {
- return;
- }
- this._depthTest = value;
- this._isDepthTestDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _DepthCullingState.prototype.reset = function () {
- this._depthMask = true;
- this._depthTest = true;
- this._depthFunc = null;
- this._cull = null;
- this._cullFace = null;
- this._zOffset = 0;
- this._isDepthTestDirty = true;
- this._isDepthMaskDirty = true;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- };
- _DepthCullingState.prototype.apply = function (gl) {
- if (!this.isDirty) {
- return;
- }
- // Cull
- if (this._isCullDirty) {
- if (this.cull) {
- gl.enable(gl.CULL_FACE);
- }
- else {
- gl.disable(gl.CULL_FACE);
- }
- this._isCullDirty = false;
- }
- // Cull face
- if (this._isCullFaceDirty) {
- gl.cullFace(this.cullFace);
- this._isCullFaceDirty = false;
- }
- // Depth mask
- if (this._isDepthMaskDirty) {
- gl.depthMask(this.depthMask);
- this._isDepthMaskDirty = false;
- }
- // Depth test
- if (this._isDepthTestDirty) {
- if (this.depthTest) {
- gl.enable(gl.DEPTH_TEST);
- }
- else {
- gl.disable(gl.DEPTH_TEST);
- }
- this._isDepthTestDirty = false;
- }
- // Depth func
- if (this._isDepthFuncDirty) {
- gl.depthFunc(this.depthFunc);
- this._isDepthFuncDirty = false;
- }
- // zOffset
- if (this._isZOffsetDirty) {
- if (this.zOffset) {
- gl.enable(gl.POLYGON_OFFSET_FILL);
- gl.polygonOffset(this.zOffset, 0);
- }
- else {
- gl.disable(gl.POLYGON_OFFSET_FILL);
- }
- this._isZOffsetDirty = false;
- }
- };
- return _DepthCullingState;
- })();
- BABYLON._DepthCullingState = _DepthCullingState;
- var _AlphaState = (function () {
- function _AlphaState() {
- this._isAlphaBlendDirty = false;
- this._isBlendFunctionParametersDirty = false;
- this._alphaBlend = false;
- this._blendFunctionParameters = new Array(4);
- }
- Object.defineProperty(_AlphaState.prototype, "isDirty", {
- get: function () {
- return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
- get: function () {
- return this._alphaBlend;
- },
- set: function (value) {
- if (this._alphaBlend === value) {
- return;
- }
- this._alphaBlend = value;
- this._isAlphaBlendDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
- if (this._blendFunctionParameters[0] === value0 &&
- this._blendFunctionParameters[1] === value1 &&
- this._blendFunctionParameters[2] === value2 &&
- this._blendFunctionParameters[3] === value3) {
- return;
- }
- this._blendFunctionParameters[0] = value0;
- this._blendFunctionParameters[1] = value1;
- this._blendFunctionParameters[2] = value2;
- this._blendFunctionParameters[3] = value3;
- this._isBlendFunctionParametersDirty = true;
- };
- _AlphaState.prototype.reset = function () {
- this._alphaBlend = false;
- this._blendFunctionParameters[0] = null;
- this._blendFunctionParameters[1] = null;
- this._blendFunctionParameters[2] = null;
- this._blendFunctionParameters[3] = null;
- this._isAlphaBlendDirty = true;
- this._isBlendFunctionParametersDirty = false;
- };
- _AlphaState.prototype.apply = function (gl) {
- if (!this.isDirty) {
- return;
- }
- // Alpha blend
- if (this._isAlphaBlendDirty) {
- if (this._alphaBlend) {
- gl.enable(gl.BLEND);
- }
- else {
- gl.disable(gl.BLEND);
- }
- this._isAlphaBlendDirty = false;
- }
- // Alpha function
- if (this._isBlendFunctionParametersDirty) {
- gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
- this._isBlendFunctionParametersDirty = false;
- }
- };
- return _AlphaState;
- })();
- BABYLON._AlphaState = _AlphaState;
- var compileShader = function (gl, source, type, defines) {
- var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
- gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
- gl.compileShader(shader);
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
- throw new Error(gl.getShaderInfoLog(shader));
- }
- return shader;
- };
- var getWebGLTextureType = function (gl, type) {
- var textureType = gl.UNSIGNED_BYTE;
- if (type === Engine.TEXTURETYPE_FLOAT)
- textureType = gl.FLOAT;
- return textureType;
- };
- var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.LINEAR;
- }
- }
- else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.LINEAR;
- }
- }
- else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.NEAREST;
- }
- }
- return {
- min: minFilter,
- mag: magFilter
- };
- };
- var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- var engine = scene.getEngine();
- var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
- var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = potWidth;
- texture._height = potHeight;
- texture.isReady = true;
- processFunction(potWidth, potHeight);
- var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- if (!noMipmap && !isCompressed) {
- gl.generateMipmap(gl.TEXTURE_2D);
- }
- gl.bindTexture(gl.TEXTURE_2D, null);
- engine.resetTextureCache();
- scene._removePendingData(texture);
- if (onLoad) {
- onLoad();
- }
- };
- var partialLoad = function (url, index, loadedImages, scene, onfinish) {
- var img;
- var onload = function () {
- loadedImages[index] = img;
- loadedImages._internalCount++;
- scene._removePendingData(img);
- if (loadedImages._internalCount === 6) {
- onfinish(loadedImages);
- }
- };
- var onerror = function () {
- scene._removePendingData(img);
- };
- img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
- scene._addPendingData(img);
- };
- var cascadeLoad = function (rootUrl, scene, onfinish, files) {
- var loadedImages = [];
- loadedImages._internalCount = 0;
- for (var index = 0; index < 6; index++) {
- partialLoad(files[index], index, loadedImages, scene, onfinish);
- }
- };
- var EngineCapabilities = (function () {
- function EngineCapabilities() {
- }
- return EngineCapabilities;
- })();
- BABYLON.EngineCapabilities = EngineCapabilities;
- /**
- * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
- */
- var Engine = (function () {
- /**
- * @constructor
- * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
- * @param {boolean} [antialias] - enable antialias
- * @param options - further options to be sent to the getContext function
- */
- function Engine(canvas, antialias, options, adaptToDeviceRatio) {
- var _this = this;
- if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
- // Public members
- this.isFullscreen = false;
- this.isPointerLock = false;
- this.cullBackFaces = true;
- this.renderEvenInBackground = true;
- // To enable/disable IDB support and avoid XHR on .manifest
- this.enableOfflineSupport = true;
- this.scenes = new Array();
- this._windowIsBackground = false;
- this._webGLVersion = "1.0";
- this._drawCalls = 0;
- this._renderingQueueLaunched = false;
- this._activeRenderLoops = [];
- // FPS
- this.fpsRange = 60;
- this.previousFramesDuration = [];
- this.fps = 60;
- this.deltaTime = 0;
- // States
- this._depthCullingState = new _DepthCullingState();
- this._alphaState = new _AlphaState();
- this._alphaMode = Engine.ALPHA_DISABLE;
- // Cache
- this._loadedTexturesCache = new Array();
- this._maxTextureChannels = 16;
- this._activeTexturesCache = new Array(this._maxTextureChannels);
- this._compiledEffects = {};
- this._uintIndicesCurrentlySet = false;
- this._renderingCanvas = canvas;
- options = options || {};
- options.antialias = antialias;
- if (options.preserveDrawingBuffer === undefined) {
- options.preserveDrawingBuffer = false;
- }
- // GL
- //try {
- // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
- // if (this._gl) {
- // this._webGLVersion = "2.0";
- // }
- //} catch (e) {
- // // Do nothing
- //}
- if (!this._gl) {
- try {
- this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
- }
- catch (e) {
- throw new Error("WebGL not supported");
- }
- }
- if (!this._gl) {
- throw new Error("WebGL not supported");
- }
- this._onBlur = function () {
- _this._windowIsBackground = true;
- };
- this._onFocus = function () {
- _this._windowIsBackground = false;
- };
- window.addEventListener("blur", this._onBlur);
- window.addEventListener("focus", this._onFocus);
- // Viewport
- this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
- this.resize();
- // Caps
- this._caps = new EngineCapabilities();
- this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
- this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
- this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
- this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
- // Infos
- this._glVersion = this._gl.getParameter(this._gl.VERSION);
- var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
- if (rendererInfo != null) {
- this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
- this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
- }
- if (!this._glVendor) {
- this._glVendor = "Unknown vendor";
- }
- if (!this._glRenderer) {
- this._glRenderer = "Unknown renderer";
- }
- // Extensions
- this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
- this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
- this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
- 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');
- this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
- this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
- this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
- this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
- this._caps.highPrecisionShaderSupported = true;
- this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
- this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
- this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
- if (this._gl.getShaderPrecisionFormat) {
- var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
- this._caps.highPrecisionShaderSupported = highp.precision !== 0;
- }
- // Depth buffer
- this.setDepthBuffer(true);
- this.setDepthFunctionToLessOrEqual();
- this.setDepthWrite(true);
- // Fullscreen
- this._onFullscreenChange = function () {
- if (document.fullscreen !== undefined) {
- _this.isFullscreen = document.fullscreen;
- }
- else if (document.mozFullScreen !== undefined) {
- _this.isFullscreen = document.mozFullScreen;
- }
- else if (document.webkitIsFullScreen !== undefined) {
- _this.isFullscreen = document.webkitIsFullScreen;
- }
- else if (document.msIsFullScreen !== undefined) {
- _this.isFullscreen = document.msIsFullScreen;
- }
- // Pointer lock
- if (_this.isFullscreen && _this._pointerLockRequested) {
- canvas.requestPointerLock = canvas.requestPointerLock ||
- canvas.msRequestPointerLock ||
- canvas.mozRequestPointerLock ||
- canvas.webkitRequestPointerLock;
- if (canvas.requestPointerLock) {
- canvas.requestPointerLock();
- }
- }
- };
- document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
- // Pointer lock
- this._onPointerLockChange = function () {
- _this.isPointerLock = (document.mozPointerLockElement === canvas ||
- document.webkitPointerLockElement === canvas ||
- document.msPointerLockElement === canvas ||
- document.pointerLockElement === canvas);
- };
- document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
- if (BABYLON.AudioEngine && !Engine.audioEngine) {
- Engine.audioEngine = new BABYLON.AudioEngine();
- }
- //default loading screen
- this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
- BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
- }
- Object.defineProperty(Engine, "ALPHA_DISABLE", {
- get: function () {
- return Engine._ALPHA_DISABLE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_ONEONE", {
- get: function () {
- return Engine._ALPHA_ONEONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_ADD", {
- get: function () {
- return Engine._ALPHA_ADD;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_COMBINE", {
- get: function () {
- return Engine._ALPHA_COMBINE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
- get: function () {
- return Engine._ALPHA_SUBTRACT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
- get: function () {
- return Engine._ALPHA_MULTIPLY;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
- get: function () {
- return Engine._ALPHA_MAXIMIZED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
- get: function () {
- return Engine._DELAYLOADSTATE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
- get: function () {
- return Engine._DELAYLOADSTATE_LOADED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
- get: function () {
- return Engine._DELAYLOADSTATE_LOADING;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
- get: function () {
- return Engine._DELAYLOADSTATE_NOTLOADED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
- get: function () {
- return Engine._TEXTUREFORMAT_ALPHA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
- get: function () {
- return Engine._TEXTUREFORMAT_LUMINANCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
- get: function () {
- return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
- get: function () {
- return Engine._TEXTUREFORMAT_RGB;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
- get: function () {
- return Engine._TEXTUREFORMAT_RGBA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
- get: function () {
- return Engine._TEXTURETYPE_UNSIGNED_INT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
- get: function () {
- return Engine._TEXTURETYPE_FLOAT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "Version", {
- get: function () {
- return "2.4.0-alpha";
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "webGLVersion", {
- get: function () {
- return this._webGLVersion;
- },
- enumerable: true,
- configurable: true
- });
- Engine.prototype._prepareWorkingCanvas = function () {
- if (this._workingCanvas) {
- return;
- }
- this._workingCanvas = document.createElement("canvas");
- this._workingContext = this._workingCanvas.getContext("2d");
- };
- Engine.prototype.resetTextureCache = function () {
- for (var index = 0; index < this._maxTextureChannels; index++) {
- this._activeTexturesCache[index] = null;
- }
- };
- Engine.prototype.getGlInfo = function () {
- return {
- vendor: this._glVendor,
- renderer: this._glRenderer,
- version: this._glVersion
- };
- };
- Engine.prototype.getAspectRatio = function (camera, useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- var viewport = camera.viewport;
- return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
- };
- Engine.prototype.getRenderWidth = function (useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._width;
- }
- return this._renderingCanvas.width;
- };
- Engine.prototype.getRenderHeight = function (useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._height;
- }
- return this._renderingCanvas.height;
- };
- Engine.prototype.getRenderingCanvas = function () {
- return this._renderingCanvas;
- };
- Engine.prototype.getRenderingCanvasClientRect = function () {
- return this._renderingCanvas.getBoundingClientRect();
- };
- Engine.prototype.setHardwareScalingLevel = function (level) {
- this._hardwareScalingLevel = level;
- this.resize();
- };
- Engine.prototype.getHardwareScalingLevel = function () {
- return this._hardwareScalingLevel;
- };
- Engine.prototype.getLoadedTexturesCache = function () {
- return this._loadedTexturesCache;
- };
- Engine.prototype.getCaps = function () {
- return this._caps;
- };
- Object.defineProperty(Engine.prototype, "drawCalls", {
- get: function () {
- return this._drawCalls;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- Engine.prototype.resetDrawCalls = function () {
- this._drawCalls = 0;
- };
- Engine.prototype.setDepthFunctionToGreater = function () {
- this._depthCullingState.depthFunc = this._gl.GREATER;
- };
- Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
- this._depthCullingState.depthFunc = this._gl.GEQUAL;
- };
- Engine.prototype.setDepthFunctionToLess = function () {
- this._depthCullingState.depthFunc = this._gl.LESS;
- };
- Engine.prototype.setDepthFunctionToLessOrEqual = function () {
- this._depthCullingState.depthFunc = this._gl.LEQUAL;
- };
- /**
- * stop executing a render loop function and remove it from the execution array
- * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
- */
- Engine.prototype.stopRenderLoop = function (renderFunction) {
- if (!renderFunction) {
- this._activeRenderLoops = [];
- return;
- }
- var index = this._activeRenderLoops.indexOf(renderFunction);
- if (index >= 0) {
- this._activeRenderLoops.splice(index, 1);
- }
- };
- Engine.prototype._renderLoop = function () {
- var shouldRender = true;
- if (!this.renderEvenInBackground && this._windowIsBackground) {
- shouldRender = false;
- }
- if (shouldRender) {
- // Start new frame
- this.beginFrame();
- for (var index = 0; index < this._activeRenderLoops.length; index++) {
- var renderFunction = this._activeRenderLoops[index];
- renderFunction();
- }
- // Present
- this.endFrame();
- }
- if (this._activeRenderLoops.length > 0) {
- // Register new frame
- BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- else {
- this._renderingQueueLaunched = false;
- }
- };
- /**
- * Register and execute a render loop. The engine can have more than one render function.
- * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
- * @example
- * engine.runRenderLoop(function () {
- * scene.render()
- * })
- */
- Engine.prototype.runRenderLoop = function (renderFunction) {
- if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
- return;
- }
- this._activeRenderLoops.push(renderFunction);
- if (!this._renderingQueueLaunched) {
- this._renderingQueueLaunched = true;
- this._bindedRenderFunction = this._renderLoop.bind(this);
- BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- };
- /**
- * Toggle full screen mode.
- * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
- */
- Engine.prototype.switchFullscreen = function (requestPointerLock) {
- if (this.isFullscreen) {
- BABYLON.Tools.ExitFullscreen();
- }
- else {
- this._pointerLockRequested = requestPointerLock;
- BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
- }
- };
- Engine.prototype.clear = function (color, backBuffer, depthStencil) {
- this.applyStates();
- if (backBuffer) {
- this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
- }
- if (depthStencil && this._depthCullingState.depthMask) {
- this._gl.clearDepth(1.0);
- }
- var mode = 0;
- if (backBuffer) {
- mode |= this._gl.COLOR_BUFFER_BIT;
- }
- if (depthStencil && this._depthCullingState.depthMask) {
- mode |= this._gl.DEPTH_BUFFER_BIT;
- }
- this._gl.clear(mode);
- };
- /**
- * Set the WebGL's viewport
- * @param {BABYLON.Viewport} viewport - the viewport element to be used.
- * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
- * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
- */
- Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
- var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
- var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
- var x = viewport.x || 0;
- var y = viewport.y || 0;
- this._cachedViewport = viewport;
- this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
- };
- Engine.prototype.setDirectViewport = function (x, y, width, height) {
- this._cachedViewport = null;
- this._gl.viewport(x, y, width, height);
- };
- Engine.prototype.beginFrame = function () {
- this._measureFps();
- };
- Engine.prototype.endFrame = function () {
- //this.flushFramebuffer();
- };
- /**
- * resize the view according to the canvas' size.
- * @example
- * window.addEventListener("resize", function () {
- * engine.resize();
- * });
- */
- Engine.prototype.resize = function () {
- var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
- var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
- this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
- for (var index = 0; index < this.scenes.length; index++) {
- var scene = this.scenes[index];
- if (scene.debugLayer.isVisible()) {
- scene.debugLayer._syncPositions();
- }
- }
- };
- /**
- * force a specific size of the canvas
- * @param {number} width - the new canvas' width
- * @param {number} height - the new canvas' height
- */
- Engine.prototype.setSize = function (width, height) {
- this._renderingCanvas.width = width;
- this._renderingCanvas.height = height;
- for (var index = 0; index < this.scenes.length; index++) {
- var scene = this.scenes[index];
- for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
- var cam = scene.cameras[camIndex];
- cam._currentRenderId = 0;
- }
- }
- };
- Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
- this._currentRenderTarget = texture;
- var gl = this._gl;
- gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
- if (texture.isCube) {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
- }
- else {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
- }
- this._gl.viewport(0, 0, texture._width, texture._height);
- this.wipeCaches();
- };
- Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
- if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
- this._currentRenderTarget = null;
- if (texture.generateMipMaps && !disableGenerateMipMaps) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.generateMipmap(gl.TEXTURE_2D);
- gl.bindTexture(gl.TEXTURE_2D, null);
- }
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
- };
- Engine.prototype.generateMipMapsForCubemap = function (texture) {
- if (texture.generateMipMaps) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- }
- };
- Engine.prototype.flushFramebuffer = function () {
- this._gl.flush();
- };
- Engine.prototype.restoreDefaultFramebuffer = function () {
- this._currentRenderTarget = null;
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
- this.setViewport(this._cachedViewport);
- this.wipeCaches();
- };
- // VBOs
- Engine.prototype._resetVertexBufferBinding = function () {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
- this._cachedVertexBuffers = null;
- };
- Engine.prototype.createVertexBuffer = function (vertices) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
- if (vertices instanceof Float32Array) {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
- }
- else {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
- }
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- };
- Engine.prototype.createDynamicVertexBuffer = function (capacity) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
- this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- };
- Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
- if (offset === undefined) {
- offset = 0;
- }
- if (vertices instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
- }
- else {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
- }
- this._resetVertexBufferBinding();
- };
- Engine.prototype._resetIndexBufferBinding = function () {
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
- this._cachedIndexBuffer = null;
- };
- Engine.prototype.createIndexBuffer = function (indices) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
- // Check for 32 bits indices
- var arrayBuffer;
- var need32Bits = false;
- if (this._caps.uintIndices) {
- for (var index = 0; index < indices.length; index++) {
- if (indices[index] > 65535) {
- need32Bits = true;
- break;
- }
- }
- arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
- }
- else {
- arrayBuffer = new Uint16Array(indices);
- }
- this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
- this._resetIndexBufferBinding();
- vbo.references = 1;
- vbo.is32Bits = need32Bits;
- return vbo;
- };
- Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
- if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffer;
- this._cachedEffectForVertexBuffers = effect;
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
- var offset = 0;
- for (var index = 0; index < vertexDeclaration.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
- }
- offset += vertexDeclaration[index] * 4;
- }
- }
- if (this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- };
- Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
- if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffers;
- this._cachedEffectForVertexBuffers = effect;
- var attributes = effect.getAttributesNames();
- for (var index = 0; index < attributes.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- var vertexBuffer = vertexBuffers[attributes[index]];
- if (!vertexBuffer) {
- continue;
- }
- var stride = vertexBuffer.getStrideSize();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
- this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
- }
- }
- }
- if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- };
- Engine.prototype._releaseBuffer = function (buffer) {
- buffer.references--;
- if (buffer.references === 0) {
- this._gl.deleteBuffer(buffer);
- return true;
- }
- return false;
- };
- Engine.prototype.createInstancesBuffer = function (capacity) {
- var buffer = this._gl.createBuffer();
- buffer.capacity = capacity;
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
- this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
- return buffer;
- };
- Engine.prototype.deleteInstancesBuffer = function (buffer) {
- this._gl.deleteBuffer(buffer);
- };
- Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- for (var index = 0; index < 4; index++) {
- var offsetLocation = offsetLocations[index];
- this._gl.enableVertexAttribArray(offsetLocation);
- this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
- this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
- }
- };
- Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
- for (var index = 0; index < 4; index++) {
- var offsetLocation = offsetLocations[index];
- this._gl.disableVertexAttribArray(offsetLocation);
- this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
- }
- };
- Engine.prototype.applyStates = function () {
- this._depthCullingState.apply(this._gl);
- this._alphaState.apply(this._gl);
- };
- Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- // Render
- var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
- var mult = this._uintIndicesCurrentlySet ? 4 : 2;
- if (instancesCount) {
- this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
- return;
- }
- this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
- };
- Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- if (instancesCount) {
- this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
- };
- Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- if (instancesCount) {
- this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
- };
- // Shaders
- Engine.prototype._releaseEffect = function (effect) {
- if (this._compiledEffects[effect._key]) {
- delete this._compiledEffects[effect._key];
- if (effect.getProgram()) {
- this._gl.deleteProgram(effect.getProgram());
- }
- }
- };
- Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
- var vertex = baseName.vertexElement || baseName.vertex || baseName;
- var fragment = baseName.fragmentElement || baseName.fragment || baseName;
- var name = vertex + "+" + fragment + "@" + defines;
- if (this._compiledEffects[name]) {
- return this._compiledEffects[name];
- }
- var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
- effect._key = name;
- this._compiledEffects[name] = effect;
- return effect;
- };
- Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
- if (uniformsNames === void 0) { uniformsNames = []; }
- if (samplers === void 0) { samplers = []; }
- if (defines === void 0) { defines = ""; }
- return this.createEffect({
- vertex: "particles",
- fragmentElement: fragmentName
- }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
- };
- Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
- var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
- var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
- var shaderProgram = this._gl.createProgram();
- this._gl.attachShader(shaderProgram, vertexShader);
- this._gl.attachShader(shaderProgram, fragmentShader);
- this._gl.linkProgram(shaderProgram);
- var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
- if (!linked) {
- var error = this._gl.getProgramInfoLog(shaderProgram);
- if (error) {
- throw new Error(error);
- }
- }
- this._gl.deleteShader(vertexShader);
- this._gl.deleteShader(fragmentShader);
- return shaderProgram;
- };
- Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
- var results = [];
- for (var index = 0; index < uniformsNames.length; index++) {
- results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
- }
- return results;
- };
- Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
- var results = [];
- for (var index = 0; index < attributesNames.length; index++) {
- try {
- results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
- }
- catch (e) {
- results.push(-1);
- }
- }
- return results;
- };
- Engine.prototype.enableEffect = function (effect) {
- if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
- if (effect && effect.onBind) {
- effect.onBind(effect);
- }
- return;
- }
- this._vertexAttribArrays = this._vertexAttribArrays || [];
- // Use program
- this._gl.useProgram(effect.getProgram());
- for (var i in this._vertexAttribArrays) {
- if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
- continue;
- }
- this._vertexAttribArrays[i] = false;
- this._gl.disableVertexAttribArray(i);
- }
- var attributesCount = effect.getAttributesCount();
- for (var index = 0; index < attributesCount; index++) {
- // Attributes
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._vertexAttribArrays[order] = true;
- this._gl.enableVertexAttribArray(order);
- }
- }
- this._currentEffect = effect;
- if (effect.onBind) {
- effect.onBind(effect);
- }
- };
- Engine.prototype.setArray = function (uniform, array) {
- if (!uniform)
- return;
- this._gl.uniform1fv(uniform, array);
- };
- Engine.prototype.setArray2 = function (uniform, array) {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2fv(uniform, array);
- };
- Engine.prototype.setArray3 = function (uniform, array) {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3fv(uniform, array);
- };
- Engine.prototype.setArray4 = function (uniform, array) {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4fv(uniform, array);
- };
- Engine.prototype.setMatrices = function (uniform, matrices) {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrices);
- };
- Engine.prototype.setMatrix = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
- };
- Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix3fv(uniform, false, matrix);
- };
- Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix2fv(uniform, false, matrix);
- };
- Engine.prototype.setFloat = function (uniform, value) {
- if (!uniform)
- return;
- this._gl.uniform1f(uniform, value);
- };
- Engine.prototype.setFloat2 = function (uniform, x, y) {
- if (!uniform)
- return;
- this._gl.uniform2f(uniform, x, y);
- };
- Engine.prototype.setFloat3 = function (uniform, x, y, z) {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, x, y, z);
- };
- Engine.prototype.setBool = function (uniform, bool) {
- if (!uniform)
- return;
- this._gl.uniform1i(uniform, bool);
- };
- Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, x, y, z, w);
- };
- Engine.prototype.setColor3 = function (uniform, color3) {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
- };
- Engine.prototype.setColor4 = function (uniform, color3, alpha) {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
- };
- // States
- Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
- if (zOffset === void 0) { zOffset = 0; }
- if (reverseSide === void 0) { reverseSide = false; }
- // Culling
- var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
- var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
- var cullFace = this.cullBackFaces ? showSide : hideSide;
- if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
- if (culling) {
- this._depthCullingState.cullFace = cullFace;
- this._depthCullingState.cull = true;
- }
- else {
- this._depthCullingState.cull = false;
- }
- }
- // Z offset
- this._depthCullingState.zOffset = zOffset;
- };
- Engine.prototype.setDepthBuffer = function (enable) {
- this._depthCullingState.depthTest = enable;
- };
- Engine.prototype.getDepthWrite = function () {
- return this._depthCullingState.depthMask;
- };
- Engine.prototype.setDepthWrite = function (enable) {
- this._depthCullingState.depthMask = enable;
- };
- Engine.prototype.setColorWrite = function (enable) {
- this._gl.colorMask(enable, enable, enable, enable);
- };
- Engine.prototype.setAlphaMode = function (mode) {
- if (this._alphaMode === mode) {
- return;
- }
- switch (mode) {
- case Engine.ALPHA_DISABLE:
- this.setDepthWrite(true);
- this._alphaState.alphaBlend = false;
- break;
- case Engine.ALPHA_COMBINE:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ONEONE:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ADD:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_SUBTRACT:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MULTIPLY:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MAXIMIZED:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- }
- this._alphaMode = mode;
- };
- Engine.prototype.getAlphaMode = function () {
- return this._alphaMode;
- };
- Engine.prototype.setAlphaTesting = function (enable) {
- this._alphaTest = enable;
- };
- Engine.prototype.getAlphaTesting = function () {
- return this._alphaTest;
- };
- // Textures
- Engine.prototype.wipeCaches = function () {
- this.resetTextureCache();
- this._currentEffect = null;
- this._depthCullingState.reset();
- this._alphaState.reset();
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._cachedEffectForVertexBuffers = null;
- };
- Engine.prototype.setSamplingMode = function (texture, samplingMode) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- minFilter = gl.LINEAR;
- }
- else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
- gl.bindTexture(gl.TEXTURE_2D, null);
- texture.samplingMode = samplingMode;
- };
- Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (buffer === void 0) { buffer = null; }
- var texture = this._gl.createTexture();
- var extension;
- var fromData = false;
- if (url.substr(0, 5) === "data:") {
- fromData = true;
- }
- if (!fromData)
- extension = url.substr(url.length - 4, 4).toLowerCase();
- else {
- var oldUrl = url;
- fromData = oldUrl.split(':');
- url = oldUrl;
- extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
- }
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- var isTGA = (extension === ".tga");
- scene._addPendingData(texture);
- texture.url = url;
- texture.noMipmap = noMipmap;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this._loadedTexturesCache.push(texture);
- var onerror = function () {
- scene._removePendingData(texture);
- if (onError) {
- onError();
- }
- };
- var callback;
- if (isTGA) {
- callback = function (arrayBuffer) {
- var data = new Uint8Array(arrayBuffer);
- var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
- prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
- BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
- callback(arrayBuffer);
- }, onerror, scene.database, true);
- else
- callback(buffer);
- }
- else if (isDDS) {
- callback = function (data) {
- var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
- prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
- BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadFile(url, function (data) {
- callback(data);
- }, onerror, scene.database, true);
- else
- callback(buffer);
- }
- else {
- var onload = function (img) {
- prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
- var isPot = (img.width === potWidth && img.height === potHeight);
- if (!isPot) {
- _this._prepareWorkingCanvas();
- _this._workingCanvas.width = potWidth;
- _this._workingCanvas.height = potHeight;
- if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- _this._workingContext.imageSmoothingEnabled = false;
- _this._workingContext.mozImageSmoothingEnabled = false;
- _this._workingContext.oImageSmoothingEnabled = false;
- _this._workingContext.webkitImageSmoothingEnabled = false;
- _this._workingContext.msImageSmoothingEnabled = false;
- }
- _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
- if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- _this._workingContext.imageSmoothingEnabled = true;
- _this._workingContext.mozImageSmoothingEnabled = true;
- _this._workingContext.oImageSmoothingEnabled = true;
- _this._workingContext.webkitImageSmoothingEnabled = true;
- _this._workingContext.msImageSmoothingEnabled = true;
- }
- }
- _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
- else
- BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
- }
- return texture;
- };
- Engine.prototype._getInternalFormat = function (format) {
- var internalFormat = this._gl.RGBA;
- switch (format) {
- case Engine.TEXTUREFORMAT_ALPHA:
- internalFormat = this._gl.ALPHA;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE:
- internalFormat = this._gl.LUMINANCE;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
- internalFormat = this._gl.LUMINANCE_ALPHA;
- break;
- case Engine.TEXTUREFORMAT_RGB:
- internalFormat = this._gl.RGB;
- break;
- case Engine.TEXTUREFORMAT_RGBA:
- internalFormat = this._gl.RGBA;
- break;
- }
- return internalFormat;
- };
- Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
- if (compression === void 0) { compression = null; }
- var internalFormat = this._getInternalFormat(format);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (compression) {
- this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
- }
- else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
- if (compression === void 0) { compression = null; }
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = width;
- texture._height = height;
- texture.references = 1;
- this.updateRawTexture(texture, data, format, invertY, compression);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- // Filters
- var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- texture.samplingMode = samplingMode;
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
- if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- if (forceExponantOfTwo) {
- width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
- height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
- }
- this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = false;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this.updateTextureSamplingMode(samplingMode, texture);
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
- var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
- if (texture.isCube) {
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- }
- else {
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- }
- };
- Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
- if (texture._isDisabled) {
- return;
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
- try {
- // Testing video texture support
- if (this._videoTextureSupported === undefined) {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- if (this._gl.getError() !== 0) {
- this._videoTextureSupported = false;
- }
- else {
- this._videoTextureSupported = true;
- }
- }
- // Copy video through the current working canvas if video texture is not supported
- if (!this._videoTextureSupported) {
- if (!texture._workingCanvas) {
- texture._workingCanvas = document.createElement("canvas");
- texture._workingContext = texture._workingCanvas.getContext("2d");
- texture._workingCanvas.width = texture._width;
- texture._workingCanvas.height = texture._height;
- }
- texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
- }
- else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- }
- catch (ex) {
- // Something unexpected
- // Let's disable the texture
- texture._isDisabled = true;
- }
- };
- Engine.prototype.createRenderTargetTexture = function (size, options) {
- // old version had a "generateMipMaps" arg instead of options.
- // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
- // in the same way, generateDepthBuffer is defaulted to true
- var generateMipMaps = false;
- var generateDepthBuffer = true;
- var type = Engine.TEXTURETYPE_UNSIGNED_INT;
- var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- type = options.type === undefined ? type : options.type;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- if (type === Engine.TEXTURETYPE_FLOAT) {
- // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- }
- var gl = this._gl;
- var texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- var width = size.width || size;
- var height = size.height || size;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
- type = Engine.TEXTURETYPE_UNSIGNED_INT;
- BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
- var depthBuffer;
- // Create the depth buffer
- if (generateDepthBuffer) {
- depthBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
- }
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
- if (generateDepthBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
- }
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- // Unbind
- gl.bindTexture(gl.TEXTURE_2D, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- texture._framebuffer = framebuffer;
- if (generateDepthBuffer) {
- texture._depthBuffer = depthBuffer;
- }
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this.resetTextureCache();
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
- var gl = this._gl;
- var texture = gl.createTexture();
- var generateMipMaps = true;
- var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- }
- texture.isCube = true;
- texture.references = 1;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- for (var face = 0; face < 6; face++) {
- gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- // Create the depth buffer
- var depthBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
- // Mipmaps
- if (texture.generateMipMaps) {
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- // Unbind
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- texture._framebuffer = framebuffer;
- texture._depthBuffer = depthBuffer;
- this.resetTextureCache();
- texture._width = size;
- texture._height = size;
- texture.isReady = true;
- return texture;
- };
- Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
- var _this = this;
- var gl = this._gl;
- var texture = gl.createTexture();
- texture.isCube = true;
- texture.url = rootUrl;
- texture.references = 1;
- var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- if (isDDS) {
- BABYLON.Tools.LoadFile(rootUrl, function (data) {
- var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
- BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
- if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- _this.resetTextureCache();
- texture._width = info.width;
- texture._height = info.height;
- texture.isReady = true;
- }, null, null, true);
- }
- else {
- cascadeLoad(rootUrl, scene, function (imgs) {
- var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
- var height = width;
- _this._prepareWorkingCanvas();
- _this._workingCanvas.width = width;
- _this._workingCanvas.height = height;
- var faces = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- for (var index = 0; index < faces.length; index++) {
- _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
- gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
- }
- if (!noMipmap) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- _this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- }, files);
- }
- return texture;
- };
- Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
- var _this = this;
- var gl = this._gl;
- var texture = gl.createTexture();
- scene._addPendingData(texture);
- texture.isCube = true;
- texture.references = 1;
- texture.url = url;
- var internalFormat = this._getInternalFormat(format);
- var textureType = gl.UNSIGNED_BYTE;
- if (type === Engine.TEXTURETYPE_FLOAT) {
- textureType = gl.FLOAT;
- }
- var width = size;
- var height = width;
- var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
- texture._width = width;
- texture._height = height;
- var onerror = function () {
- scene._removePendingData(texture);
- };
- var internalCallback = function (data) {
- var rgbeDataArrays = callback(data);
- var facesIndex = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- for (var index = 0; index < facesIndex.length; index++) {
- var faceData = rgbeDataArrays[index];
- gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
- }
- if (!noMipmap && isPot) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- else {
- noMipmap = true;
- }
- if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- else {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- texture.isReady = true;
- _this.resetTextureCache();
- scene._removePendingData(texture);
- };
- BABYLON.Tools.LoadFile(url, function (data) {
- internalCallback(data);
- }, onerror, scene.database, true);
- return texture;
- };
- ;
- Engine.prototype._releaseTexture = function (texture) {
- var gl = this._gl;
- if (texture._framebuffer) {
- gl.deleteFramebuffer(texture._framebuffer);
- }
- if (texture._depthBuffer) {
- gl.deleteRenderbuffer(texture._depthBuffer);
- }
- gl.deleteTexture(texture);
- // Unbind channels
- this.unbindAllTextures();
- var index = this._loadedTexturesCache.indexOf(texture);
- if (index !== -1) {
- this._loadedTexturesCache.splice(index, 1);
- }
- };
- Engine.prototype.bindSamplers = function (effect) {
- this._gl.useProgram(effect.getProgram());
- var samplers = effect.getSamplers();
- for (var index = 0; index < samplers.length; index++) {
- var uniform = effect.getUniform(samplers[index]);
- this._gl.uniform1i(uniform, index);
- }
- this._currentEffect = null;
- };
- Engine.prototype._bindTexture = function (channel, texture) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._activeTexturesCache[channel] = null;
- };
- Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
- };
- Engine.prototype.unbindAllTextures = function () {
- for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- this._activeTexturesCache[channel] = null;
- }
- };
- Engine.prototype.setTexture = function (channel, texture) {
- if (channel < 0) {
- return;
- }
- // Not ready?
- if (!texture || !texture.isReady()) {
- if (this._activeTexturesCache[channel] != null) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- this._activeTexturesCache[channel] = null;
- }
- return;
- }
- // Video
- var alreadyActivated = false;
- if (texture instanceof BABYLON.VideoTexture) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- alreadyActivated = true;
- texture.update();
- }
- else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
- texture.delayLoad();
- return;
- }
- if (this._activeTexturesCache[channel] === texture) {
- return;
- }
- this._activeTexturesCache[channel] = texture;
- var internalTexture = texture.getInternalTexture();
- if (!alreadyActivated) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- }
- if (internalTexture.isCube) {
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
- if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
- internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
- // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
- var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
- }
- else {
- this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
- if (internalTexture._cachedWrapU !== texture.wrapU) {
- internalTexture._cachedWrapU = texture.wrapU;
- switch (texture.wrapU) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- if (internalTexture._cachedWrapV !== texture.wrapV) {
- internalTexture._cachedWrapV = texture.wrapV;
- switch (texture.wrapV) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
- }
- };
- Engine.prototype._setAnisotropicLevel = function (key, texture) {
- var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
- var value = texture.anisotropicFilteringLevel;
- if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- value = 1;
- }
- if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
- this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
- texture._cachedAnisotropicFilteringLevel = value;
- }
- };
- Engine.prototype.readPixels = function (x, y, width, height) {
- var data = new Uint8Array(height * width * 4);
- this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
- return data;
- };
- Engine.prototype.releaseInternalTexture = function (texture) {
- if (!texture) {
- return;
- }
- texture.references--;
- // Final reference ?
- if (texture.references === 0) {
- var texturesCache = this.getLoadedTexturesCache();
- var index = texturesCache.indexOf(texture);
- if (index > -1) {
- texturesCache.splice(index, 1);
- }
- this._releaseTexture(texture);
- }
- };
- // Dispose
- Engine.prototype.dispose = function () {
- this.hideLoadingUI();
- this.stopRenderLoop();
- // Release scenes
- while (this.scenes.length) {
- this.scenes[0].dispose();
- }
- // Release audio engine
- Engine.audioEngine.dispose();
- // Release effects
- for (var name in this._compiledEffects) {
- this._gl.deleteProgram(this._compiledEffects[name]._program);
- }
- // Unbind
- for (var i in this._vertexAttribArrays) {
- if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
- continue;
- }
- this._gl.disableVertexAttribArray(i);
- }
- this._gl = null;
- // Events
- window.removeEventListener("blur", this._onBlur);
- window.removeEventListener("focus", this._onFocus);
- document.removeEventListener("fullscreenchange", this._onFullscreenChange);
- document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("pointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
- document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
- };
- // Loading screen
- Engine.prototype.displayLoadingUI = function () {
- this._loadingScreen.displayLoadingUI();
- };
- Engine.prototype.hideLoadingUI = function () {
- this._loadingScreen.hideLoadingUI();
- };
- Object.defineProperty(Engine.prototype, "loadingScreen", {
- get: function () {
- return this._loadingScreen;
- },
- set: function (loadingScreen) {
- this._loadingScreen = loadingScreen;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "loadingUIText", {
- set: function (text) {
- this._loadingScreen.loadingUIText = text;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
- set: function (color) {
- this._loadingScreen.loadingUIBackgroundColor = color;
- },
- enumerable: true,
- configurable: true
- });
- // FPS
- Engine.prototype.getFps = function () {
- return this.fps;
- };
- Engine.prototype.getDeltaTime = function () {
- return this.deltaTime;
- };
- Engine.prototype._measureFps = function () {
- this.previousFramesDuration.push(BABYLON.Tools.Now);
- var length = this.previousFramesDuration.length;
- if (length >= 2) {
- this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
- }
- if (length >= this.fpsRange) {
- if (length > this.fpsRange) {
- this.previousFramesDuration.splice(0, 1);
- length = this.previousFramesDuration.length;
- }
- var sum = 0;
- for (var id = 0; id < length - 1; id++) {
- sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
- }
- this.fps = 1000.0 / (sum / (length - 1));
- }
- };
- // Statics
- Engine.isSupported = function () {
- try {
- // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
- if (navigator.isCocoonJS) {
- return true;
- }
- var tempcanvas = document.createElement("canvas");
- var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
- return gl != null && !!window.WebGLRenderingContext;
- }
- catch (e) {
- return false;
- }
- };
- // Const statics
- Engine._ALPHA_DISABLE = 0;
- Engine._ALPHA_ADD = 1;
- Engine._ALPHA_COMBINE = 2;
- Engine._ALPHA_SUBTRACT = 3;
- Engine._ALPHA_MULTIPLY = 4;
- Engine._ALPHA_MAXIMIZED = 5;
- Engine._ALPHA_ONEONE = 6;
- Engine._DELAYLOADSTATE_NONE = 0;
- Engine._DELAYLOADSTATE_LOADED = 1;
- Engine._DELAYLOADSTATE_LOADING = 2;
- Engine._DELAYLOADSTATE_NOTLOADED = 4;
- Engine._TEXTUREFORMAT_ALPHA = 0;
- Engine._TEXTUREFORMAT_LUMINANCE = 1;
- Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
- Engine._TEXTUREFORMAT_RGB = 4;
- Engine._TEXTUREFORMAT_RGBA = 5;
- Engine._TEXTURETYPE_UNSIGNED_INT = 0;
- Engine._TEXTURETYPE_FLOAT = 1;
- // Updatable statics so stick with vars here
- Engine.Epsilon = 0.001;
- Engine.CollisionsEpsilon = 0.001;
- Engine.CodeRepository = "src/";
- Engine.ShadersRepository = "src/Shaders/";
- return Engine;
- })();
- BABYLON.Engine = Engine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Node is the basic class for all scene objects (Mesh, Light Camera).
- */
- var Node = (function () {
- /**
- * @constructor
- * @param {string} name - the name and id to be given to this node
- * @param {BABYLON.Scene} the scene this node will be added to
- */
- function Node(name, scene) {
- this.state = "";
- this.animations = new Array();
- this._ranges = {};
- this._childrenFlag = -1;
- this._isEnabled = true;
- this._isReady = true;
- this._currentRenderId = -1;
- this._parentRenderId = -1;
- this.name = name;
- this.id = name;
- this._scene = scene;
- this._initCache();
- }
- Node.prototype.getScene = function () {
- return this._scene;
- };
- Node.prototype.getEngine = function () {
- return this._scene.getEngine();
- };
- // override it in derived class
- Node.prototype.getWorldMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- // override it in derived class if you add new variables to the cache
- // and call the parent class method
- Node.prototype._initCache = function () {
- this._cache = {};
- this._cache.parent = undefined;
- };
- Node.prototype.updateCache = function (force) {
- if (!force && this.isSynchronized())
- return;
- this._cache.parent = this.parent;
- this._updateCache();
- };
- // override it in derived class if you add new variables to the cache
- // and call the parent class method if !ignoreParentClass
- Node.prototype._updateCache = function (ignoreParentClass) {
- };
- // override it in derived class if you add new variables to the cache
- Node.prototype._isSynchronized = function () {
- return true;
- };
- Node.prototype._markSyncedWithParent = function () {
- this._parentRenderId = this.parent._currentRenderId;
- };
- Node.prototype.isSynchronizedWithParent = function () {
- if (!this.parent) {
- return true;
- }
- if (this._parentRenderId !== this.parent._currentRenderId) {
- return false;
- }
- return this.parent.isSynchronized();
- };
- Node.prototype.isSynchronized = function (updateCache) {
- var check = this.hasNewParent();
- check = check || !this.isSynchronizedWithParent();
- check = check || !this._isSynchronized();
- if (updateCache)
- this.updateCache(true);
- return !check;
- };
- Node.prototype.hasNewParent = function (update) {
- if (this._cache.parent === this.parent)
- return false;
- if (update)
- this._cache.parent = this.parent;
- return true;
- };
- /**
- * Is this node ready to be used/rendered
- * @return {boolean} is it ready
- */
- Node.prototype.isReady = function () {
- return this._isReady;
- };
- /**
- * Is this node enabled.
- * If the node has a parent and is enabled, the parent will be inspected as well.
- * @return {boolean} whether this node (and its parent) is enabled.
- * @see setEnabled
- */
- Node.prototype.isEnabled = function () {
- if (!this._isEnabled) {
- return false;
- }
- if (this.parent) {
- return this.parent.isEnabled();
- }
- return true;
- };
- /**
- * Set the enabled state of this node.
- * @param {boolean} value - the new enabled state
- * @see isEnabled
- */
- Node.prototype.setEnabled = function (value) {
- this._isEnabled = value;
- };
- /**
- * Is this node a descendant of the given node.
- * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
- * @param {BABYLON.Node} ancestor - The parent node to inspect
- * @see parent
- */
- Node.prototype.isDescendantOf = function (ancestor) {
- if (this.parent) {
- if (this.parent === ancestor) {
- return true;
- }
- return this.parent.isDescendantOf(ancestor);
- }
- return false;
- };
- Node.prototype._getDescendants = function (list, results) {
- for (var index = 0; index < list.length; index++) {
- var item = list[index];
- if (item.isDescendantOf(this)) {
- results.push(item);
- }
- }
- };
- /**
- * Will return all nodes that have this node as parent.
- * @return {BABYLON.Node[]} all children nodes of all types.
- */
- Node.prototype.getDescendants = function () {
- var results = [];
- this._getDescendants(this._scene.meshes, results);
- this._getDescendants(this._scene.lights, results);
- this._getDescendants(this._scene.cameras, results);
- return results;
- };
- Node.prototype._setReady = function (state) {
- if (state === this._isReady) {
- return;
- }
- if (!state) {
- this._isReady = false;
- return;
- }
- this._isReady = true;
- if (this.onReady) {
- this.onReady(this);
- }
- };
- Node.prototype.getAnimationByName = function (name) {
- for (var i = 0; i < this.animations.length; i++) {
- var animation = this.animations[i];
- if (animation.name === name) {
- return animation;
- }
- }
- return null;
- };
- Node.prototype.createAnimationRange = function (name, from, to) {
- // check name not already in use
- if (!this._ranges[name]) {
- this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
- for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].createRange(name, from, to);
- }
- }
- }
- };
- Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].deleteRange(name, deleteFrames);
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- };
- Node.prototype.getAnimationRange = function (name) {
- return this._ranges[name];
- };
- Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
- var range = this.getAnimationRange(name);
- if (!range) {
- return null;
- }
- this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- };
- Node.prototype.serializeAnimationRanges = function () {
- var serializationRanges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationRanges.push(range);
- }
- return serializationRanges;
- };
- Node.ParseAnimationRanges = function (node, parsedNode, scene) {
- if (parsedNode.ranges) {
- for (var index = 0; index < parsedNode.ranges.length; index++) {
- var data = parsedNode.ranges[index];
- node.createAnimationRange(data.name, data.from, data.to);
- }
- }
- };
- return Node;
- })();
- BABYLON.Node = Node;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FilesInput = (function () {
- /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
- /// loading progress callback and optionnal addionnal logic to call in the rendering loop
- function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
- this._engine = p_engine;
- this._canvas = p_canvas;
- this._currentScene = p_scene;
- this._sceneLoadedCallback = p_sceneLoadedCallback;
- this._progressCallback = p_progressCallback;
- this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
- this._textureLoadingCallback = p_textureLoadingCallback;
- this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
- }
- FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
- var _this = this;
- if (p_elementToMonitor) {
- this._elementToMonitor = p_elementToMonitor;
- this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
- this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
- this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
- }
- };
- FilesInput.prototype.renderFunction = function () {
- if (this._additionnalRenderLoopLogicCallback) {
- this._additionnalRenderLoopLogicCallback();
- }
- if (this._currentScene) {
- if (this._textureLoadingCallback) {
- var remaining = this._currentScene.getWaitingItemsCount();
- if (remaining > 0) {
- this._textureLoadingCallback(remaining);
- }
- }
- this._currentScene.render();
- }
- };
- FilesInput.prototype.drag = function (e) {
- e.stopPropagation();
- e.preventDefault();
- };
- FilesInput.prototype.drop = function (eventDrop) {
- eventDrop.stopPropagation();
- eventDrop.preventDefault();
- this.loadFiles(eventDrop);
- };
- FilesInput.prototype.loadFiles = function (event) {
- if (this._startingProcessingFilesCallback)
- this._startingProcessingFilesCallback();
- // Handling data transfer via drag'n'drop
- if (event && event.dataTransfer && event.dataTransfer.files) {
- this._filesToLoad = event.dataTransfer.files;
- }
- // Handling files from input files
- if (event && event.target && event.target.files) {
- this._filesToLoad = event.target.files;
- }
- if (this._filesToLoad && this._filesToLoad.length > 0) {
- for (var i = 0; i < this._filesToLoad.length; i++) {
- switch (this._filesToLoad[i].type) {
- case "image/jpeg":
- case "image/png":
- case "image/bmp":
- FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
- break;
- case "image/targa":
- case "image/vnd.ms-dds":
- case "audio/wav":
- case "audio/x-wav":
- case "audio/mp3":
- case "audio/mpeg":
- case "audio/mpeg3":
- case "audio/x-mpeg-3":
- case "audio/ogg":
- FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
- break;
- default:
- if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
- this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
- && this._filesToLoad[i].name.indexOf(".manifest") === -1
- && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
- && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
- this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
- this._sceneFileToLoad = this._filesToLoad[i];
- }
- break;
- }
- }
- this.reload();
- }
- };
- FilesInput.prototype.reload = function () {
- var _this = this;
- var that = this;
- // If a ".babylon" file has been provided
- if (this._sceneFileToLoad) {
- if (this._currentScene) {
- if (BABYLON.Tools.errorsCount > 0) {
- BABYLON.Tools.ClearLogCache();
- BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
- }
- this._engine.stopRenderLoop();
- this._currentScene.dispose();
- }
- BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
- that._currentScene = newScene;
- // Wait for textures and shaders to be ready
- that._currentScene.executeWhenReady(function () {
- // Attach camera to canvas inputs
- if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
- that._currentScene.createDefaultCameraOrLight();
- }
- that._currentScene.activeCamera.attachControl(that._canvas);
- if (that._sceneLoadedCallback) {
- that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
- }
- that._engine.runRenderLoop(function () { that.renderFunction(); });
- });
- }, function (progress) {
- if (_this._progressCallback) {
- _this._progressCallback(progress);
- }
- });
- }
- else {
- BABYLON.Tools.Error("Please provide a valid .babylon file.");
- }
- };
- FilesInput.FilesTextures = new Array();
- FilesInput.FilesToLoad = new Array();
- return FilesInput;
- })();
- BABYLON.FilesInput = FilesInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var IntersectionInfo = (function () {
- function IntersectionInfo(bu, bv, distance) {
- this.bu = bu;
- this.bv = bv;
- this.distance = distance;
- this.faceId = 0;
- this.subMeshId = 0;
- }
- return IntersectionInfo;
- })();
- BABYLON.IntersectionInfo = IntersectionInfo;
- var PickingInfo = (function () {
- function PickingInfo() {
- this.hit = false;
- this.distance = 0;
- this.pickedPoint = null;
- this.pickedMesh = null;
- this.bu = 0;
- this.bv = 0;
- this.faceId = -1;
- this.subMeshId = 0;
- this.pickedSprite = null;
- }
- // Methods
- PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
- if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
- if (useVerticesNormals === void 0) { useVerticesNormals = true; }
- if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return null;
- }
- var indices = this.pickedMesh.getIndices();
- var result;
- if (useVerticesNormals) {
- var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
- var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
- var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
- normal0 = normal0.scale(this.bu);
- normal1 = normal1.scale(this.bv);
- normal2 = normal2.scale(1.0 - this.bu - this.bv);
- result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
- }
- else {
- var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
- var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
- var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
- var p1p2 = vertex1.subtract(vertex2);
- var p3p2 = vertex3.subtract(vertex2);
- result = BABYLON.Vector3.Cross(p1p2, p3p2);
- }
- if (useWorldCoordinates) {
- result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
- }
- return BABYLON.Vector3.Normalize(result);
- };
- PickingInfo.prototype.getTextureCoordinates = function () {
- if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- return null;
- }
- var indices = this.pickedMesh.getIndices();
- var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
- var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
- var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
- uv0 = uv0.scale(1.0 - this.bu - this.bv);
- uv1 = uv1.scale(this.bu);
- uv2 = uv2.scale(this.bv);
- return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
- };
- return PickingInfo;
- })();
- BABYLON.PickingInfo = PickingInfo;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingSphere = (function () {
- function BoundingSphere(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this._tempRadiusVector = BABYLON.Vector3.Zero();
- var distance = BABYLON.Vector3.Distance(minimum, maximum);
- this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
- this.radius = distance * 0.5;
- this.centerWorld = BABYLON.Vector3.Zero();
- this._update(BABYLON.Matrix.Identity());
- }
- // Methods
- BoundingSphere.prototype._update = function (world) {
- BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
- this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
- };
- BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
- for (var i = 0; i < 6; i++) {
- if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
- return false;
- }
- return true;
- };
- BoundingSphere.prototype.intersectsPoint = function (point) {
- var x = this.centerWorld.x - point.x;
- var y = this.centerWorld.y - point.y;
- var z = this.centerWorld.z - point.z;
- var distance = Math.sqrt((x * x) + (y * y) + (z * z));
- if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
- return false;
- return true;
- };
- // Statics
- BoundingSphere.Intersects = function (sphere0, sphere1) {
- var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
- var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
- var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
- var distance = Math.sqrt((x * x) + (y * y) + (z * z));
- if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
- return false;
- return true;
- };
- return BoundingSphere;
- })();
- BABYLON.BoundingSphere = BoundingSphere;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingBox = (function () {
- function BoundingBox(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this.vectors = new Array();
- this.vectorsWorld = new Array();
- // Bounding vectors
- this.vectors.push(this.minimum.clone());
- this.vectors.push(this.maximum.clone());
- this.vectors.push(this.minimum.clone());
- this.vectors[2].x = this.maximum.x;
- this.vectors.push(this.minimum.clone());
- this.vectors[3].y = this.maximum.y;
- this.vectors.push(this.minimum.clone());
- this.vectors[4].z = this.maximum.z;
- this.vectors.push(this.maximum.clone());
- this.vectors[5].z = this.minimum.z;
- this.vectors.push(this.maximum.clone());
- this.vectors[6].x = this.minimum.x;
- this.vectors.push(this.maximum.clone());
- this.vectors[7].y = this.minimum.y;
- // OBB
- this.center = this.maximum.add(this.minimum).scale(0.5);
- this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
- this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
- // World
- for (var index = 0; index < this.vectors.length; index++) {
- this.vectorsWorld[index] = BABYLON.Vector3.Zero();
- }
- this.minimumWorld = BABYLON.Vector3.Zero();
- this.maximumWorld = BABYLON.Vector3.Zero();
- this._update(BABYLON.Matrix.Identity());
- }
- // Methods
- BoundingBox.prototype.getWorldMatrix = function () {
- return this._worldMatrix;
- };
- BoundingBox.prototype.setWorldMatrix = function (matrix) {
- this._worldMatrix.copyFrom(matrix);
- return this;
- };
- BoundingBox.prototype._update = function (world) {
- BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
- BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
- for (var index = 0; index < this.vectors.length; index++) {
- var v = this.vectorsWorld[index];
- BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
- if (v.x < this.minimumWorld.x)
- this.minimumWorld.x = v.x;
- if (v.y < this.minimumWorld.y)
- this.minimumWorld.y = v.y;
- if (v.z < this.minimumWorld.z)
- this.minimumWorld.z = v.z;
- if (v.x > this.maximumWorld.x)
- this.maximumWorld.x = v.x;
- if (v.y > this.maximumWorld.y)
- this.maximumWorld.y = v.y;
- if (v.z > this.maximumWorld.z)
- this.maximumWorld.z = v.z;
- }
- // OBB
- this.maximumWorld.addToRef(this.minimumWorld, this.center);
- this.center.scaleInPlace(0.5);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
- this._worldMatrix = world;
- };
- BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
- return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
- };
- BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
- };
- BoundingBox.prototype.intersectsPoint = function (point) {
- var delta = -BABYLON.Engine.Epsilon;
- if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
- return false;
- if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
- return false;
- if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
- return false;
- return true;
- };
- BoundingBox.prototype.intersectsSphere = function (sphere) {
- return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
- };
- BoundingBox.prototype.intersectsMinMax = function (min, max) {
- if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
- return false;
- if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
- return false;
- if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
- return false;
- return true;
- };
- // Statics
- BoundingBox.Intersects = function (box0, box1) {
- if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
- return false;
- if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
- return false;
- if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
- return false;
- return true;
- };
- BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
- var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
- var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
- return (num <= (sphereRadius * sphereRadius));
- };
- BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
- for (var p = 0; p < 6; p++) {
- for (var i = 0; i < 8; i++) {
- if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
- return false;
- }
- }
- }
- return true;
- };
- BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
- for (var p = 0; p < 6; p++) {
- var inCount = 8;
- for (var i = 0; i < 8; i++) {
- if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
- --inCount;
- }
- else {
- break;
- }
- }
- if (inCount === 0)
- return false;
- }
- return true;
- };
- return BoundingBox;
- })();
- BABYLON.BoundingBox = BoundingBox;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var computeBoxExtents = function (axis, box) {
- var p = BABYLON.Vector3.Dot(box.center, axis);
- var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
- var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
- var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
- var r = r0 + r1 + r2;
- return {
- min: p - r,
- max: p + r
- };
- };
- var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
- var axisOverlap = function (axis, box0, box1) {
- var result0 = computeBoxExtents(axis, box0);
- var result1 = computeBoxExtents(axis, box1);
- return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
- };
- var BoundingInfo = (function () {
- function BoundingInfo(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this._isLocked = false;
- this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
- this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
- }
- Object.defineProperty(BoundingInfo.prototype, "isLocked", {
- get: function () {
- return this._isLocked;
- },
- set: function (value) {
- this._isLocked = value;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- BoundingInfo.prototype.update = function (world) {
- if (this._isLocked) {
- return;
- }
- this.boundingBox._update(world);
- this.boundingSphere._update(world);
- };
- BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
- if (!this.boundingSphere.isInFrustum(frustumPlanes))
- return false;
- return this.boundingBox.isInFrustum(frustumPlanes);
- };
- BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
- };
- BoundingInfo.prototype._checkCollision = function (collider) {
- return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
- };
- BoundingInfo.prototype.intersectsPoint = function (point) {
- if (!this.boundingSphere.centerWorld) {
- return false;
- }
- if (!this.boundingSphere.intersectsPoint(point)) {
- return false;
- }
- if (!this.boundingBox.intersectsPoint(point)) {
- return false;
- }
- return true;
- };
- BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
- if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
- return false;
- }
- if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
- return false;
- }
- if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
- return false;
- }
- if (!precise) {
- return true;
- }
- var box0 = this.boundingBox;
- var box1 = boundingInfo.boundingBox;
- if (!axisOverlap(box0.directions[0], box0, box1))
- return false;
- if (!axisOverlap(box0.directions[1], box0, box1))
- return false;
- if (!axisOverlap(box0.directions[2], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[0], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[1], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[2], box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
- return false;
- return true;
- };
- return BoundingInfo;
- })();
- BABYLON.BoundingInfo = BoundingInfo;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AbstractMesh = (function (_super) {
- __extends(AbstractMesh, _super);
- // Constructor
- function AbstractMesh(name, scene) {
- var _this = this;
- _super.call(this, name, scene);
- // Properties
- this.definedFacingForward = true; // orientation for POV movement & rotation
- this.position = new BABYLON.Vector3(0, 0, 0);
- this.rotation = new BABYLON.Vector3(0, 0, 0);
- this.scaling = new BABYLON.Vector3(1, 1, 1);
- this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
- this.visibility = 1.0;
- this.alphaIndex = Number.MAX_VALUE;
- this.infiniteDistance = false;
- this.isVisible = true;
- this.isPickable = true;
- this.showBoundingBox = false;
- this.showSubMeshesBoundingBox = false;
- this.onDispose = null;
- this.isBlocker = false;
- this.renderingGroupId = 0;
- this.receiveShadows = false;
- this.renderOutline = false;
- this.outlineColor = BABYLON.Color3.Red();
- this.outlineWidth = 0.02;
- this.renderOverlay = false;
- this.overlayColor = BABYLON.Color3.Red();
- this.overlayAlpha = 0.5;
- this.hasVertexAlpha = false;
- this.useVertexColors = true;
- this.applyFog = true;
- this.computeBonesUsingShaders = true;
- this.scalingDeterminant = 1;
- this.numBoneInfluencers = 4;
- this.useOctreeForRenderingSelection = true;
- this.useOctreeForPicking = true;
- this.useOctreeForCollisions = true;
- this.layerMask = 0x0FFFFFFF;
- this.alwaysSelectAsActiveMesh = false;
- // Physics
- this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
- // Collisions
- this._checkCollisions = false;
- this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
- this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
- this._collider = new BABYLON.Collider();
- this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- // Edges
- this.edgesWidth = 1;
- this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
- // Cache
- this._localWorld = BABYLON.Matrix.Zero();
- this._worldMatrix = BABYLON.Matrix.Zero();
- this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
- this._absolutePosition = BABYLON.Vector3.Zero();
- this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
- this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
- this._isDirty = false;
- this._pivotMatrix = BABYLON.Matrix.Identity();
- this._isDisposed = false;
- this._renderId = 0;
- this._intersectionsInProgress = new Array();
- this._onAfterWorldMatrixUpdate = new Array();
- this._isWorldMatrixFrozen = false;
- this._unIndexed = false;
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- //TODO move this to the collision coordinator!
- if (_this.getScene().workerCollisions)
- newPosition.multiplyInPlace(_this._collider.radius);
- newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
- if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
- _this.position.addInPlace(_this._diffPositionForCollisions);
- }
- if (_this.onCollide && collidedMesh) {
- _this.onCollide(collidedMesh);
- }
- if (_this.onCollisionPositionChange) {
- _this.onCollisionPositionChange(_this.position);
- }
- };
- scene.addMesh(this);
- }
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_X;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_Y;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_Z;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_ALL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "skeleton", {
- get: function () {
- return this._skeleton;
- },
- set: function (value) {
- if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
- this._skeleton._unregisterMeshWithPoseMatrix(this);
- }
- if (value && value.needInitialSkinMatrix) {
- value._registerMeshWithPoseMatrix(this);
- }
- this._skeleton = value;
- if (!this._skeleton) {
- this._bonesTransformMatrices = null;
- }
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
- this._poseMatrix.copyFrom(matrix);
- };
- AbstractMesh.prototype.getPoseMatrix = function () {
- return this._poseMatrix;
- };
- AbstractMesh.prototype.disableEdgesRendering = function () {
- if (this._edgesRenderer !== undefined) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = undefined;
- }
- };
- AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
- if (epsilon === void 0) { epsilon = 0.95; }
- if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
- this.disableEdgesRendering();
- this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
- };
- Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.getLOD = function (camera) {
- return this;
- };
- AbstractMesh.prototype.getTotalVertices = function () {
- return 0;
- };
- AbstractMesh.prototype.getIndices = function () {
- return null;
- };
- AbstractMesh.prototype.getVerticesData = function (kind) {
- return null;
- };
- AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
- return false;
- };
- AbstractMesh.prototype.getBoundingInfo = function () {
- if (this._masterMesh) {
- return this._masterMesh.getBoundingInfo();
- }
- if (!this._boundingInfo) {
- this._updateBoundingInfo();
- }
- return this._boundingInfo;
- };
- Object.defineProperty(AbstractMesh.prototype, "useBones", {
- get: function () {
- return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype._preActivate = function () {
- };
- AbstractMesh.prototype._activate = function (renderId) {
- this._renderId = renderId;
- };
- AbstractMesh.prototype.getWorldMatrix = function () {
- if (this._masterMesh) {
- return this._masterMesh.getWorldMatrix();
- }
- if (this._currentRenderId !== this.getScene().getRenderId()) {
- this.computeWorldMatrix();
- }
- return this._worldMatrix;
- };
- Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
- get: function () {
- return this._worldMatrix;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
- get: function () {
- return this._absolutePosition;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.freezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
- this.computeWorldMatrix(true);
- this._isWorldMatrixFrozen = true;
- };
- AbstractMesh.prototype.unfreezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false;
- this.computeWorldMatrix(true);
- };
- Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
- get: function () {
- return this._isWorldMatrixFrozen;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.rotate = function (axis, amount, space) {
- axis.normalize();
- if (!this.rotationQuaternion) {
- this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
- this.rotation = BABYLON.Vector3.Zero();
- }
- var rotationQuaternion;
- if (!space || space === BABYLON.Space.LOCAL) {
- rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
- this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
- }
- else {
- if (this.parent) {
- var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
- }
- rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
- this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
- }
- };
- AbstractMesh.prototype.translate = function (axis, distance, space) {
- var displacementVector = axis.scale(distance);
- if (!space || space === BABYLON.Space.LOCAL) {
- var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
- this.setPositionWithLocalVector(tempV3);
- }
- else {
- this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
- }
- };
- AbstractMesh.prototype.getAbsolutePosition = function () {
- this.computeWorldMatrix();
- return this._absolutePosition;
- };
- AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
- if (!absolutePosition) {
- return;
- }
- var absolutePositionX;
- var absolutePositionY;
- var absolutePositionZ;
- if (absolutePosition.x === undefined) {
- if (arguments.length < 3) {
- return;
- }
- absolutePositionX = arguments[0];
- absolutePositionY = arguments[1];
- absolutePositionZ = arguments[2];
- }
- else {
- absolutePositionX = absolutePosition.x;
- absolutePositionY = absolutePosition.y;
- absolutePositionZ = absolutePosition.z;
- }
- if (this.parent) {
- var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
- this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
- }
- else {
- this.position.x = absolutePositionX;
- this.position.y = absolutePositionY;
- this.position.z = absolutePositionZ;
- }
- };
- // ================================== Point of View Movement =================================
- /**
- * Perform relative position change from the point of view of behind the front of the mesh.
- * This is performed taking into account the meshes current rotation, so you do not have to care.
- * Supports definition of mesh facing forward or backward.
- * @param {number} amountRight
- * @param {number} amountUp
- * @param {number} amountForward
- */
- AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
- this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
- };
- /**
- * Calculate relative position change from the point of view of behind the front of the mesh.
- * This is performed taking into account the meshes current rotation, so you do not have to care.
- * Supports definition of mesh facing forward or backward.
- * @param {number} amountRight
- * @param {number} amountUp
- * @param {number} amountForward
- */
- AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
- var rotMatrix = new BABYLON.Matrix();
- var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
- rotQuaternion.toRotationMatrix(rotMatrix);
- var translationDelta = BABYLON.Vector3.Zero();
- var defForwardMult = this.definedFacingForward ? -1 : 1;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
- return translationDelta;
- };
- // ================================== Point of View Rotation =================================
- /**
- * Perform relative rotation change from the point of view of behind the front of the mesh.
- * Supports definition of mesh facing forward or backward.
- * @param {number} flipBack
- * @param {number} twirlClockwise
- * @param {number} tiltRight
- */
- AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
- };
- /**
- * Calculate relative rotation change from the point of view of behind the front of the mesh.
- * Supports definition of mesh facing forward or backward.
- * @param {number} flipBack
- * @param {number} twirlClockwise
- * @param {number} tiltRight
- */
- AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- var defForwardMult = this.definedFacingForward ? 1 : -1;
- return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
- };
- AbstractMesh.prototype.setPivotMatrix = function (matrix) {
- this._pivotMatrix = matrix;
- this._cache.pivotMatrixUpdated = true;
- };
- AbstractMesh.prototype.getPivotMatrix = function () {
- return this._pivotMatrix;
- };
- AbstractMesh.prototype._isSynchronized = function () {
- if (this._isDirty) {
- return false;
- }
- if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
- return false;
- if (this._cache.pivotMatrixUpdated) {
- return false;
- }
- if (this.infiniteDistance) {
- return false;
- }
- if (!this._cache.position.equals(this.position))
- return false;
- if (this.rotationQuaternion) {
- if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
- return false;
- }
- else {
- if (!this._cache.rotation.equals(this.rotation))
- return false;
- }
- if (!this._cache.scaling.equals(this.scaling))
- return false;
- return true;
- };
- AbstractMesh.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.localMatrixUpdated = false;
- this._cache.position = BABYLON.Vector3.Zero();
- this._cache.scaling = BABYLON.Vector3.Zero();
- this._cache.rotation = BABYLON.Vector3.Zero();
- this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
- this._cache.billboardMode = -1;
- };
- AbstractMesh.prototype.markAsDirty = function (property) {
- if (property === "rotation") {
- this.rotationQuaternion = null;
- }
- this._currentRenderId = Number.MAX_VALUE;
- this._isDirty = true;
- };
- AbstractMesh.prototype._updateBoundingInfo = function () {
- this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
- this._boundingInfo.update(this.worldMatrixFromCache);
- this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- };
- AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
- if (!this.subMeshes) {
- return;
- }
- for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
- var subMesh = this.subMeshes[subIndex];
- if (!subMesh.IsGlobal) {
- subMesh.updateBoundingInfo(matrix);
- }
- }
- };
- AbstractMesh.prototype.computeWorldMatrix = function (force) {
- if (this._isWorldMatrixFrozen) {
- return this._worldMatrix;
- }
- if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
- this._currentRenderId = this.getScene().getRenderId();
- return this._worldMatrix;
- }
- this._cache.position.copyFrom(this.position);
- this._cache.scaling.copyFrom(this.scaling);
- this._cache.pivotMatrixUpdated = false;
- this._cache.billboardMode = this.billboardMode;
- this._currentRenderId = this.getScene().getRenderId();
- this._isDirty = false;
- // Scaling
- BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
- // Rotation
- if (this.rotationQuaternion) {
- this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
- this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
- }
- else {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
- this._cache.rotation.copyFrom(this.rotation);
- }
- // Translation
- if (this.infiniteDistance && !this.parent) {
- var camera = this.getScene().activeCamera;
- if (camera) {
- var cameraWorldMatrix = camera.getWorldMatrix();
- var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
- BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
- }
- }
- else {
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
- }
- // Composing transformations
- this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
- BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
- // Billboarding
- if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
- var localPosition = this.position.clone();
- var zero = this.getScene().activeCamera.globalPosition.clone();
- if (this.parent && this.parent.position) {
- localPosition.addInPlace(this.parent.position);
- BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
- }
- if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
- zero.x = localPosition.x + BABYLON.Engine.Epsilon;
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
- zero.y = localPosition.y + 0.001;
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
- zero.z = localPosition.z + 0.001;
- }
- BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
- BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
- BABYLON.Tmp.Matrix[3].invert();
- BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
- this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
- }
- // Local world
- BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
- // Parent
- if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
- this._markSyncedWithParent();
- if (this._meshToBoneReferal) {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
- }
- else {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
- }
- }
- else {
- this._worldMatrix.copyFrom(this._localWorld);
- }
- // Bounding info
- this._updateBoundingInfo();
- // Absolute position
- this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
- // Callbacks
- for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
- this._onAfterWorldMatrixUpdate[callbackIndex](this);
- }
- if (!this._poseMatrix) {
- this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
- }
- return this._worldMatrix;
- };
- /**
- * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
- * @param func: callback function to add
- */
- AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
- this._onAfterWorldMatrixUpdate.push(func);
- };
- AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
- var index = this._onAfterWorldMatrixUpdate.indexOf(func);
- if (index > -1) {
- this._onAfterWorldMatrixUpdate.splice(index, 1);
- }
- };
- AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
- this.computeWorldMatrix();
- this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
- };
- AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
- this.computeWorldMatrix();
- var invLocalWorldMatrix = this._localWorld.clone();
- invLocalWorldMatrix.invert();
- return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
- };
- AbstractMesh.prototype.locallyTranslate = function (vector3) {
- this.computeWorldMatrix(true);
- this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
- };
- AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
- /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
- /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
- /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
- /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
- /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
- /// <returns>Mesh oriented towards targetMesh</returns>
- yawCor = yawCor || 0; // default to zero if undefined
- pitchCor = pitchCor || 0;
- rollCor = rollCor || 0;
- var dv = targetPoint.subtract(this.position);
- var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
- var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
- var pitch = Math.atan2(dv.y, len);
- this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
- };
- AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
- this._meshToBoneReferal = affectedMesh;
- this.parent = bone;
- if (bone.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- };
- AbstractMesh.prototype.detachFromBone = function () {
- if (this.parent.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- this._meshToBoneReferal = null;
- this.parent = null;
- };
- AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
- return this._boundingInfo.isInFrustum(frustumPlanes);
- };
- AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
- if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
- return false;
- }
- return true;
- };
- AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
- if (!this._boundingInfo || !mesh._boundingInfo) {
- return false;
- }
- return this._boundingInfo.intersects(mesh._boundingInfo, precise);
- };
- AbstractMesh.prototype.intersectsPoint = function (point) {
- if (!this._boundingInfo) {
- return false;
- }
- return this._boundingInfo.intersectsPoint(point);
- };
- // Physics
- AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
- var physicsEngine = this.getScene().getPhysicsEngine();
- if (!physicsEngine) {
- return null;
- }
- impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
- if (impostor.impostor) {
- // Old API
- options = impostor;
- impostor = impostor.impostor;
- }
- if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
- physicsEngine._unregisterMesh(this);
- return null;
- }
- if (!options) {
- options = { mass: 0, friction: 0.2, restitution: 0.2 };
- }
- else {
- if (!options.mass && options.mass !== 0)
- options.mass = 0;
- if (!options.friction && options.friction !== 0)
- options.friction = 0.2;
- if (!options.restitution && options.restitution !== 0)
- options.restitution = 0.2;
- }
- this._physicImpostor = impostor;
- this._physicsMass = options.mass;
- this._physicsFriction = options.friction;
- this._physicRestitution = options.restitution;
- return physicsEngine._registerMesh(this, impostor, options);
- };
- AbstractMesh.prototype.getPhysicsImpostor = function () {
- if (!this._physicImpostor) {
- return BABYLON.PhysicsEngine.NoImpostor;
- }
- return this._physicImpostor;
- };
- AbstractMesh.prototype.getPhysicsMass = function () {
- if (!this._physicsMass) {
- return 0;
- }
- return this._physicsMass;
- };
- AbstractMesh.prototype.getPhysicsFriction = function () {
- if (!this._physicsFriction) {
- return 0;
- }
- return this._physicsFriction;
- };
- AbstractMesh.prototype.getPhysicsRestitution = function () {
- if (!this._physicRestitution) {
- return 0;
- }
- return this._physicRestitution;
- };
- AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
- };
- AbstractMesh.prototype.getDistanceToCamera = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return this.absolutePosition.subtract(camera.position).length();
- };
- AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
- if (!this._physicImpostor) {
- return;
- }
- this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
- };
- AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
- if (!this._physicImpostor) {
- return;
- }
- this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
- };
- AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
- BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
- this.updatePhysicsBody();
- };
- AbstractMesh.prototype.updatePhysicsBody = function () {
- if (!this._physicImpostor) {
- return;
- }
- this.getScene().getPhysicsEngine()._updateBodyPosition(this);
- };
- Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
- // Collisions
- get: function () {
- return this._checkCollisions;
- },
- set: function (collisionEnabled) {
- this._checkCollisions = collisionEnabled;
- if (this.getScene().workerCollisions) {
- this.getScene().collisionCoordinator.onMeshUpdated(this);
- }
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.moveWithCollisions = function (velocity) {
- var globalPosition = this.getAbsolutePosition();
- globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
- this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
- this._collider.radius = this.ellipsoid;
- this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
- };
- // Submeshes octree
- /**
- * This function will create an octree to help select the right submeshes for rendering, picking and collisions
- * Please note that you must have a decent number of submeshes to get performance improvements when using octree
- */
- AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
- if (maxCapacity === void 0) { maxCapacity = 64; }
- if (maxDepth === void 0) { maxDepth = 2; }
- if (!this._submeshesOctree) {
- this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
- }
- this.computeWorldMatrix(true);
- // Update octree
- var bbox = this.getBoundingInfo().boundingBox;
- this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
- return this._submeshesOctree;
- };
- // Collisions
- AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
- this._generatePointsArray();
- // Transformation
- if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
- subMesh._lastColliderTransformMatrix = transformMatrix.clone();
- subMesh._lastColliderWorldVertices = [];
- subMesh._trianglePlanes = [];
- var start = subMesh.verticesStart;
- var end = (subMesh.verticesStart + subMesh.verticesCount);
- for (var i = start; i < end; i++) {
- subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
- }
- }
- // Collide
- collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
- if (collider.collisionFound) {
- collider.collidedMesh = this;
- }
- };
- AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
- var subMeshes;
- var len;
- // Octrees
- if (this._submeshesOctree && this.useOctreeForCollisions) {
- var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
- var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = this.subMeshes;
- len = subMeshes.length;
- }
- for (var index = 0; index < len; index++) {
- var subMesh = subMeshes[index];
- // Bounding test
- if (len > 1 && !subMesh._checkCollision(collider))
- continue;
- this._collideForSubMesh(subMesh, transformMatrix, collider);
- }
- };
- AbstractMesh.prototype._checkCollision = function (collider) {
- // Bounding box test
- if (!this._boundingInfo._checkCollision(collider))
- return;
- // Transformation matrix
- BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
- this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
- this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
- };
- // Picking
- AbstractMesh.prototype._generatePointsArray = function () {
- return false;
- };
- AbstractMesh.prototype.intersects = function (ray, fastCheck) {
- var pickingInfo = new BABYLON.PickingInfo();
- if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
- return pickingInfo;
- }
- if (!this._generatePointsArray()) {
- return pickingInfo;
- }
- var intersectInfo = null;
- // Octrees
- var subMeshes;
- var len;
- if (this._submeshesOctree && this.useOctreeForPicking) {
- var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
- var intersections = this._submeshesOctree.intersectsRay(worldRay);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = this.subMeshes;
- len = subMeshes.length;
- }
- for (var index = 0; index < len; index++) {
- var subMesh = subMeshes[index];
- // Bounding test
- if (len > 1 && !subMesh.canIntersects(ray))
- continue;
- var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
- if (currentIntersectInfo) {
- if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
- intersectInfo = currentIntersectInfo;
- intersectInfo.subMeshId = index;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- if (intersectInfo) {
- // Get picked point
- var world = this.getWorldMatrix();
- var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
- var direction = ray.direction.clone();
- direction = direction.scale(intersectInfo.distance);
- var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
- var pickedPoint = worldOrigin.add(worldDirection);
- // Return result
- pickingInfo.hit = true;
- pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
- pickingInfo.pickedPoint = pickedPoint;
- pickingInfo.pickedMesh = this;
- pickingInfo.bu = intersectInfo.bu;
- pickingInfo.bv = intersectInfo.bv;
- pickingInfo.faceId = intersectInfo.faceId;
- pickingInfo.subMeshId = intersectInfo.subMeshId;
- return pickingInfo;
- }
- return pickingInfo;
- };
- AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return null;
- };
- AbstractMesh.prototype.releaseSubMeshes = function () {
- if (this.subMeshes) {
- while (this.subMeshes.length) {
- this.subMeshes[0].dispose();
- }
- }
- else {
- this.subMeshes = new Array();
- }
- };
- AbstractMesh.prototype.dispose = function (doNotRecurse) {
- var index;
- // Skeleton
- this.skeleton = null;
- // Animations
- this.getScene().stopAnimation(this);
- // Physics
- if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
- this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
- }
- // Intersections in progress
- for (index = 0; index < this._intersectionsInProgress.length; index++) {
- var other = this._intersectionsInProgress[index];
- var pos = other._intersectionsInProgress.indexOf(this);
- other._intersectionsInProgress.splice(pos, 1);
- }
- this._intersectionsInProgress = [];
- // Edges
- if (this._edgesRenderer) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = null;
- }
- // SubMeshes
- this.releaseSubMeshes();
- // Remove from scene
- this.getScene().removeMesh(this);
- if (!doNotRecurse) {
- // Particles
- for (index = 0; index < this.getScene().particleSystems.length; index++) {
- if (this.getScene().particleSystems[index].emitter === this) {
- this.getScene().particleSystems[index].dispose();
- index--;
- }
- }
- // Children
- var objects = this.getScene().meshes.slice(0);
- for (index = 0; index < objects.length; index++) {
- if (objects[index].parent === this) {
- objects[index].dispose();
- }
- }
- }
- else {
- for (index = 0; index < this.getScene().meshes.length; index++) {
- var obj = this.getScene().meshes[index];
- if (obj.parent === this) {
- obj.parent = null;
- obj.computeWorldMatrix(true);
- }
- }
- }
- this._onAfterWorldMatrixUpdate = [];
- this._isDisposed = true;
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- // Statics
- AbstractMesh._BILLBOARDMODE_NONE = 0;
- AbstractMesh._BILLBOARDMODE_X = 1;
- AbstractMesh._BILLBOARDMODE_Y = 2;
- AbstractMesh._BILLBOARDMODE_Z = 4;
- AbstractMesh._BILLBOARDMODE_ALL = 7;
- return AbstractMesh;
- })(BABYLON.Node);
- BABYLON.AbstractMesh = AbstractMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Light = (function (_super) {
- __extends(Light, _super);
- function Light(name, scene) {
- _super.call(this, name, scene);
- this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
- this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
- this.intensity = 1.0;
- this.range = Number.MAX_VALUE;
- this.includeOnlyWithLayerMask = 0;
- this.includedOnlyMeshes = new Array();
- this.excludedMeshes = new Array();
- this.excludeWithLayerMask = 0;
- // PBR Properties.
- this.radius = 0.00001;
- this._excludedMeshesIds = new Array();
- this._includedOnlyMeshesIds = new Array();
- scene.addLight(this);
- }
- Light.prototype.getShadowGenerator = function () {
- return this._shadowGenerator;
- };
- Light.prototype.getAbsolutePosition = function () {
- return BABYLON.Vector3.Zero();
- };
- Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
- };
- Light.prototype._getWorldMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- Light.prototype.canAffectMesh = function (mesh) {
- if (!mesh) {
- return true;
- }
- if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
- return false;
- }
- if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
- return false;
- }
- if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
- return false;
- }
- if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
- return false;
- }
- return true;
- };
- Light.prototype.getWorldMatrix = function () {
- this._currentRenderId = this.getScene().getRenderId();
- var worldMatrix = this._getWorldMatrix();
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._parentedWorldMatrix) {
- this._parentedWorldMatrix = BABYLON.Matrix.Identity();
- }
- worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
- this._markSyncedWithParent();
- return this._parentedWorldMatrix;
- }
- return worldMatrix;
- };
- Light.prototype.dispose = function () {
- if (this._shadowGenerator) {
- this._shadowGenerator.dispose();
- this._shadowGenerator = null;
- }
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeLight(this);
- };
- Light.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- if (this.intensity) {
- serializationObject.intensity = this.intensity;
- }
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- serializationObject.range = this.range;
- serializationObject.radius = this.radius;
- serializationObject.diffuse = this.diffuse.asArray();
- serializationObject.specular = this.specular.asArray();
- return serializationObject;
- };
- Light.Parse = function (parsedLight, scene) {
- var light;
- switch (parsedLight.type) {
- case 0:
- light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
- break;
- case 1:
- light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
- light.position = BABYLON.Vector3.FromArray(parsedLight.position);
- break;
- case 2:
- light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
- break;
- case 3:
- light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
- light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
- break;
- }
- light.id = parsedLight.id;
- BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
- if (parsedLight.intensity !== undefined) {
- light.intensity = parsedLight.intensity;
- }
- if (parsedLight.range) {
- light.range = parsedLight.range;
- }
- if (parsedLight.radius) {
- light.radius = parsedLight.radius;
- }
- light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
- light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
- if (parsedLight.excludedMeshesIds) {
- light._excludedMeshesIds = parsedLight.excludedMeshesIds;
- }
- // Parent
- if (parsedLight.parentId) {
- light._waitingParentId = parsedLight.parentId;
- }
- if (parsedLight.includedOnlyMeshesIds) {
- light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
- }
- // Animations
- if (parsedLight.animations) {
- for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
- var parsedAnimation = parsedLight.animations[animationIndex];
- light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
- }
- if (parsedLight.autoAnimate) {
- scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
- }
- return light;
- };
- return Light;
- })(BABYLON.Node);
- BABYLON.Light = Light;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PointLight = (function (_super) {
- __extends(PointLight, _super);
- function PointLight(name, position, scene) {
- _super.call(this, name, scene);
- this.position = position;
- }
- PointLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- PointLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
- if (this.parent && this.parent.getWorldMatrix) {
- this.computeTransformedPosition();
- effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
- return;
- }
- effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
- };
- PointLight.prototype.needCube = function () {
- return true;
- };
- PointLight.prototype.supportsVSM = function () {
- return false;
- };
- PointLight.prototype.needRefreshPerFrame = function () {
- return false;
- };
- PointLight.prototype.getShadowDirection = function (faceIndex) {
- switch (faceIndex) {
- case 0:
- return new BABYLON.Vector3(1, 0, 0);
- case 1:
- return new BABYLON.Vector3(-1, 0, 0);
- case 2:
- return new BABYLON.Vector3(0, -1, 0);
- case 3:
- return new BABYLON.Vector3(0, 1, 0);
- case 4:
- return new BABYLON.Vector3(0, 0, 1);
- case 5:
- return new BABYLON.Vector3(0, 0, -1);
- }
- return BABYLON.Vector3.Zero();
- };
- PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
- };
- PointLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- PointLight.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.type = 0;
- serializationObject.position = this.position.asArray();
- return serializationObject;
- };
- return PointLight;
- })(BABYLON.Light);
- BABYLON.PointLight = PointLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SpotLight = (function (_super) {
- __extends(SpotLight, _super);
- function SpotLight(name, position, direction, angle, exponent, scene) {
- _super.call(this, name, scene);
- this.position = position;
- this.direction = direction;
- this.angle = angle;
- this.exponent = exponent;
- }
- SpotLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
- };
- SpotLight.prototype.needCube = function () {
- return false;
- };
- SpotLight.prototype.supportsVSM = function () {
- return true;
- };
- SpotLight.prototype.needRefreshPerFrame = function () {
- return false;
- };
- SpotLight.prototype.getShadowDirection = function (faceIndex) {
- return this.direction;
- };
- SpotLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
- return this.direction;
- };
- SpotLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
- var normalizeDirection;
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._transformedDirection) {
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- this.computeTransformedPosition();
- BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
- effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
- normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
- }
- else {
- effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
- normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
- }
- effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
- };
- SpotLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- SpotLight.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.type = 2;
- serializationObject.position = this.position.asArray();
- serializationObject.direction = this.position.asArray();
- serializationObject.angle = this.angle;
- serializationObject.exponent = this.exponent;
- return serializationObject;
- };
- return SpotLight;
- })(BABYLON.Light);
- BABYLON.SpotLight = SpotLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var HemisphericLight = (function (_super) {
- __extends(HemisphericLight, _super);
- function HemisphericLight(name, direction, scene) {
- _super.call(this, name, scene);
- this.direction = direction;
- this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
- }
- HemisphericLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
- return this.direction;
- };
- HemisphericLight.prototype.getShadowGenerator = function () {
- return null;
- };
- HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
- var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
- effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
- effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
- };
- HemisphericLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- return this._worldMatrix;
- };
- HemisphericLight.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.type = 3;
- serializationObject.direction = this.direction.asArray();
- serializationObject.groundColor = this.groundColor.asArray();
- return serializationObject;
- };
- return HemisphericLight;
- })(BABYLON.Light);
- BABYLON.HemisphericLight = HemisphericLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DirectionalLight = (function (_super) {
- __extends(DirectionalLight, _super);
- function DirectionalLight(name, direction, scene) {
- _super.call(this, name, scene);
- this.direction = direction;
- this.shadowOrthoScale = 0.5;
- this.autoUpdateExtends = true;
- // Cache
- this._orthoLeft = Number.MAX_VALUE;
- this._orthoRight = Number.MIN_VALUE;
- this._orthoTop = Number.MIN_VALUE;
- this._orthoBottom = Number.MAX_VALUE;
- this.position = direction.scale(-1);
- }
- DirectionalLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- DirectionalLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
- return this.direction;
- };
- DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- // Check extends
- if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
- var tempVector3 = BABYLON.Vector3.Zero();
- this._orthoLeft = Number.MAX_VALUE;
- this._orthoRight = Number.MIN_VALUE;
- this._orthoTop = Number.MIN_VALUE;
- this._orthoBottom = Number.MAX_VALUE;
- for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
- var mesh = renderList[meshIndex];
- if (!mesh) {
- continue;
- }
- var boundingInfo = mesh.getBoundingInfo();
- if (!boundingInfo) {
- continue;
- }
- var boundingBox = boundingInfo.boundingBox;
- for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
- BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
- if (tempVector3.x < this._orthoLeft)
- this._orthoLeft = tempVector3.x;
- if (tempVector3.y < this._orthoBottom)
- this._orthoBottom = tempVector3.y;
- if (tempVector3.x > this._orthoRight)
- this._orthoRight = tempVector3.x;
- if (tempVector3.y > this._orthoTop)
- this._orthoTop = tempVector3.y;
- }
- }
- }
- var xOffset = this._orthoRight - this._orthoLeft;
- var yOffset = this._orthoTop - this._orthoBottom;
- BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
- };
- DirectionalLight.prototype.supportsVSM = function () {
- return true;
- };
- DirectionalLight.prototype.needRefreshPerFrame = function () {
- return true;
- };
- DirectionalLight.prototype.needCube = function () {
- return false;
- };
- DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
- return this.direction;
- };
- DirectionalLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._transformedDirection) {
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
- effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
- return;
- }
- effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
- };
- DirectionalLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- DirectionalLight.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.type = 1;
- serializationObject.position = this.position.asArray();
- serializationObject.direction = this.direction.asArray();
- return serializationObject;
- };
- return DirectionalLight;
- })(BABYLON.Light);
- BABYLON.DirectionalLight = DirectionalLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ShadowGenerator = (function () {
- function ShadowGenerator(mapSize, light) {
- var _this = this;
- // Members
- this._filter = ShadowGenerator.FILTER_NONE;
- this.blurScale = 2;
- this._blurBoxOffset = 0;
- this._bias = 0.00005;
- this._lightDirection = BABYLON.Vector3.Zero();
- this.forceBackFacesOnly = false;
- this._darkness = 0;
- this._transparencyShadow = false;
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._projectionMatrix = BABYLON.Matrix.Zero();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._worldViewProjection = BABYLON.Matrix.Zero();
- this._currentFaceIndex = 0;
- this._currentFaceIndexCache = 0;
- this._light = light;
- this._scene = light.getScene();
- this._mapSize = mapSize;
- light._shadowGenerator = this;
- // Render target
- this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
- this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._shadowMap.anisotropicFilteringLevel = 1;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
- this._shadowMap.renderParticles = false;
- this._shadowMap.onBeforeRender = function (faceIndex) {
- _this._currentFaceIndex = faceIndex;
- };
- this._shadowMap.onAfterUnbind = function () {
- if (!_this.useBlurVarianceShadowMap) {
- return;
- }
- if (!_this._shadowMap2) {
- _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
- _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
- _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
- _this._downSamplePostprocess.onApply = function (effect) {
- effect.setTexture("textureSampler", _this._shadowMap);
- };
- _this.blurBoxOffset = 1;
- }
- _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
- };
- // Custom render function
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- var scene = _this._scene;
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(_this._effect);
- mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
- var material = subMesh.getMaterial();
- _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
- _this._effect.setVector3("lightPosition", _this.getLight().position);
- if (_this.getLight().needCube()) {
- _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- _this._effect.setTexture("diffuseSampler", alphaTexture);
- _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- if (_this.forceBackFacesOnly) {
- engine.setState(true, 0, false, true);
- }
- // Draw
- mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
- if (_this.forceBackFacesOnly) {
- engine.setState(true, 0, false, false);
- }
- }
- else {
- // Need to reset refresh rate of the shadowMap
- _this._shadowMap.resetRefreshCounter();
- }
- };
- this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- if (_this._transparencyShadow) {
- for (index = 0; index < transparentSubMeshes.length; index++) {
- renderSubMesh(transparentSubMeshes.data[index]);
- }
- }
- };
- this._shadowMap.onClear = function (engine) {
- if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
- engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
- }
- else {
- engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
- }
- };
- }
- Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
- // Static
- get: function () {
- return ShadowGenerator._FILTER_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
- get: function () {
- return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
- get: function () {
- return ShadowGenerator._FILTER_POISSONSAMPLING;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
- get: function () {
- return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "bias", {
- get: function () {
- return this._bias;
- },
- set: function (bias) {
- this._bias = bias;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
- get: function () {
- return this._blurBoxOffset;
- },
- set: function (value) {
- var _this = this;
- if (this._blurBoxOffset === value) {
- return;
- }
- this._blurBoxOffset = value;
- if (this._boxBlurPostprocess) {
- this._boxBlurPostprocess.dispose();
- }
- this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
- this._boxBlurPostprocess.onApply = function (effect) {
- effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
- };
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "filter", {
- get: function () {
- return this._filter;
- },
- set: function (value) {
- if (this._filter === value) {
- return;
- }
- this._filter = value;
- if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
- this._shadowMap.anisotropicFilteringLevel = 16;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- }
- else {
- this._shadowMap.anisotropicFilteringLevel = 1;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
- (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
- this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
- var defines = [];
- if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
- defines.push("#define VSM");
- }
- if (this.getLight().needCube()) {
- defines.push("#define CUBEMAP");
- }
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var mesh = subMesh.getMesh();
- var material = subMesh.getMaterial();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- ShadowGenerator.prototype.getShadowMap = function () {
- return this._shadowMap;
- };
- ShadowGenerator.prototype.getShadowMapForRendering = function () {
- if (this._shadowMap2) {
- return this._shadowMap2;
- }
- return this._shadowMap;
- };
- ShadowGenerator.prototype.getLight = function () {
- return this._light;
- };
- // Methods
- ShadowGenerator.prototype.getTransformMatrix = function () {
- var scene = this._scene;
- if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
- return this._transformMatrix;
- }
- this._currentRenderID = scene.getRenderId();
- this._currentFaceIndexCache = this._currentFaceIndex;
- var lightPosition = this._light.position;
- BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
- if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
- this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
- }
- if (this._light.computeTransformedPosition()) {
- lightPosition = this._light.transformedPosition;
- }
- if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
- this._cachedPosition = lightPosition.clone();
- this._cachedDirection = this._lightDirection.clone();
- BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
- this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
- this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- }
- return this._transformMatrix;
- };
- ShadowGenerator.prototype.getDarkness = function () {
- return this._darkness;
- };
- ShadowGenerator.prototype.setDarkness = function (darkness) {
- if (darkness >= 1.0)
- this._darkness = 1.0;
- else if (darkness <= 0.0)
- this._darkness = 0.0;
- else
- this._darkness = darkness;
- };
- ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
- this._transparencyShadow = hasShadow;
- };
- ShadowGenerator.prototype._packHalf = function (depth) {
- var scale = depth * 255.0;
- var fract = scale - Math.floor(scale);
- return new BABYLON.Vector2(depth - fract / 255.0, fract);
- };
- ShadowGenerator.prototype.dispose = function () {
- this._shadowMap.dispose();
- if (this._shadowMap2) {
- this._shadowMap2.dispose();
- }
- if (this._downSamplePostprocess) {
- this._downSamplePostprocess.dispose();
- }
- if (this._boxBlurPostprocess) {
- this._boxBlurPostprocess.dispose();
- }
- };
- ShadowGenerator.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.lightId = this._light.id;
- serializationObject.mapSize = this.getShadowMap().getRenderSize();
- serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
- serializationObject.usePoissonSampling = this.usePoissonSampling;
- serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
- serializationObject.renderList = [];
- for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
- var mesh = this.getShadowMap().renderList[meshIndex];
- serializationObject.renderList.push(mesh.id);
- }
- return serializationObject;
- };
- ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
- //casting to point light, as light is missing the position attr and typescript complains.
- var light = scene.getLightByID(parsedShadowGenerator.lightId);
- var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
- for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
- var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
- shadowGenerator.getShadowMap().renderList.push(mesh);
- }
- if (parsedShadowGenerator.usePoissonSampling) {
- shadowGenerator.usePoissonSampling = true;
- }
- else if (parsedShadowGenerator.useVarianceShadowMap) {
- shadowGenerator.useVarianceShadowMap = true;
- }
- else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
- shadowGenerator.useBlurVarianceShadowMap = true;
- if (parsedShadowGenerator.blurScale) {
- shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
- }
- if (parsedShadowGenerator.blurBoxOffset) {
- shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
- }
- }
- if (parsedShadowGenerator.bias !== undefined) {
- shadowGenerator.bias = parsedShadowGenerator.bias;
- }
- shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
- return shadowGenerator;
- };
- ShadowGenerator._FILTER_NONE = 0;
- ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
- ShadowGenerator._FILTER_POISSONSAMPLING = 2;
- ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
- return ShadowGenerator;
- })();
- BABYLON.ShadowGenerator = ShadowGenerator;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
- if (boxMin.x > sphereCenter.x + sphereRadius)
- return false;
- if (sphereCenter.x - sphereRadius > boxMax.x)
- return false;
- if (boxMin.y > sphereCenter.y + sphereRadius)
- return false;
- if (sphereCenter.y - sphereRadius > boxMax.y)
- return false;
- if (boxMin.z > sphereCenter.z + sphereRadius)
- return false;
- if (sphereCenter.z - sphereRadius > boxMax.z)
- return false;
- return true;
- };
- var getLowestRoot = function (a, b, c, maxR) {
- var determinant = b * b - 4.0 * a * c;
- var result = { root: 0, found: false };
- if (determinant < 0)
- return result;
- var sqrtD = Math.sqrt(determinant);
- var r1 = (-b - sqrtD) / (2.0 * a);
- var r2 = (-b + sqrtD) / (2.0 * a);
- if (r1 > r2) {
- var temp = r2;
- r2 = r1;
- r1 = temp;
- }
- if (r1 > 0 && r1 < maxR) {
- result.root = r1;
- result.found = true;
- return result;
- }
- if (r2 > 0 && r2 < maxR) {
- result.root = r2;
- result.found = true;
- return result;
- }
- return result;
- };
- var Collider = (function () {
- function Collider() {
- this.radius = new BABYLON.Vector3(1, 1, 1);
- this.retry = 0;
- this.basePointWorld = BABYLON.Vector3.Zero();
- this.velocityWorld = BABYLON.Vector3.Zero();
- this.normalizedVelocity = BABYLON.Vector3.Zero();
- this._collisionPoint = BABYLON.Vector3.Zero();
- this._planeIntersectionPoint = BABYLON.Vector3.Zero();
- this._tempVector = BABYLON.Vector3.Zero();
- this._tempVector2 = BABYLON.Vector3.Zero();
- this._tempVector3 = BABYLON.Vector3.Zero();
- this._tempVector4 = BABYLON.Vector3.Zero();
- this._edge = BABYLON.Vector3.Zero();
- this._baseToVertex = BABYLON.Vector3.Zero();
- this._destinationPoint = BABYLON.Vector3.Zero();
- this._slidePlaneNormal = BABYLON.Vector3.Zero();
- this._displacementVector = BABYLON.Vector3.Zero();
- }
- // Methods
- Collider.prototype._initialize = function (source, dir, e) {
- this.velocity = dir;
- BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
- this.basePoint = source;
- source.multiplyToRef(this.radius, this.basePointWorld);
- dir.multiplyToRef(this.radius, this.velocityWorld);
- this.velocityWorldLength = this.velocityWorld.length();
- this.epsilon = e;
- this.collisionFound = false;
- };
- Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
- pa.subtractToRef(point, this._tempVector);
- pb.subtractToRef(point, this._tempVector2);
- BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
- var d = BABYLON.Vector3.Dot(this._tempVector4, n);
- if (d < 0)
- return false;
- pc.subtractToRef(point, this._tempVector3);
- BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
- d = BABYLON.Vector3.Dot(this._tempVector4, n);
- if (d < 0)
- return false;
- BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
- d = BABYLON.Vector3.Dot(this._tempVector4, n);
- return d >= 0;
- };
- Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
- var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
- var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
- if (distance > this.velocityWorldLength + max + sphereRadius) {
- return false;
- }
- if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
- return false;
- return true;
- };
- Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
- var t0;
- var embeddedInPlane = false;
- //defensive programming, actually not needed.
- if (!trianglePlaneArray) {
- trianglePlaneArray = [];
- }
- if (!trianglePlaneArray[faceIndex]) {
- trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
- trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
- }
- var trianglePlane = trianglePlaneArray[faceIndex];
- if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
- return;
- var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
- var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
- if (normalDotVelocity == 0) {
- if (Math.abs(signedDistToTrianglePlane) >= 1.0)
- return;
- embeddedInPlane = true;
- t0 = 0;
- }
- else {
- t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
- var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
- if (t0 > t1) {
- var temp = t1;
- t1 = t0;
- t0 = temp;
- }
- if (t0 > 1.0 || t1 < 0.0)
- return;
- if (t0 < 0)
- t0 = 0;
- if (t0 > 1.0)
- t0 = 1.0;
- }
- this._collisionPoint.copyFromFloats(0, 0, 0);
- var found = false;
- var t = 1.0;
- if (!embeddedInPlane) {
- this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
- this.velocity.scaleToRef(t0, this._tempVector);
- this._planeIntersectionPoint.addInPlace(this._tempVector);
- if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
- found = true;
- t = t0;
- this._collisionPoint.copyFrom(this._planeIntersectionPoint);
- }
- }
- if (!found) {
- var velocitySquaredLength = this.velocity.lengthSquared();
- var a = velocitySquaredLength;
- this.basePoint.subtractToRef(p1, this._tempVector);
- var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- var c = this._tempVector.lengthSquared() - 1.0;
- var lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p1);
- }
- this.basePoint.subtractToRef(p2, this._tempVector);
- b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- c = this._tempVector.lengthSquared() - 1.0;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p2);
- }
- this.basePoint.subtractToRef(p3, this._tempVector);
- b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- c = this._tempVector.lengthSquared() - 1.0;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p3);
- }
- p2.subtractToRef(p1, this._edge);
- p1.subtractToRef(this.basePoint, this._baseToVertex);
- var edgeSquaredLength = this._edge.lengthSquared();
- var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p1.addToRef(this._edge, this._collisionPoint);
- }
- }
- p3.subtractToRef(p2, this._edge);
- p2.subtractToRef(this.basePoint, this._baseToVertex);
- edgeSquaredLength = this._edge.lengthSquared();
- edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p2.addToRef(this._edge, this._collisionPoint);
- }
- }
- p1.subtractToRef(p3, this._edge);
- p3.subtractToRef(this.basePoint, this._baseToVertex);
- edgeSquaredLength = this._edge.lengthSquared();
- edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p3.addToRef(this._edge, this._collisionPoint);
- }
- }
- }
- if (found) {
- var distToCollision = t * this.velocity.length();
- if (!this.collisionFound || distToCollision < this.nearestDistance) {
- if (!this.intersectionPoint) {
- this.intersectionPoint = this._collisionPoint.clone();
- }
- else {
- this.intersectionPoint.copyFrom(this._collisionPoint);
- }
- this.nearestDistance = distToCollision;
- this.collisionFound = true;
- }
- }
- };
- Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
- for (var i = indexStart; i < indexEnd; i += 3) {
- var p1 = pts[indices[i] - decal];
- var p2 = pts[indices[i + 1] - decal];
- var p3 = pts[indices[i + 2] - decal];
- this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
- }
- };
- Collider.prototype._getResponse = function (pos, vel) {
- pos.addToRef(vel, this._destinationPoint);
- vel.scaleInPlace((this.nearestDistance / vel.length()));
- this.basePoint.addToRef(vel, pos);
- pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
- this._slidePlaneNormal.normalize();
- this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
- pos.addInPlace(this._displacementVector);
- this.intersectionPoint.addInPlace(this._displacementVector);
- this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
- this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
- this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
- };
- return Collider;
- })();
- BABYLON.Collider = Collider;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- //WebWorker code will be inserted to this variable.
- BABYLON.CollisionWorker = "";
- (function (WorkerTaskType) {
- WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
- WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
- WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
- })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
- var WorkerTaskType = BABYLON.WorkerTaskType;
- (function (WorkerReplyType) {
- WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
- WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
- })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
- var WorkerReplyType = BABYLON.WorkerReplyType;
- var CollisionCoordinatorWorker = (function () {
- function CollisionCoordinatorWorker() {
- var _this = this;
- this._scaledPosition = BABYLON.Vector3.Zero();
- this._scaledVelocity = BABYLON.Vector3.Zero();
- this.onMeshUpdated = function (mesh) {
- _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
- };
- this.onGeometryUpdated = function (geometry) {
- _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
- };
- this._afterRender = function () {
- if (!_this._init)
- return;
- if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
- return;
- }
- //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
- //TODO make sure update runs as fast as possible to be able to update 60 FPS.
- if (_this._runningUpdated > 4) {
- return;
- }
- ++_this._runningUpdated;
- var payload = {
- updatedMeshes: _this._addUpdateMeshesList,
- updatedGeometries: _this._addUpdateGeometriesList,
- removedGeometries: _this._toRemoveGeometryArray,
- removedMeshes: _this._toRemoveMeshesArray
- };
- var message = {
- payload: payload,
- taskType: WorkerTaskType.UPDATE
- };
- var serializable = [];
- for (var id in payload.updatedGeometries) {
- if (payload.updatedGeometries.hasOwnProperty(id)) {
- //prepare transferables
- serializable.push(message.payload.updatedGeometries[id].indices.buffer);
- serializable.push(message.payload.updatedGeometries[id].normals.buffer);
- serializable.push(message.payload.updatedGeometries[id].positions.buffer);
- }
- }
- _this._worker.postMessage(message, serializable);
- _this._addUpdateMeshesList = {};
- _this._addUpdateGeometriesList = {};
- _this._toRemoveGeometryArray = [];
- _this._toRemoveMeshesArray = [];
- };
- this._onMessageFromWorker = function (e) {
- var returnData = e.data;
- if (returnData.error != WorkerReplyType.SUCCESS) {
- //TODO what errors can be returned from the worker?
- BABYLON.Tools.Warn("error returned from worker!");
- return;
- }
- switch (returnData.taskType) {
- case WorkerTaskType.INIT:
- _this._init = true;
- //Update the worked with ALL of the scene's current state
- _this._scene.meshes.forEach(function (mesh) {
- _this.onMeshAdded(mesh);
- });
- _this._scene.getGeometries().forEach(function (geometry) {
- _this.onGeometryAdded(geometry);
- });
- break;
- case WorkerTaskType.UPDATE:
- _this._runningUpdated--;
- break;
- case WorkerTaskType.COLLIDE:
- _this._runningCollisionTask = false;
- var returnPayload = returnData.payload;
- if (!_this._collisionsCallbackArray[returnPayload.collisionId])
- return;
- _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
- //cleanup
- _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
- break;
- }
- };
- this._collisionsCallbackArray = [];
- this._init = false;
- this._runningUpdated = 0;
- this._runningCollisionTask = false;
- this._addUpdateMeshesList = {};
- this._addUpdateGeometriesList = {};
- this._toRemoveGeometryArray = [];
- this._toRemoveMeshesArray = [];
- }
- CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
- if (!this._init)
- return;
- if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
- return;
- position.divideToRef(collider.radius, this._scaledPosition);
- velocity.divideToRef(collider.radius, this._scaledVelocity);
- this._collisionsCallbackArray[collisionIndex] = onNewPosition;
- var payload = {
- collider: {
- position: this._scaledPosition.asArray(),
- velocity: this._scaledVelocity.asArray(),
- radius: collider.radius.asArray()
- },
- collisionId: collisionIndex,
- excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
- maximumRetry: maximumRetry
- };
- var message = {
- payload: payload,
- taskType: WorkerTaskType.COLLIDE
- };
- this._worker.postMessage(message);
- };
- CollisionCoordinatorWorker.prototype.init = function (scene) {
- this._scene = scene;
- this._scene.registerAfterRender(this._afterRender);
- var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
- this._worker = new Worker(workerUrl);
- this._worker.onmessage = this._onMessageFromWorker;
- var message = {
- payload: {},
- taskType: WorkerTaskType.INIT
- };
- this._worker.postMessage(message);
- };
- CollisionCoordinatorWorker.prototype.destroy = function () {
- this._scene.unregisterAfterRender(this._afterRender);
- this._worker.terminate();
- };
- CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
- mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
- this.onMeshUpdated(mesh);
- };
- CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
- this._toRemoveMeshesArray.push(mesh.uniqueId);
- };
- CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
- //TODO this will break if the user uses his own function. This should be an array of callbacks!
- geometry.onGeometryUpdated = this.onGeometryUpdated;
- this.onGeometryUpdated(geometry);
- };
- CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
- this._toRemoveGeometryArray.push(geometry.id);
- };
- CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
- var submeshes = [];
- if (mesh.subMeshes) {
- submeshes = mesh.subMeshes.map(function (sm, idx) {
- return {
- position: idx,
- verticesStart: sm.verticesStart,
- verticesCount: sm.verticesCount,
- indexStart: sm.indexStart,
- indexCount: sm.indexCount,
- hasMaterial: !!sm.getMaterial(),
- sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
- sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
- boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
- boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
- };
- });
- }
- var geometryId = null;
- if (mesh instanceof BABYLON.Mesh) {
- geometryId = mesh.geometry ? mesh.geometry.id : null;
- }
- else if (mesh instanceof BABYLON.InstancedMesh) {
- geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
- }
- return {
- uniqueId: mesh.uniqueId,
- id: mesh.id,
- name: mesh.name,
- geometryId: geometryId,
- sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
- sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
- boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
- boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
- worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
- subMeshes: submeshes,
- checkCollisions: mesh.checkCollisions
- };
- };
- CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
- return {
- id: geometry.id,
- positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
- normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
- indices: new Int32Array(geometry.getIndices() || []),
- };
- };
- return CollisionCoordinatorWorker;
- })();
- BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
- var CollisionCoordinatorLegacy = (function () {
- function CollisionCoordinatorLegacy() {
- this._scaledPosition = BABYLON.Vector3.Zero();
- this._scaledVelocity = BABYLON.Vector3.Zero();
- this._finalPosition = BABYLON.Vector3.Zero();
- }
- CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
- position.divideToRef(collider.radius, this._scaledPosition);
- velocity.divideToRef(collider.radius, this._scaledVelocity);
- collider.collidedMesh = null;
- collider.retry = 0;
- collider.initialVelocity = this._scaledVelocity;
- collider.initialPosition = this._scaledPosition;
- this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
- this._finalPosition.multiplyInPlace(collider.radius);
- //run the callback
- onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
- };
- CollisionCoordinatorLegacy.prototype.init = function (scene) {
- this._scene = scene;
- };
- CollisionCoordinatorLegacy.prototype.destroy = function () {
- //Legacy need no destruction method.
- };
- //No update in legacy mode
- CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
- CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
- CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
- CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
- if (excludedMesh === void 0) { excludedMesh = null; }
- var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
- if (collider.retry >= maximumRetry) {
- finalPosition.copyFrom(position);
- return;
- }
- collider._initialize(position, velocity, closeDistance);
- // Check all meshes
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
- mesh._checkCollision(collider);
- }
- }
- if (!collider.collisionFound) {
- position.addToRef(velocity, finalPosition);
- return;
- }
- if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
- collider._getResponse(position, velocity);
- }
- if (velocity.length() <= closeDistance) {
- finalPosition.copyFrom(position);
- return;
- }
- collider.retry++;
- this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
- };
- return CollisionCoordinatorLegacy;
- })();
- BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRCameraMetrics = (function () {
- function VRCameraMetrics() {
- this.compensateDistortion = true;
- }
- Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
- get: function () {
- return this.hResolution / (2 * this.vResolution);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
- get: function () {
- return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
- get: function () {
- var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
- var h = (4 * meters) / this.hScreenSize;
- return BABYLON.Matrix.Translation(h, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
- get: function () {
- var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
- var h = (4 * meters) / this.hScreenSize;
- return BABYLON.Matrix.Translation(-h, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
- get: function () {
- return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
- get: function () {
- return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- VRCameraMetrics.GetDefault = function () {
- var result = new VRCameraMetrics();
- result.hResolution = 1280;
- result.vResolution = 800;
- result.hScreenSize = 0.149759993;
- result.vScreenSize = 0.0935999975;
- result.vScreenCenter = 0.0467999987,
- result.eyeToScreenDistance = 0.0410000011;
- result.lensSeparationDistance = 0.0635000020;
- result.interpupillaryDistance = 0.0640000030;
- result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
- result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
- result.postProcessScaleFactor = 1.714605507808412;
- result.lensCenterOffset = 0.151976421;
- return result;
- };
- return VRCameraMetrics;
- })();
- BABYLON.VRCameraMetrics = VRCameraMetrics;
- var Camera = (function (_super) {
- __extends(Camera, _super);
- function Camera(name, position, scene) {
- _super.call(this, name, scene);
- this.position = position;
- // Members
- this.upVector = BABYLON.Vector3.Up();
- this.orthoLeft = null;
- this.orthoRight = null;
- this.orthoBottom = null;
- this.orthoTop = null;
- this.fov = 0.8;
- this.minZ = 1.0;
- this.maxZ = 10000.0;
- this.inertia = 0.9;
- this.mode = Camera.PERSPECTIVE_CAMERA;
- this.isIntermediate = false;
- this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
- this.layerMask = 0x0FFFFFFF;
- this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
- // Camera rig members
- this.cameraRigMode = Camera.RIG_MODE_NONE;
- this._rigCameras = new Array();
- // Cache
- this._computedViewMatrix = BABYLON.Matrix.Identity();
- this._projectionMatrix = new BABYLON.Matrix();
- this._postProcesses = new Array();
- this._postProcessesTakenIndices = [];
- this._activeMeshes = new BABYLON.SmartArray(256);
- this._globalPosition = BABYLON.Vector3.Zero();
- scene.addCamera(this);
- if (!scene.activeCamera) {
- scene.activeCamera = this;
- }
- }
- Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
- get: function () {
- return Camera._PERSPECTIVE_CAMERA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
- get: function () {
- return Camera._ORTHOGRAPHIC_CAMERA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
- get: function () {
- return Camera._FOVMODE_VERTICAL_FIXED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
- get: function () {
- return Camera._FOVMODE_HORIZONTAL_FIXED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_NONE", {
- get: function () {
- return Camera._RIG_MODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_VR", {
- get: function () {
- return Camera._RIG_MODE_VR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera.prototype, "globalPosition", {
- get: function () {
- return this._globalPosition;
- },
- enumerable: true,
- configurable: true
- });
- Camera.prototype.getActiveMeshes = function () {
- return this._activeMeshes;
- };
- Camera.prototype.isActiveMesh = function (mesh) {
- return (this._activeMeshes.indexOf(mesh) !== -1);
- };
- //Cache
- Camera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.mode = undefined;
- this._cache.minZ = undefined;
- this._cache.maxZ = undefined;
- this._cache.fov = undefined;
- this._cache.aspectRatio = undefined;
- this._cache.orthoLeft = undefined;
- this._cache.orthoRight = undefined;
- this._cache.orthoBottom = undefined;
- this._cache.orthoTop = undefined;
- this._cache.renderWidth = undefined;
- this._cache.renderHeight = undefined;
- };
- Camera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- var engine = this.getEngine();
- this._cache.position.copyFrom(this.position);
- this._cache.upVector.copyFrom(this.upVector);
- this._cache.mode = this.mode;
- this._cache.minZ = this.minZ;
- this._cache.maxZ = this.maxZ;
- this._cache.fov = this.fov;
- this._cache.aspectRatio = engine.getAspectRatio(this);
- this._cache.orthoLeft = this.orthoLeft;
- this._cache.orthoRight = this.orthoRight;
- this._cache.orthoBottom = this.orthoBottom;
- this._cache.orthoTop = this.orthoTop;
- this._cache.renderWidth = engine.getRenderWidth();
- this._cache.renderHeight = engine.getRenderHeight();
- };
- Camera.prototype._updateFromScene = function () {
- this.updateCache();
- this._update();
- };
- // Synchronized
- Camera.prototype._isSynchronized = function () {
- return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
- };
- Camera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronized.call(this))
- return false;
- return this._cache.position.equals(this.position)
- && this._cache.upVector.equals(this.upVector)
- && this.isSynchronizedWithParent();
- };
- Camera.prototype._isSynchronizedProjectionMatrix = function () {
- var check = this._cache.mode === this.mode
- && this._cache.minZ === this.minZ
- && this._cache.maxZ === this.maxZ;
- if (!check) {
- return false;
- }
- var engine = this.getEngine();
- if (this.mode === Camera.PERSPECTIVE_CAMERA) {
- check = this._cache.fov === this.fov
- && this._cache.aspectRatio === engine.getAspectRatio(this);
- }
- else {
- check = this._cache.orthoLeft === this.orthoLeft
- && this._cache.orthoRight === this.orthoRight
- && this._cache.orthoBottom === this.orthoBottom
- && this._cache.orthoTop === this.orthoTop
- && this._cache.renderWidth === engine.getRenderWidth()
- && this._cache.renderHeight === engine.getRenderHeight();
- }
- return check;
- };
- // Controls
- Camera.prototype.attachControl = function (element) {
- };
- Camera.prototype.detachControl = function (element) {
- };
- Camera.prototype._update = function () {
- if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
- this._updateRigCameras();
- }
- this._checkInputs();
- };
- Camera.prototype._checkInputs = function () {
- };
- Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
- if (insertAt === void 0) { insertAt = null; }
- if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
- BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
- return 0;
- }
- if (insertAt == null || insertAt < 0) {
- this._postProcesses.push(postProcess);
- this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
- return this._postProcesses.length - 1;
- }
- var add = 0;
- var i;
- var start;
- if (this._postProcesses[insertAt]) {
- start = this._postProcesses.length - 1;
- for (i = start; i >= insertAt + 1; --i) {
- this._postProcesses[i + 1] = this._postProcesses[i];
- }
- add = 1;
- }
- for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
- if (this._postProcessesTakenIndices[i] < insertAt) {
- continue;
- }
- start = this._postProcessesTakenIndices.length - 1;
- for (var j = start; j >= i; --j) {
- this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
- }
- this._postProcessesTakenIndices[i] = insertAt;
- break;
- }
- if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
- this._postProcessesTakenIndices.push(insertAt);
- }
- var result = insertAt + add;
- this._postProcesses[result] = postProcess;
- return result;
- };
- Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
- if (atIndices === void 0) { atIndices = null; }
- var result = [];
- var i;
- var index;
- if (!atIndices) {
- var length = this._postProcesses.length;
- for (i = 0; i < length; i++) {
- if (this._postProcesses[i] !== postProcess) {
- continue;
- }
- delete this._postProcesses[i];
- index = this._postProcessesTakenIndices.indexOf(i);
- this._postProcessesTakenIndices.splice(index, 1);
- }
- }
- else {
- atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
- for (i = 0; i < atIndices.length; i++) {
- var foundPostProcess = this._postProcesses[atIndices[i]];
- if (foundPostProcess !== postProcess) {
- result.push(i);
- continue;
- }
- delete this._postProcesses[atIndices[i]];
- index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
- this._postProcessesTakenIndices.splice(index, 1);
- }
- }
- return result;
- };
- Camera.prototype.getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- var viewMatrix = this.getViewMatrix();
- viewMatrix.invertToRef(this._worldMatrix);
- return this._worldMatrix;
- };
- Camera.prototype._getViewMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- Camera.prototype.getViewMatrix = function (force) {
- this._computedViewMatrix = this._computeViewMatrix(force);
- if (!force && this._isSynchronizedViewMatrix()) {
- return this._computedViewMatrix;
- }
- if (!this.parent || !this.parent.getWorldMatrix) {
- this._globalPosition.copyFrom(this.position);
- }
- else {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- this._computedViewMatrix.invertToRef(this._worldMatrix);
- this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
- this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
- this._computedViewMatrix.invert();
- this._markSyncedWithParent();
- }
- this._currentRenderId = this.getScene().getRenderId();
- return this._computedViewMatrix;
- };
- Camera.prototype._computeViewMatrix = function (force) {
- if (!force && this._isSynchronizedViewMatrix()) {
- return this._computedViewMatrix;
- }
- this._computedViewMatrix = this._getViewMatrix();
- this._currentRenderId = this.getScene().getRenderId();
- return this._computedViewMatrix;
- };
- Camera.prototype.getProjectionMatrix = function (force) {
- if (!force && this._isSynchronizedProjectionMatrix()) {
- return this._projectionMatrix;
- }
- var engine = this.getEngine();
- if (this.mode === Camera.PERSPECTIVE_CAMERA) {
- if (this.minZ <= 0) {
- this.minZ = 0.1;
- }
- BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
- return this._projectionMatrix;
- }
- var halfWidth = engine.getRenderWidth() / 2.0;
- var halfHeight = engine.getRenderHeight() / 2.0;
- BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
- return this._projectionMatrix;
- };
- Camera.prototype.dispose = function () {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeCamera(this);
- while (this._rigCameras.length > 0) {
- this._rigCameras.pop().dispose();
- }
- // Postprocesses
- for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
- this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
- }
- };
- // ---- Camera rigs section ----
- Camera.prototype.setCameraRigMode = function (mode, rigParams) {
- while (this._rigCameras.length > 0) {
- this._rigCameras.pop().dispose();
- }
- this.cameraRigMode = mode;
- this._cameraRigParams = {};
- switch (this.cameraRigMode) {
- case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
- //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
- //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
- this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
- this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
- break;
- }
- var postProcesses = new Array();
- switch (this.cameraRigMode) {
- case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
- this._rigCameras[0].isIntermediate = true;
- postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
- postProcesses[1].onApply = function (effect) {
- effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
- };
- break;
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
- var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
- var secondCamIndex = 1 - firstCamIndex;
- postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
- this._rigCameras[firstCamIndex].isIntermediate = true;
- postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
- break;
- case Camera.RIG_MODE_VR:
- this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
- this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
- var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
- this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
- this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
- this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
- this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
- this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
- if (metrics.compensateDistortion) {
- postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
- }
- this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
- this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
- this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
- this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
- this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
- if (metrics.compensateDistortion) {
- postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
- }
- break;
- }
- this._update();
- };
- Camera.prototype._getVRProjectionMatrix = function () {
- BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
- this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
- return this._projectionMatrix;
- };
- Camera.prototype.setCameraRigParameter = function (name, value) {
- this._cameraRigParams[name] = value;
- //provisionnally:
- if (name === "interaxialDistance") {
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
- }
- };
- /**
- * May needs to be overridden by children so sub has required properties to be copied
- */
- Camera.prototype.createRigCamera = function (name, cameraIndex) {
- return null;
- };
- /**
- * May needs to be overridden by children
- */
- Camera.prototype._updateRigCameras = function () {
- for (var i = 0; i < this._rigCameras.length; i++) {
- this._rigCameras[i].minZ = this.minZ;
- this._rigCameras[i].maxZ = this.maxZ;
- this._rigCameras[i].fov = this.fov;
- }
- // only update viewport when ANAGLYPH
- if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
- this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
- }
- };
- Camera.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- serializationObject.id = this.id;
- serializationObject.position = this.position.asArray();
- serializationObject.type = BABYLON.Tools.GetConstructorName(this);
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- serializationObject.fov = this.fov;
- serializationObject.minZ = this.minZ;
- serializationObject.maxZ = this.maxZ;
- serializationObject.inertia = this.inertia;
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- serializationObject.ranges = this.serializeAnimationRanges();
- // Layer mask
- serializationObject.layerMask = this.layerMask;
- return serializationObject;
- };
- Camera.Parse = function (parsedCamera, scene) {
- var camera;
- var position = BABYLON.Vector3.FromArray(parsedCamera.position);
- var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
- var interaxial_distance;
- if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
- var alpha = parsedCamera.alpha;
- var beta = parsedCamera.beta;
- var radius = parsedCamera.radius;
- if (parsedCamera.type === "AnaglyphArcRotateCamera") {
- interaxial_distance = parsedCamera.interaxial_distance;
- camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
- }
- else {
- camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
- }
- }
- else if (parsedCamera.type === "AnaglyphFreeCamera") {
- interaxial_distance = parsedCamera.interaxial_distance;
- camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
- }
- else if (parsedCamera.type === "DeviceOrientationCamera") {
- camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "FollowCamera") {
- camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
- camera.heightOffset = parsedCamera.heightOffset;
- camera.radius = parsedCamera.radius;
- camera.rotationOffset = parsedCamera.rotationOffset;
- if (lockedTargetMesh)
- camera.target = lockedTargetMesh;
- }
- else if (parsedCamera.type === "GamepadCamera") {
- camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "TouchCamera") {
- camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "VirtualJoysticksCamera") {
- camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "WebVRFreeCamera") {
- camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
- camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
- }
- else if (parsedCamera.type === "FreeCamera") {
- camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
- }
- else {
- // Universal Camera is the default value
- camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
- }
- // apply 3d rig, when found
- if (parsedCamera.cameraRigMode) {
- var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
- camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
- }
- // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
- if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
- camera.lockedTarget = lockedTargetMesh;
- }
- camera.id = parsedCamera.id;
- BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
- // Parent
- if (parsedCamera.parentId) {
- camera._waitingParentId = parsedCamera.parentId;
- }
- // Target
- if (parsedCamera.target) {
- if (camera.setTarget) {
- camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
- }
- else {
- //For ArcRotate
- camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
- }
- }
- else {
- camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
- }
- camera.fov = parsedCamera.fov;
- camera.minZ = parsedCamera.minZ;
- camera.maxZ = parsedCamera.maxZ;
- camera.speed = parsedCamera.speed;
- camera.inertia = parsedCamera.inertia;
- camera.checkCollisions = parsedCamera.checkCollisions;
- camera.applyGravity = parsedCamera.applyGravity;
- if (parsedCamera.ellipsoid) {
- camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
- }
- // Animations
- if (parsedCamera.animations) {
- for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
- var parsedAnimation = parsedCamera.animations[animationIndex];
- camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
- }
- if (parsedCamera.autoAnimate) {
- scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
- }
- // Layer Mask
- if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
- camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
- }
- else {
- camera.layerMask = 0x0FFFFFFF;
- }
- return camera;
- };
- // Statics
- Camera._PERSPECTIVE_CAMERA = 0;
- Camera._ORTHOGRAPHIC_CAMERA = 1;
- Camera._FOVMODE_VERTICAL_FIXED = 0;
- Camera._FOVMODE_HORIZONTAL_FIXED = 1;
- Camera._RIG_MODE_NONE = 0;
- Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
- Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
- Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
- Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
- Camera._RIG_MODE_VR = 20;
- return Camera;
- })(BABYLON.Node);
- BABYLON.Camera = Camera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var TargetCamera = (function (_super) {
- __extends(TargetCamera, _super);
- function TargetCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
- this.cameraRotation = new BABYLON.Vector2(0, 0);
- this.rotation = new BABYLON.Vector3(0, 0, 0);
- this.speed = 2.0;
- this.noRotationConstraint = false;
- this.lockedTarget = null;
- this._currentTarget = BABYLON.Vector3.Zero();
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._camMatrix = BABYLON.Matrix.Zero();
- this._cameraTransformMatrix = BABYLON.Matrix.Zero();
- this._cameraRotationMatrix = BABYLON.Matrix.Zero();
- this._referencePoint = new BABYLON.Vector3(0, 0, 1);
- this._transformedReferencePoint = BABYLON.Vector3.Zero();
- this._lookAtTemp = BABYLON.Matrix.Zero();
- this._tempMatrix = BABYLON.Matrix.Zero();
- }
- TargetCamera.prototype.getFrontPosition = function (distance) {
- var direction = this.getTarget().subtract(this.position);
- direction.normalize();
- direction.scaleInPlace(distance);
- return this.globalPosition.add(direction);
- };
- TargetCamera.prototype._getLockedTargetPosition = function () {
- if (!this.lockedTarget) {
- return null;
- }
- return this.lockedTarget.position || this.lockedTarget;
- };
- // Cache
- TargetCamera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- };
- TargetCamera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- var lockedTargetPosition = this._getLockedTargetPosition();
- if (!lockedTargetPosition) {
- this._cache.lockedTarget = null;
- }
- else {
- if (!this._cache.lockedTarget) {
- this._cache.lockedTarget = lockedTargetPosition.clone();
- }
- else {
- this._cache.lockedTarget.copyFrom(lockedTargetPosition);
- }
- }
- this._cache.rotation.copyFrom(this.rotation);
- };
- // Synchronized
- TargetCamera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
- return false;
- }
- var lockedTargetPosition = this._getLockedTargetPosition();
- return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
- && this._cache.rotation.equals(this.rotation);
- };
- // Methods
- TargetCamera.prototype._computeLocalCameraSpeed = function () {
- var engine = this.getEngine();
- return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
- };
- // Target
- TargetCamera.prototype.setTarget = function (target) {
- this.upVector.normalize();
- BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
- this._camMatrix.invert();
- this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
- var vDir = target.subtract(this.position);
- if (vDir.x >= 0.0) {
- this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
- }
- else {
- this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
- }
- this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
- if (isNaN(this.rotation.x)) {
- this.rotation.x = 0;
- }
- if (isNaN(this.rotation.y)) {
- this.rotation.y = 0;
- }
- if (isNaN(this.rotation.z)) {
- this.rotation.z = 0;
- }
- };
- TargetCamera.prototype.getTarget = function () {
- return this._currentTarget;
- };
- TargetCamera.prototype._decideIfNeedsToMove = function () {
- return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
- };
- TargetCamera.prototype._updatePosition = function () {
- this.position.addInPlace(this.cameraDirection);
- };
- TargetCamera.prototype._checkInputs = function () {
- var needToMove = this._decideIfNeedsToMove();
- var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
- // Move
- if (needToMove) {
- this._updatePosition();
- }
- // Rotate
- if (needToRotate) {
- this.rotation.x += this.cameraRotation.x;
- this.rotation.y += this.cameraRotation.y;
- if (!this.noRotationConstraint) {
- var limit = (Math.PI / 2) * 0.95;
- if (this.rotation.x > limit)
- this.rotation.x = limit;
- if (this.rotation.x < -limit)
- this.rotation.x = -limit;
- }
- }
- // Inertia
- if (needToMove) {
- if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
- this.cameraDirection.x = 0;
- }
- if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
- this.cameraDirection.y = 0;
- }
- if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
- this.cameraDirection.z = 0;
- }
- this.cameraDirection.scaleInPlace(this.inertia);
- }
- if (needToRotate) {
- if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
- this.cameraRotation.x = 0;
- }
- if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
- this.cameraRotation.y = 0;
- }
- this.cameraRotation.scaleInPlace(this.inertia);
- }
- _super.prototype._checkInputs.call(this);
- };
- TargetCamera.prototype._getViewMatrix = function () {
- if (!this.lockedTarget) {
- // Compute
- if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
- BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
- this._lookAtTemp.invert();
- this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
- }
- else {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
- // Computing target and final matrix
- this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
- }
- else {
- this._currentTarget.copyFrom(this._getLockedTargetPosition());
- }
- BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
- return this._viewMatrix;
- };
- TargetCamera.prototype._getVRViewMatrix = function () {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
- BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
- // Computing target and final matrix
- this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
- BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
- this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
- return this._viewMatrix;
- };
- /**
- * @override
- * Override Camera.createRigCamera
- */
- TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
- if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
- var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
- if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
- rigCamera._cameraRigParams = {};
- rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
- rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
- }
- return rigCamera;
- }
- return null;
- };
- /**
- * @override
- * Override Camera._updateRigCameras
- */
- TargetCamera.prototype._updateRigCameras = function () {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var camLeft = this._rigCameras[0];
- var camRight = this._rigCameras[1];
- if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
- camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
- camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
- camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
- camLeft.position.copyFrom(this.position);
- camRight.position.copyFrom(this.position);
- }
- else {
- //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
- this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
- this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
- camLeft.setTarget(this.getTarget());
- camRight.setTarget(this.getTarget());
- }
- break;
- }
- _super.prototype._updateRigCameras.call(this);
- };
- TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
- if (!this._rigCamTransformMatrix) {
- this._rigCamTransformMatrix = new BABYLON.Matrix();
- }
- var target = this.getTarget();
- BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
- this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
- };
- TargetCamera.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.speed = this.speed;
- if (this.rotation) {
- serializationObject.rotation = this.rotation.asArray();
- }
- if (this.lockedTarget && this.lockedTarget.id) {
- serializationObject.lockedTargetId = this.lockedTarget.id;
- }
- return serializationObject;
- };
- return TargetCamera;
- })(BABYLON.Camera);
- BABYLON.TargetCamera = TargetCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCamera = (function (_super) {
- __extends(FreeCamera, _super);
- function FreeCamera(name, position, scene) {
- var _this = this;
- _super.call(this, name, position, scene);
- this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
- this.keysUp = [38];
- this.keysDown = [40];
- this.keysLeft = [37];
- this.keysRight = [39];
- this.checkCollisions = false;
- this.applyGravity = false;
- this.angularSensibility = 2000.0;
- this._keys = [];
- this._collider = new BABYLON.Collider();
- this._needMoveForGravity = false;
- this._oldPosition = BABYLON.Vector3.Zero();
- this._diffPosition = BABYLON.Vector3.Zero();
- this._newPosition = BABYLON.Vector3.Zero();
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- //TODO move this to the collision coordinator!
- if (_this.getScene().workerCollisions)
- newPosition.multiplyInPlace(_this._collider.radius);
- var updatePosition = function (newPos) {
- _this._newPosition.copyFrom(newPos);
- _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
- var oldPosition = _this.position.clone();
- if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
- _this.position.addInPlace(_this._diffPosition);
- if (_this.onCollide && collidedMesh) {
- _this.onCollide(collidedMesh);
- }
- }
- };
- updatePosition(newPosition);
- };
- }
- FreeCamera.prototype._onLostFocus = function (e) {
- this._keys = [];
- };
- // Controls
- FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- var previousPosition;
- var engine = this.getEngine();
- if (this._attachedElement) {
- return;
- }
- this._attachedElement = element;
- if (this._onMouseDown === undefined) {
- this._onMouseDown = function (evt) {
- previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onMouseUp = function (evt) {
- previousPosition = null;
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onMouseOut = function (evt) {
- previousPosition = null;
- _this._keys = [];
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onMouseMove = function (evt) {
- if (!previousPosition && !engine.isPointerLock) {
- return;
- }
- var offsetX;
- var offsetY;
- if (!engine.isPointerLock) {
- offsetX = evt.clientX - previousPosition.x;
- offsetY = evt.clientY - previousPosition.y;
- }
- else {
- offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
- offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
- }
- _this.cameraRotation.y += offsetX / _this.angularSensibility;
- _this.cameraRotation.x += offsetY / _this.angularSensibility;
- previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onKeyDown = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index === -1) {
- _this._keys.push(evt.keyCode);
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- };
- this._onKeyUp = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index >= 0) {
- _this._keys.splice(index, 1);
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- };
- this._reset = function () {
- _this._keys = [];
- previousPosition = null;
- _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
- _this.cameraRotation = new BABYLON.Vector2(0, 0);
- };
- }
- element.addEventListener("mousedown", this._onMouseDown, false);
- element.addEventListener("mouseup", this._onMouseUp, false);
- element.addEventListener("mouseout", this._onMouseOut, false);
- element.addEventListener("mousemove", this._onMouseMove, false);
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- };
- FreeCamera.prototype.detachControl = function (element) {
- if (this._attachedElement !== element) {
- return;
- }
- element.removeEventListener("mousedown", this._onMouseDown);
- element.removeEventListener("mouseup", this._onMouseUp);
- element.removeEventListener("mouseout", this._onMouseOut);
- element.removeEventListener("mousemove", this._onMouseMove);
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- this._attachedElement = null;
- if (this._reset) {
- this._reset();
- }
- };
- FreeCamera.prototype._collideWithWorld = function (velocity) {
- var globalPosition;
- if (this.parent) {
- globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
- }
- else {
- globalPosition = this.position;
- }
- globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
- this._collider.radius = this.ellipsoid;
- //no need for clone, as long as gravity is not on.
- var actualVelocity = velocity;
- //add gravity to the velocity to prevent the dual-collision checking
- if (this.applyGravity) {
- //this prevents mending with cameraDirection, a global variable of the free camera class.
- actualVelocity = velocity.add(this.getScene().gravity);
- }
- this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
- };
- FreeCamera.prototype._checkInputs = function () {
- if (!this._localDirection) {
- this._localDirection = BABYLON.Vector3.Zero();
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- // Keyboard
- for (var index = 0; index < this._keys.length; index++) {
- var keyCode = this._keys[index];
- var speed = this._computeLocalCameraSpeed();
- if (this.keysLeft.indexOf(keyCode) !== -1) {
- this._localDirection.copyFromFloats(-speed, 0, 0);
- }
- else if (this.keysUp.indexOf(keyCode) !== -1) {
- this._localDirection.copyFromFloats(0, 0, speed);
- }
- else if (this.keysRight.indexOf(keyCode) !== -1) {
- this._localDirection.copyFromFloats(speed, 0, 0);
- }
- else if (this.keysDown.indexOf(keyCode) !== -1) {
- this._localDirection.copyFromFloats(0, 0, -speed);
- }
- this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
- BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
- this.cameraDirection.addInPlace(this._transformedDirection);
- }
- _super.prototype._checkInputs.call(this);
- };
- FreeCamera.prototype._decideIfNeedsToMove = function () {
- return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
- };
- FreeCamera.prototype._updatePosition = function () {
- if (this.checkCollisions && this.getScene().collisionsEnabled) {
- this._collideWithWorld(this.cameraDirection);
- }
- else {
- this.position.addInPlace(this.cameraDirection);
- }
- };
- FreeCamera.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.checkCollisions = this.checkCollisions;
- serializationObject.applyGravity = this.applyGravity;
- serializationObject.ellipsoid = this.ellipsoid.asArray();
- return serializationObject;
- };
- return FreeCamera;
- })(BABYLON.TargetCamera);
- BABYLON.FreeCamera = FreeCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FollowCamera = (function (_super) {
- __extends(FollowCamera, _super);
- function FollowCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.radius = 12;
- this.rotationOffset = 0;
- this.heightOffset = 4;
- this.cameraAcceleration = 0.05;
- this.maxCameraSpeed = 20;
- }
- FollowCamera.prototype.getRadians = function (degrees) {
- return degrees * Math.PI / 180;
- };
- FollowCamera.prototype.follow = function (cameraTarget) {
- if (!cameraTarget)
- return;
- var yRotation;
- if (cameraTarget.rotationQuaternion) {
- var rotMatrix = new BABYLON.Matrix();
- cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
- yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
- }
- else {
- yRotation = cameraTarget.rotation.y;
- }
- var radians = this.getRadians(this.rotationOffset) + yRotation;
- var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
- var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
- var dx = targetX - this.position.x;
- var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
- var dz = (targetZ) - this.position.z;
- var vx = dx * this.cameraAcceleration * 2; //this is set to .05
- var vy = dy * this.cameraAcceleration;
- var vz = dz * this.cameraAcceleration * 2;
- if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
- vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
- vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
- vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
- this.setTarget(cameraTarget.position);
- };
- FollowCamera.prototype._checkInputs = function () {
- _super.prototype._checkInputs.call(this);
- this.follow(this.target);
- };
- FollowCamera.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.radius = this.radius;
- serializationObject.heightOffset = this.heightOffset;
- serializationObject.rotationOffset = this.rotationOffset;
- return serializationObject;
- };
- return FollowCamera;
- })(BABYLON.TargetCamera);
- BABYLON.FollowCamera = FollowCamera;
- var ArcFollowCamera = (function (_super) {
- __extends(ArcFollowCamera, _super);
- function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
- _super.call(this, name, BABYLON.Vector3.Zero(), scene);
- this.alpha = alpha;
- this.beta = beta;
- this.radius = radius;
- this.target = target;
- this._cartesianCoordinates = BABYLON.Vector3.Zero();
- this.follow();
- }
- ArcFollowCamera.prototype.follow = function () {
- this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
- this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
- this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
- this.position = this.target.position.add(this._cartesianCoordinates);
- this.setTarget(this.target.position);
- };
- ArcFollowCamera.prototype._checkInputs = function () {
- _super.prototype._checkInputs.call(this);
- this.follow();
- };
- ArcFollowCamera.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.radius = this.radius;
- return serializationObject;
- };
- return ArcFollowCamera;
- })(BABYLON.TargetCamera);
- BABYLON.ArcFollowCamera = ArcFollowCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var TouchCamera = (function (_super) {
- __extends(TouchCamera, _super);
- function TouchCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this._offsetX = null;
- this._offsetY = null;
- this._pointerCount = 0;
- this._pointerPressed = [];
- this.touchAngularSensibility = 200000.0;
- this.touchMoveSensibility = 250.0;
- }
- TouchCamera.prototype._onLostFocus = function (e) {
- this._offsetX = null;
- this._offsetY = null;
- _super.prototype._onLostFocus.call(this, e);
- };
- TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
- var _this = this;
- var previousPosition;
- if (this._attachedCanvas) {
- return;
- }
- if (this._onPointerDown === undefined) {
- this._onPointerDown = function (evt) {
- if (evt.pointerType === "mouse") {
- return;
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- _this._pointerPressed.push(evt.pointerId);
- if (_this._pointerPressed.length !== 1) {
- return;
- }
- previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- };
- this._onPointerUp = function (evt) {
- if (evt.pointerType === "mouse") {
- return;
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- var index = _this._pointerPressed.indexOf(evt.pointerId);
- if (index === -1) {
- return;
- }
- _this._pointerPressed.splice(index, 1);
- if (index != 0) {
- return;
- }
- previousPosition = null;
- _this._offsetX = null;
- _this._offsetY = null;
- };
- this._onPointerMove = function (evt) {
- if (evt.pointerType === "mouse") {
- return;
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- if (!previousPosition) {
- return;
- }
- var index = _this._pointerPressed.indexOf(evt.pointerId);
- if (index != 0) {
- return;
- }
- _this._offsetX = evt.clientX - previousPosition.x;
- _this._offsetY = -(evt.clientY - previousPosition.y);
- };
- }
- canvas.addEventListener("pointerdown", this._onPointerDown);
- canvas.addEventListener("pointerup", this._onPointerUp);
- canvas.addEventListener("pointerout", this._onPointerUp);
- canvas.addEventListener("pointermove", this._onPointerMove);
- _super.prototype.attachControl.call(this, canvas);
- };
- TouchCamera.prototype.detachControl = function (canvas) {
- if (this._attachedCanvas !== canvas) {
- return;
- }
- canvas.removeEventListener("pointerdown", this._onPointerDown);
- canvas.removeEventListener("pointerup", this._onPointerUp);
- canvas.removeEventListener("pointerout", this._onPointerUp);
- canvas.removeEventListener("pointermove", this._onPointerMove);
- _super.prototype.detachControl.call(this, canvas);
- };
- TouchCamera.prototype._checkInputs = function () {
- if (this._offsetX) {
- this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
- if (this._pointerPressed.length > 1) {
- this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
- }
- else {
- var speed = this._computeLocalCameraSpeed();
- var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
- this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
- }
- }
- _super.prototype._checkInputs.call(this);
- };
- return TouchCamera;
- })(BABYLON.FreeCamera);
- BABYLON.TouchCamera = TouchCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- var ArcRotateCamera = (function (_super) {
- __extends(ArcRotateCamera, _super);
- function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
- var _this = this;
- _super.call(this, name, BABYLON.Vector3.Zero(), scene);
- this.alpha = alpha;
- this.beta = beta;
- this.radius = radius;
- this.target = target;
- this.inertialAlphaOffset = 0;
- this.inertialBetaOffset = 0;
- this.inertialRadiusOffset = 0;
- this.lowerAlphaLimit = null;
- this.upperAlphaLimit = null;
- this.lowerBetaLimit = 0.01;
- this.upperBetaLimit = Math.PI;
- this.lowerRadiusLimit = null;
- this.upperRadiusLimit = null;
- this.angularSensibilityX = 1000.0;
- this.angularSensibilityY = 1000.0;
- this.wheelPrecision = 3.0;
- this.pinchPrecision = 2.0;
- this.panningSensibility = 50.0;
- this.inertialPanningX = 0;
- this.inertialPanningY = 0;
- this.keysUp = [38];
- this.keysDown = [40];
- this.keysLeft = [37];
- this.keysRight = [39];
- this.zoomOnFactor = 1;
- this.targetScreenOffset = BABYLON.Vector2.Zero();
- this.pinchInwards = true;
- this.allowUpsideDown = true;
- this._keys = [];
- this._viewMatrix = new BABYLON.Matrix();
- // Panning
- this.panningAxis = new BABYLON.Vector3(1, 1, 0);
- this._isRightClick = false;
- this._isCtrlPushed = false;
- this.checkCollisions = false;
- this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
- this._collider = new BABYLON.Collider();
- this._previousPosition = BABYLON.Vector3.Zero();
- this._collisionVelocity = BABYLON.Vector3.Zero();
- this._newPosition = BABYLON.Vector3.Zero();
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- if (_this.getScene().workerCollisions && _this.checkCollisions) {
- newPosition.multiplyInPlace(_this._collider.radius);
- }
- if (!collidedMesh) {
- _this._previousPosition.copyFrom(_this.position);
- }
- else {
- _this.setPosition(newPosition);
- if (_this.onCollide) {
- _this.onCollide(collidedMesh);
- }
- }
- // Recompute because of constraints
- var cosa = Math.cos(_this.alpha);
- var sina = Math.sin(_this.alpha);
- var cosb = Math.cos(_this.beta);
- var sinb = Math.sin(_this.beta);
- var target = _this._getTargetPosition();
- target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
- _this.position.copyFrom(_this._newPosition);
- var up = _this.upVector;
- if (_this.allowUpsideDown && _this.beta < 0) {
- up = up.clone();
- up = up.negate();
- }
- BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
- _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
- _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
- _this._collisionTriggered = false;
- };
- if (!this.target) {
- this.target = BABYLON.Vector3.Zero();
- }
- this.getViewMatrix();
- }
- Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
- //deprecated angularSensibility support
- get: function () {
- BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
- return Math.max(this.angularSensibilityX, this.angularSensibilityY);
- },
- //deprecated angularSensibility support
- set: function (value) {
- BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
- this.angularSensibilityX = value;
- this.angularSensibilityY = value;
- },
- enumerable: true,
- configurable: true
- });
- ArcRotateCamera.prototype._getTargetPosition = function () {
- return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
- };
- // Cache
- ArcRotateCamera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.alpha = undefined;
- this._cache.beta = undefined;
- this._cache.radius = undefined;
- this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
- };
- ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- this._cache.target.copyFrom(this._getTargetPosition());
- this._cache.alpha = this.alpha;
- this._cache.beta = this.beta;
- this._cache.radius = this.radius;
- this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
- };
- // Synchronized
- ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronizedViewMatrix.call(this))
- return false;
- return this._cache.target.equals(this._getTargetPosition())
- && this._cache.alpha === this.alpha
- && this._cache.beta === this.beta
- && this._cache.radius === this.radius
- && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
- };
- // Methods
- ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
- var _this = this;
- if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
- var cacheSoloPointer; // cache pointer object for better perf on camera rotation
- var previousPinchDistance = 0;
- var pointers = new BABYLON.SmartCollection();
- if (this._attachedElement) {
- return;
- }
- this._attachedElement = element;
- var engine = this.getEngine();
- if (this._onPointerDown === undefined) {
- this._onPointerDown = function (evt) {
- // Manage panning with right click
- _this._isRightClick = evt.button === 2;
- // manage pointers
- pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
- cacheSoloPointer = pointers.item(evt.pointerId);
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onPointerUp = function (evt) {
- cacheSoloPointer = null;
- previousPinchDistance = 0;
- //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
- //but emptying completly pointers collection is required to fix a bug on iPhone :
- //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
- //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
- pointers.empty();
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onContextMenu = function (evt) {
- evt.preventDefault();
- };
- this._onPointerMove = function (evt) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- switch (pointers.count) {
- case 1:
- if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
- _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
- _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
- }
- else {
- var offsetX = evt.clientX - cacheSoloPointer.x;
- var offsetY = evt.clientY - cacheSoloPointer.y;
- _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
- _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
- }
- cacheSoloPointer.x = evt.clientX;
- cacheSoloPointer.y = evt.clientY;
- break;
- case 2:
- //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
- pointers.item(evt.pointerId).x = evt.clientX;
- pointers.item(evt.pointerId).y = evt.clientY;
- var direction = _this.pinchInwards ? 1 : -1;
- var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
- var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
- var pinchSquaredDistance = (distX * distX) + (distY * distY);
- if (previousPinchDistance === 0) {
- previousPinchDistance = pinchSquaredDistance;
- return;
- }
- if (pinchSquaredDistance !== previousPinchDistance) {
- _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
- previousPinchDistance = pinchSquaredDistance;
- }
- break;
- default:
- if (pointers.item(evt.pointerId)) {
- pointers.item(evt.pointerId).x = evt.clientX;
- pointers.item(evt.pointerId).y = evt.clientY;
- }
- }
- };
- this._onMouseMove = function (evt) {
- if (!engine.isPointerLock) {
- return;
- }
- var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
- var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
- _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
- _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._wheel = function (event) {
- var delta = 0;
- if (event.wheelDelta) {
- delta = event.wheelDelta / (_this.wheelPrecision * 40);
- }
- else if (event.detail) {
- delta = -event.detail / _this.wheelPrecision;
- }
- if (delta)
- _this.inertialRadiusOffset += delta;
- if (event.preventDefault) {
- if (!noPreventDefault) {
- event.preventDefault();
- }
- }
- };
- this._onKeyDown = function (evt) {
- _this._isCtrlPushed = evt.ctrlKey;
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index === -1) {
- _this._keys.push(evt.keyCode);
- }
- if (evt.preventDefault) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- }
- };
- this._onKeyUp = function (evt) {
- _this._isCtrlPushed = evt.ctrlKey;
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index >= 0) {
- _this._keys.splice(index, 1);
- }
- if (evt.preventDefault) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- }
- };
- this._onLostFocus = function () {
- _this._keys = [];
- pointers.empty();
- previousPinchDistance = 0;
- cacheSoloPointer = null;
- };
- this._onGestureStart = function (e) {
- if (window.MSGesture === undefined) {
- return;
- }
- if (!_this._MSGestureHandler) {
- _this._MSGestureHandler = new MSGesture();
- _this._MSGestureHandler.target = element;
- }
- _this._MSGestureHandler.addPointer(e.pointerId);
- };
- this._onGesture = function (e) {
- _this.radius *= e.scale;
- if (e.preventDefault) {
- if (!noPreventDefault) {
- e.stopPropagation();
- e.preventDefault();
- }
- }
- };
- this._reset = function () {
- _this._keys = [];
- _this.inertialAlphaOffset = 0;
- _this.inertialBetaOffset = 0;
- _this.inertialRadiusOffset = 0;
- pointers.empty();
- previousPinchDistance = 0;
- cacheSoloPointer = null;
- };
- }
- if (!useCtrlForPanning) {
- element.addEventListener("contextmenu", this._onContextMenu, false);
- }
- element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
- element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
- element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
- element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
- element.addEventListener("mousemove", this._onMouseMove, false);
- element.addEventListener("MSPointerDown", this._onGestureStart, false);
- element.addEventListener("MSGestureChange", this._onGesture, false);
- element.addEventListener('mousewheel', this._wheel, false);
- element.addEventListener('DOMMouseScroll', this._wheel, false);
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- };
- ArcRotateCamera.prototype.detachControl = function (element) {
- if (this._attachedElement !== element) {
- return;
- }
- element.removeEventListener("contextmenu", this._onContextMenu);
- element.removeEventListener(eventPrefix + "down", this._onPointerDown);
- element.removeEventListener(eventPrefix + "up", this._onPointerUp);
- element.removeEventListener(eventPrefix + "out", this._onPointerUp);
- element.removeEventListener(eventPrefix + "move", this._onPointerMove);
- element.removeEventListener("mousemove", this._onMouseMove);
- element.removeEventListener("MSPointerDown", this._onGestureStart);
- element.removeEventListener("MSGestureChange", this._onGesture);
- element.removeEventListener('mousewheel', this._wheel);
- element.removeEventListener('DOMMouseScroll', this._wheel);
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- this._MSGestureHandler = null;
- this._attachedElement = null;
- if (this._reset) {
- this._reset();
- }
- };
- ArcRotateCamera.prototype._checkInputs = function () {
- //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
- if (this._collisionTriggered) {
- return;
- }
- // Keyboard
- for (var index = 0; index < this._keys.length; index++) {
- var keyCode = this._keys[index];
- if (this.keysLeft.indexOf(keyCode) !== -1) {
- this.inertialAlphaOffset -= 0.01;
- }
- else if (this.keysUp.indexOf(keyCode) !== -1) {
- this.inertialBetaOffset -= 0.01;
- }
- else if (this.keysRight.indexOf(keyCode) !== -1) {
- this.inertialAlphaOffset += 0.01;
- }
- else if (this.keysDown.indexOf(keyCode) !== -1) {
- this.inertialBetaOffset += 0.01;
- }
- }
- // Inertia
- if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
- this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
- this.beta += this.inertialBetaOffset;
- this.radius -= this.inertialRadiusOffset;
- this.inertialAlphaOffset *= this.inertia;
- this.inertialBetaOffset *= this.inertia;
- this.inertialRadiusOffset *= this.inertia;
- if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
- this.inertialAlphaOffset = 0;
- if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
- this.inertialBetaOffset = 0;
- if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
- this.inertialRadiusOffset = 0;
- }
- // Panning inertia
- if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
- if (!this._localDirection) {
- this._localDirection = BABYLON.Vector3.Zero();
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- this.inertialPanningX *= this.inertia;
- this.inertialPanningY *= this.inertia;
- if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
- this.inertialPanningX = 0;
- if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
- this.inertialPanningY = 0;
- this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
- this._localDirection.multiplyInPlace(this.panningAxis);
- this._viewMatrix.invertToRef(this._cameraTransformMatrix);
- BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
- //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
- if (!this.panningAxis.y) {
- this._transformedDirection.y = 0;
- }
- this.target.addInPlace(this._transformedDirection);
- }
- // Limits
- this._checkLimits();
- _super.prototype._checkInputs.call(this);
- };
- ArcRotateCamera.prototype._checkLimits = function () {
- if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
- if (this.allowUpsideDown && this.beta > Math.PI) {
- this.beta = this.beta - (2 * Math.PI);
- }
- }
- else {
- if (this.beta < this.lowerBetaLimit) {
- this.beta = this.lowerBetaLimit;
- }
- }
- if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
- if (this.allowUpsideDown && this.beta < -Math.PI) {
- this.beta = this.beta + (2 * Math.PI);
- }
- }
- else {
- if (this.beta > this.upperBetaLimit) {
- this.beta = this.upperBetaLimit;
- }
- }
- if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
- this.alpha = this.lowerAlphaLimit;
- }
- if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
- this.alpha = this.upperAlphaLimit;
- }
- if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
- this.radius = this.lowerRadiusLimit;
- }
- if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
- this.radius = this.upperRadiusLimit;
- }
- };
- ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
- var radiusv3 = this.position.subtract(this._getTargetPosition());
- this.radius = radiusv3.length();
- // Alpha
- this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
- if (radiusv3.z < 0) {
- this.alpha = 2 * Math.PI - this.alpha;
- }
- // Beta
- this.beta = Math.acos(radiusv3.y / this.radius);
- this._checkLimits();
- };
- ArcRotateCamera.prototype.setPosition = function (position) {
- if (this.position.equals(position)) {
- return;
- }
- this.position = position;
- this.rebuildAnglesAndRadius();
- };
- ArcRotateCamera.prototype.setTarget = function (target) {
- if (this.target.equals(target)) {
- return;
- }
- this.target = target;
- this.rebuildAnglesAndRadius();
- };
- ArcRotateCamera.prototype._getViewMatrix = function () {
- // Compute
- var cosa = Math.cos(this.alpha);
- var sina = Math.sin(this.alpha);
- var cosb = Math.cos(this.beta);
- var sinb = Math.sin(this.beta);
- var target = this._getTargetPosition();
- target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
- if (this.getScene().collisionsEnabled && this.checkCollisions) {
- this._collider.radius = this.collisionRadius;
- this._newPosition.subtractToRef(this.position, this._collisionVelocity);
- this._collisionTriggered = true;
- this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
- }
- else {
- this.position.copyFrom(this._newPosition);
- var up = this.upVector;
- if (this.allowUpsideDown && this.beta < 0) {
- up = up.clone();
- up = up.negate();
- }
- BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
- this._viewMatrix.m[12] += this.targetScreenOffset.x;
- this._viewMatrix.m[13] += this.targetScreenOffset.y;
- }
- return this._viewMatrix;
- };
- ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
- if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
- meshes = meshes || this.getScene().meshes;
- var minMaxVector = BABYLON.Mesh.MinMax(meshes);
- var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
- this.radius = distance * this.zoomOnFactor;
- this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
- };
- ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
- if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
- var meshesOrMinMaxVector;
- var distance;
- if (meshesOrMinMaxVectorAndDistance.min === undefined) {
- meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
- meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
- distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
- }
- else {
- meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
- distance = meshesOrMinMaxVectorAndDistance.distance;
- }
- this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
- if (!doNotUpdateMaxZ) {
- this.maxZ = distance * 2;
- }
- };
- /**
- * @override
- * Override Camera.createRigCamera
- */
- ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
- return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
- }
- return null;
- };
- /**
- * @override
- * Override Camera._updateRigCameras
- */
- ArcRotateCamera.prototype._updateRigCameras = function () {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var camLeft = this._rigCameras[0];
- var camRight = this._rigCameras[1];
- camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
- camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
- camLeft.beta = camRight.beta = this.beta;
- camLeft.radius = camRight.radius = this.radius;
- break;
- }
- _super.prototype._updateRigCameras.call(this);
- };
- ArcRotateCamera.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- if (this.target instanceof BABYLON.Vector3) {
- serializationObject.target = this.target.asArray();
- }
- if (this.target && this.target.id) {
- serializationObject.lockedTargetId = this.target.id;
- }
- serializationObject.checkCollisions = this.checkCollisions;
- serializationObject.alpha = this.alpha;
- serializationObject.beta = this.beta;
- serializationObject.radius = this.radius;
- return serializationObject;
- };
- return ArcRotateCamera;
- })(BABYLON.TargetCamera);
- BABYLON.ArcRotateCamera = ArcRotateCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderingManager = (function () {
- function RenderingManager(scene) {
- this._renderingGroups = new Array();
- this._scene = scene;
- }
- RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
- if (this._scene._activeParticleSystems.length === 0) {
- return;
- }
- // Particles
- var activeCamera = this._scene.activeCamera;
- var beforeParticlesDate = BABYLON.Tools.Now;
- for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
- var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
- if (particleSystem.renderingGroupId !== index) {
- continue;
- }
- if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
- continue;
- }
- this._clearDepthBuffer();
- if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
- this._scene._activeParticles += particleSystem.render();
- }
- }
- this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
- };
- RenderingManager.prototype._renderSprites = function (index) {
- if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
- return;
- }
- // Sprites
- var activeCamera = this._scene.activeCamera;
- var beforeSpritessDate = BABYLON.Tools.Now;
- for (var id = 0; id < this._scene.spriteManagers.length; id++) {
- var spriteManager = this._scene.spriteManagers[id];
- if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
- this._clearDepthBuffer();
- spriteManager.render();
- }
- }
- this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
- };
- RenderingManager.prototype._clearDepthBuffer = function () {
- if (this._depthBufferAlreadyCleaned) {
- return;
- }
- this._scene.getEngine().clear(0, false, true);
- this._depthBufferAlreadyCleaned = true;
- };
- RenderingManager.prototype._renderSpritesAndParticles = function () {
- if (this._currentRenderSprites) {
- this._renderSprites(this._currentIndex);
- }
- if (this._currentRenderParticles) {
- this._renderParticles(this._currentIndex, this._currentActiveMeshes);
- }
- };
- RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
- this._currentActiveMeshes = activeMeshes;
- this._currentRenderParticles = renderParticles;
- this._currentRenderSprites = renderSprites;
- for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
- this._depthBufferAlreadyCleaned = index == 0;
- var renderingGroup = this._renderingGroups[index];
- var needToStepBack = false;
- this._currentIndex = index;
- if (renderingGroup) {
- this._clearDepthBuffer();
- if (!renderingGroup.onBeforeTransparentRendering) {
- renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
- }
- if (!renderingGroup.render(customRenderFunction)) {
- this._renderingGroups.splice(index, 1);
- needToStepBack = true;
- this._renderSpritesAndParticles();
- }
- }
- else {
- this._renderSpritesAndParticles();
- }
- if (needToStepBack) {
- index--;
- }
- }
- };
- RenderingManager.prototype.reset = function () {
- this._renderingGroups.forEach(function (renderingGroup, index, array) {
- if (renderingGroup) {
- renderingGroup.prepare();
- }
- });
- };
- RenderingManager.prototype.dispatch = function (subMesh) {
- var mesh = subMesh.getMesh();
- var renderingGroupId = mesh.renderingGroupId || 0;
- if (!this._renderingGroups[renderingGroupId]) {
- this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
- }
- this._renderingGroups[renderingGroupId].dispatch(subMesh);
- };
- RenderingManager.MAX_RENDERINGGROUPS = 4;
- return RenderingManager;
- })();
- BABYLON.RenderingManager = RenderingManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderingGroup = (function () {
- function RenderingGroup(index, scene) {
- this.index = index;
- this._opaqueSubMeshes = new BABYLON.SmartArray(256);
- this._transparentSubMeshes = new BABYLON.SmartArray(256);
- this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
- this._scene = scene;
- }
- RenderingGroup.prototype.render = function (customRenderFunction) {
- if (customRenderFunction) {
- customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
- return true;
- }
- if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- return false;
- }
- var engine = this._scene.getEngine();
- // Opaque
- var subIndex;
- var submesh;
- for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
- submesh = this._opaqueSubMeshes.data[subIndex];
- submesh.render(false);
- }
- // Alpha test
- engine.setAlphaTesting(true);
- for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
- submesh = this._alphaTestSubMeshes.data[subIndex];
- submesh.render(false);
- }
- engine.setAlphaTesting(false);
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- // Transparent
- if (this._transparentSubMeshes.length) {
- // Sorting
- for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
- submesh = this._transparentSubMeshes.data[subIndex];
- submesh._alphaIndex = submesh.getMesh().alphaIndex;
- submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
- }
- var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
- sortedArray.sort(function (a, b) {
- // Alpha index first
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- });
- // Rendering
- for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
- submesh = sortedArray[subIndex];
- submesh.render(true);
- }
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- return true;
- };
- RenderingGroup.prototype.prepare = function () {
- this._opaqueSubMeshes.reset();
- this._transparentSubMeshes.reset();
- this._alphaTestSubMeshes.reset();
- };
- RenderingGroup.prototype.dispatch = function (subMesh) {
- var material = subMesh.getMaterial();
- var mesh = subMesh.getMesh();
- if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
- this._transparentSubMeshes.push(subMesh);
- }
- else if (material.needAlphaTesting()) {
- this._alphaTestSubMeshes.push(subMesh);
- }
- else {
- this._opaqueSubMeshes.push(subMesh); // Opaque
- }
- };
- return RenderingGroup;
- })();
- BABYLON.RenderingGroup = RenderingGroup;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Represents a scene to be rendered by the engine.
- * @see http://doc.babylonjs.com/page.php?p=21911
- */
- var Scene = (function () {
- /**
- * @constructor
- * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
- */
- function Scene(engine) {
- // Members
- this.autoClear = true;
- this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- this.forceWireframe = false;
- this.forcePointsCloud = false;
- this.forceShowBoundingBoxes = false;
- this.animationsEnabled = true;
- this.constantlyUpdateMeshUnderPointer = false;
- // Animations
- this.animations = [];
- this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
- this._startingPointerPosition = new BABYLON.Vector2(0, 0);
- this._startingPointerTime = 0;
- // Fog
- /**
- * is fog enabled on this scene.
- * @type {boolean}
- */
- this.fogEnabled = true;
- this.fogMode = Scene.FOGMODE_NONE;
- this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
- this.fogDensity = 0.1;
- this.fogStart = 0;
- this.fogEnd = 1000.0;
- // Lights
- /**
- * is shadow enabled on this scene.
- * @type {boolean}
- */
- this.shadowsEnabled = true;
- /**
- * is light enabled on this scene.
- * @type {boolean}
- */
- this.lightsEnabled = true;
- /**
- * All of the lights added to this scene.
- * @see BABYLON.Light
- * @type {BABYLON.Light[]}
- */
- this.lights = new Array();
- // Cameras
- /**
- * All of the cameras added to this scene.
- * @see BABYLON.Camera
- * @type {BABYLON.Camera[]}
- */
- this.cameras = new Array();
- this.activeCameras = new Array();
- // Meshes
- /**
- * All of the (abstract) meshes added to this scene.
- * @see BABYLON.AbstractMesh
- * @type {BABYLON.AbstractMesh[]}
- */
- this.meshes = new Array();
- // Geometries
- this._geometries = new Array();
- this.materials = new Array();
- this.multiMaterials = new Array();
- this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
- // Textures
- this.texturesEnabled = true;
- this.textures = new Array();
- // Particles
- this.particlesEnabled = true;
- this.particleSystems = new Array();
- // Sprites
- this.spritesEnabled = true;
- this.spriteManagers = new Array();
- // Layers
- this.layers = new Array();
- // Skeletons
- this.skeletonsEnabled = true;
- this.skeletons = new Array();
- // Lens flares
- this.lensFlaresEnabled = true;
- this.lensFlareSystems = new Array();
- // Collisions
- this.collisionsEnabled = true;
- this.gravity = new BABYLON.Vector3(0, -9.807, 0);
- // Postprocesses
- this.postProcessesEnabled = true;
- // Customs render targets
- this.renderTargetsEnabled = true;
- this.dumpNextRenderTargets = false;
- this.customRenderTargets = new Array();
- // Imported meshes
- this.importedMeshesFiles = new Array();
- // Probes
- this.probesEnabled = true;
- this.reflectionProbes = new Array();
- this._actionManagers = new Array();
- this._meshesForIntersections = new BABYLON.SmartArray(256);
- // Procedural textures
- this.proceduralTexturesEnabled = true;
- this._proceduralTextures = new Array();
- this.soundTracks = new Array();
- this._audioEnabled = true;
- this._headphone = false;
- this._totalVertices = 0;
- this._activeIndices = 0;
- this._activeParticles = 0;
- this._lastFrameDuration = 0;
- this._evaluateActiveMeshesDuration = 0;
- this._renderTargetsDuration = 0;
- this._particlesDuration = 0;
- this._renderDuration = 0;
- this._spritesDuration = 0;
- this._animationRatio = 0;
- this._renderId = 0;
- this._executeWhenReadyTimeoutId = -1;
- this._toBeDisposed = new BABYLON.SmartArray(256);
- this._onReadyCallbacks = new Array();
- this._pendingData = []; //ANY
- this._onBeforeRenderCallbacks = new Array();
- this._onAfterRenderCallbacks = new Array();
- this._activeMeshes = new BABYLON.SmartArray(256);
- this._processedMaterials = new BABYLON.SmartArray(256);
- this._renderTargets = new BABYLON.SmartArray(256);
- this._activeParticleSystems = new BABYLON.SmartArray(256);
- this._activeSkeletons = new BABYLON.SmartArray(32);
- this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
- this._activeBones = 0;
- this._activeAnimatables = new Array();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._edgesRenderers = new BABYLON.SmartArray(16);
- this._uniqueIdCounter = 0;
- this._engine = engine;
- engine.scenes.push(this);
- this._renderingManager = new BABYLON.RenderingManager(this);
- this.postProcessManager = new BABYLON.PostProcessManager(this);
- this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
- this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
- if (BABYLON.OutlineRenderer) {
- this._outlineRenderer = new BABYLON.OutlineRenderer(this);
- }
- this.attachControl();
- this._debugLayer = new BABYLON.DebugLayer(this);
- if (BABYLON.SoundTrack) {
- this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
- }
- //simplification queue
- if (BABYLON.SimplificationQueue) {
- this.simplificationQueue = new BABYLON.SimplificationQueue();
- }
- //collision coordinator initialization. For now legacy per default.
- this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
- }
- Object.defineProperty(Scene, "FOGMODE_NONE", {
- get: function () {
- return Scene._FOGMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP", {
- get: function () {
- return Scene._FOGMODE_EXP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP2", {
- get: function () {
- return Scene._FOGMODE_EXP2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_LINEAR", {
- get: function () {
- return Scene._FOGMODE_LINEAR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "debugLayer", {
- // Properties
- get: function () {
- return this._debugLayer;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "workerCollisions", {
- get: function () {
- return this._workerCollisions;
- },
- set: function (enabled) {
- enabled = (enabled && !!Worker);
- this._workerCollisions = enabled;
- if (this.collisionCoordinator) {
- this.collisionCoordinator.destroy();
- }
- this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
- this.collisionCoordinator.init(this);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "SelectionOctree", {
- get: function () {
- return this._selectionOctree;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "meshUnderPointer", {
- /**
- * The mesh that is currently under the pointer.
- * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
- */
- get: function () {
- return this._pointerOverMesh;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "pointerX", {
- /**
- * Current on-screen X position of the pointer
- * @return {number} X position of the pointer
- */
- get: function () {
- return this._pointerX;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "pointerY", {
- /**
- * Current on-screen Y position of the pointer
- * @return {number} Y position of the pointer
- */
- get: function () {
- return this._pointerY;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getCachedMaterial = function () {
- return this._cachedMaterial;
- };
- Scene.prototype.getBoundingBoxRenderer = function () {
- return this._boundingBoxRenderer;
- };
- Scene.prototype.getOutlineRenderer = function () {
- return this._outlineRenderer;
- };
- Scene.prototype.getEngine = function () {
- return this._engine;
- };
- Scene.prototype.getTotalVertices = function () {
- return this._totalVertices;
- };
- Scene.prototype.getActiveIndices = function () {
- return this._activeIndices;
- };
- Scene.prototype.getActiveParticles = function () {
- return this._activeParticles;
- };
- Scene.prototype.getActiveBones = function () {
- return this._activeBones;
- };
- // Stats
- Scene.prototype.getLastFrameDuration = function () {
- return this._lastFrameDuration;
- };
- Scene.prototype.getEvaluateActiveMeshesDuration = function () {
- return this._evaluateActiveMeshesDuration;
- };
- Scene.prototype.getActiveMeshes = function () {
- return this._activeMeshes;
- };
- Scene.prototype.getRenderTargetsDuration = function () {
- return this._renderTargetsDuration;
- };
- Scene.prototype.getRenderDuration = function () {
- return this._renderDuration;
- };
- Scene.prototype.getParticlesDuration = function () {
- return this._particlesDuration;
- };
- Scene.prototype.getSpritesDuration = function () {
- return this._spritesDuration;
- };
- Scene.prototype.getAnimationRatio = function () {
- return this._animationRatio;
- };
- Scene.prototype.getRenderId = function () {
- return this._renderId;
- };
- Scene.prototype.incrementRenderId = function () {
- this._renderId++;
- };
- Scene.prototype._updatePointerPosition = function (evt) {
- var canvasRect = this._engine.getRenderingCanvasClientRect();
- this._pointerX = evt.clientX - canvasRect.left;
- this._pointerY = evt.clientY - canvasRect.top;
- if (this.cameraToUseForPointers) {
- this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
- this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
- }
- };
- // Pointers handling
- Scene.prototype.attachControl = function () {
- var _this = this;
- var spritePredicate = function (sprite) {
- return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
- };
- this._onPointerMove = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- var canvas = _this._engine.getRenderingCanvas();
- _this._updatePointerPosition(evt);
- // Meshes
- var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- _this.setPointerOverSprite(null);
- _this.setPointerOverMesh(pickResult.pickedMesh);
- if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
- canvas.style.cursor = "pointer";
- }
- else {
- canvas.style.cursor = "";
- }
- }
- else {
- _this.setPointerOverMesh(null);
- // Sprites
- pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- canvas.style.cursor = "pointer";
- _this.setPointerOverSprite(pickResult.pickedSprite);
- }
- else {
- _this.setPointerOverSprite(null);
- // Restore pointer
- canvas.style.cursor = "";
- }
- }
- if (_this.onPointerMove) {
- _this.onPointerMove(evt, pickResult);
- }
- };
- this._onPointerDown = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- _this._updatePointerPosition(evt);
- _this._startingPointerPosition.x = _this._pointerX;
- _this._startingPointerPosition.y = _this._pointerY;
- _this._startingPointerTime = new Date().getTime();
- var predicate = null;
- // Meshes
- _this._pickedDownMesh = null;
- if (!_this.onPointerDown && !_this.onPointerPick) {
- predicate = function (mesh) {
- return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
- };
- }
- var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (pickResult.pickedMesh.actionManager) {
- _this._pickedDownMesh = pickResult.pickedMesh;
- if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
- switch (evt.button) {
- case 0:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 1:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 2:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- }
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
- var that = _this;
- window.setTimeout(function () {
- var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (pickResult.pickedMesh.actionManager) {
- if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
- that._startingPointerTime = 0;
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }
- }, BABYLON.ActionManager.LongPressDelay);
- }
- }
- }
- if (_this.onPointerDown) {
- _this.onPointerDown(evt, pickResult);
- }
- // Sprites
- _this._pickedDownSprite = null;
- if (_this.spriteManagers.length > 0) {
- pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- if (pickResult.pickedSprite.actionManager) {
- _this._pickedDownSprite = pickResult.pickedSprite;
- switch (evt.button) {
- case 0:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- case 1:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- case 2:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- }
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- }
- }
- }
- };
- this._onPointerUp = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- var predicate = null;
- _this._updatePointerPosition(evt);
- if (!_this.onPointerUp && !_this.onPointerPick) {
- predicate = function (mesh) {
- return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
- };
- }
- // Meshes
- var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
- _this.onPointerPick(evt, pickResult);
- }
- if (pickResult.pickedMesh.actionManager) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }
- if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
- _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
- }
- if (_this.onPointerUp) {
- _this.onPointerUp(evt, pickResult);
- }
- _this._startingPointerTime = 0;
- // Sprites
- if (_this.spriteManagers.length > 0) {
- pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- if (pickResult.pickedSprite.actionManager) {
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- }
- }
- }
- if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
- _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
- }
- }
- };
- this._onKeyDown = function (evt) {
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- this._onKeyUp = function (evt) {
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
- // Wheel
- this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
- this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp }
- ]);
- };
- Scene.prototype.detachControl = function () {
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
- // Wheel
- this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
- this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp }
- ]);
- };
- // Ready
- Scene.prototype.isReady = function () {
- if (this._pendingData.length > 0) {
- return false;
- }
- var index;
- for (index = 0; index < this._geometries.length; index++) {
- var geometry = this._geometries[index];
- if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- }
- for (index = 0; index < this.meshes.length; index++) {
- var mesh = this.meshes[index];
- if (!mesh.isReady()) {
- return false;
- }
- var mat = mesh.material;
- if (mat) {
- if (!mat.isReady(mesh)) {
- return false;
- }
- }
- }
- return true;
- };
- Scene.prototype.resetCachedMaterial = function () {
- this._cachedMaterial = null;
- };
- Scene.prototype.registerBeforeRender = function (func) {
- this._onBeforeRenderCallbacks.push(func);
- };
- Scene.prototype.unregisterBeforeRender = function (func) {
- var index = this._onBeforeRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforeRenderCallbacks.splice(index, 1);
- }
- };
- Scene.prototype.registerAfterRender = function (func) {
- this._onAfterRenderCallbacks.push(func);
- };
- Scene.prototype.unregisterAfterRender = function (func) {
- var index = this._onAfterRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onAfterRenderCallbacks.splice(index, 1);
- }
- };
- Scene.prototype._addPendingData = function (data) {
- this._pendingData.push(data);
- };
- Scene.prototype._removePendingData = function (data) {
- var index = this._pendingData.indexOf(data);
- if (index !== -1) {
- this._pendingData.splice(index, 1);
- }
- };
- Scene.prototype.getWaitingItemsCount = function () {
- return this._pendingData.length;
- };
- /**
- * Registers a function to be executed when the scene is ready.
- * @param {Function} func - the function to be executed.
- */
- Scene.prototype.executeWhenReady = function (func) {
- var _this = this;
- this._onReadyCallbacks.push(func);
- if (this._executeWhenReadyTimeoutId !== -1) {
- return;
- }
- this._executeWhenReadyTimeoutId = setTimeout(function () {
- _this._checkIsReady();
- }, 150);
- };
- Scene.prototype._checkIsReady = function () {
- var _this = this;
- if (this.isReady()) {
- this._onReadyCallbacks.forEach(function (func) {
- func();
- });
- this._onReadyCallbacks = [];
- this._executeWhenReadyTimeoutId = -1;
- return;
- }
- this._executeWhenReadyTimeoutId = setTimeout(function () {
- _this._checkIsReady();
- }, 150);
- };
- // Animations
- /**
- * Will start the animation sequence of a given target
- * @param target - the target
- * @param {number} from - from which frame should animation start
- * @param {number} to - till which frame should animation run.
- * @param {boolean} [loop] - should the animation loop
- * @param {number} [speedRatio] - the speed in which to run the animation
- * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
- * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
- * @return {BABYLON.Animatable} the animatable object created for this animation
- * @see BABYLON.Animatable
- * @see http://doc.babylonjs.com/page.php?p=22081
- */
- Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
- if (speedRatio === void 0) { speedRatio = 1.0; }
- this.stopAnimation(target);
- if (!animatable) {
- animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
- }
- // Local animations
- if (target.animations) {
- animatable.appendAnimations(target, target.animations);
- }
- // Children animations
- if (target.getAnimatables) {
- var animatables = target.getAnimatables();
- for (var index = 0; index < animatables.length; index++) {
- this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
- }
- }
- return animatable;
- };
- Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
- if (speedRatio === undefined) {
- speedRatio = 1.0;
- }
- var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
- return animatable;
- };
- Scene.prototype.getAnimatableByTarget = function (target) {
- for (var index = 0; index < this._activeAnimatables.length; index++) {
- if (this._activeAnimatables[index].target === target) {
- return this._activeAnimatables[index];
- }
- }
- return null;
- };
- Object.defineProperty(Scene.prototype, "Animatables", {
- get: function () {
- return this._activeAnimatables;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Will stop the animation of the given target
- * @param target - the target
- * @see beginAnimation
- */
- Scene.prototype.stopAnimation = function (target) {
- var animatable = this.getAnimatableByTarget(target);
- if (animatable) {
- animatable.stop();
- }
- };
- Scene.prototype._animate = function () {
- if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
- return;
- }
- if (!this._animationStartDate) {
- if (this._pendingData.length > 0) {
- return;
- }
- this._animationStartDate = BABYLON.Tools.Now;
- }
- // Getting time
- var now = BABYLON.Tools.Now;
- var delay = now - this._animationStartDate;
- for (var index = 0; index < this._activeAnimatables.length; index++) {
- this._activeAnimatables[index]._animate(delay);
- }
- };
- // Matrix
- Scene.prototype.getViewMatrix = function () {
- return this._viewMatrix;
- };
- Scene.prototype.getProjectionMatrix = function () {
- return this._projectionMatrix;
- };
- Scene.prototype.getTransformMatrix = function () {
- return this._transformMatrix;
- };
- Scene.prototype.setTransformMatrix = function (view, projection) {
- this._viewMatrix = view;
- this._projectionMatrix = projection;
- this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- };
- // Methods
- Scene.prototype.addMesh = function (newMesh) {
- newMesh.uniqueId = this._uniqueIdCounter++;
- var position = this.meshes.push(newMesh);
- //notify the collision coordinator
- this.collisionCoordinator.onMeshAdded(newMesh);
- if (this.onNewMeshAdded) {
- this.onNewMeshAdded(newMesh, position, this);
- }
- };
- Scene.prototype.removeMesh = function (toRemove) {
- var index = this.meshes.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.meshes.splice(index, 1);
- }
- //notify the collision coordinator
- this.collisionCoordinator.onMeshRemoved(toRemove);
- if (this.onMeshRemoved) {
- this.onMeshRemoved(toRemove);
- }
- return index;
- };
- Scene.prototype.removeSkeleton = function (toRemove) {
- var index = this.skeletons.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.skeletons.splice(index, 1);
- }
- return index;
- };
- Scene.prototype.removeLight = function (toRemove) {
- var index = this.lights.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.lights.splice(index, 1);
- }
- if (this.onLightRemoved) {
- this.onLightRemoved(toRemove);
- }
- return index;
- };
- Scene.prototype.removeCamera = function (toRemove) {
- var index = this.cameras.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.cameras.splice(index, 1);
- }
- // Remove from activeCameras
- var index2 = this.activeCameras.indexOf(toRemove);
- if (index2 !== -1) {
- // Remove from the scene if mesh found
- this.activeCameras.splice(index2, 1);
- }
- // Reset the activeCamera
- if (this.activeCamera === toRemove) {
- if (this.cameras.length > 0) {
- this.activeCamera = this.cameras[0];
- }
- else {
- this.activeCamera = null;
- }
- }
- if (this.onCameraRemoved) {
- this.onCameraRemoved(toRemove);
- }
- return index;
- };
- Scene.prototype.addLight = function (newLight) {
- newLight.uniqueId = this._uniqueIdCounter++;
- var position = this.lights.push(newLight);
- if (this.onNewLightAdded) {
- this.onNewLightAdded(newLight, position, this);
- }
- };
- Scene.prototype.addCamera = function (newCamera) {
- newCamera.uniqueId = this._uniqueIdCounter++;
- var position = this.cameras.push(newCamera);
- if (this.onNewCameraAdded) {
- this.onNewCameraAdded(newCamera, position, this);
- }
- };
- /**
- * Switch active camera
- * @param {Camera} newCamera - new active camera
- * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
- */
- Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
- if (attachControl === void 0) { attachControl = true; }
- var canvas = this._engine.getRenderingCanvas();
- this.activeCamera.detachControl(canvas);
- this.activeCamera = newCamera;
- if (attachControl) {
- newCamera.attachControl(canvas);
- }
- };
- /**
- * sets the active camera of the scene using its ID
- * @param {string} id - the camera's ID
- * @return {BABYLON.Camera|null} the new active camera or null if none found.
- * @see activeCamera
- */
- Scene.prototype.setActiveCameraByID = function (id) {
- var camera = this.getCameraByID(id);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- };
- /**
- * sets the active camera of the scene using its name
- * @param {string} name - the camera's name
- * @return {BABYLON.Camera|null} the new active camera or null if none found.
- * @see activeCamera
- */
- Scene.prototype.setActiveCameraByName = function (name) {
- var camera = this.getCameraByName(name);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- };
- /**
- * get a material using its id
- * @param {string} the material's ID
- * @return {BABYLON.Material|null} the material or null if none found.
- */
- Scene.prototype.getMaterialByID = function (id) {
- for (var index = 0; index < this.materials.length; index++) {
- if (this.materials[index].id === id) {
- return this.materials[index];
- }
- }
- return null;
- };
- /**
- * get a material using its name
- * @param {string} the material's name
- * @return {BABYLON.Material|null} the material or null if none found.
- */
- Scene.prototype.getMaterialByName = function (name) {
- for (var index = 0; index < this.materials.length; index++) {
- if (this.materials[index].name === name) {
- return this.materials[index];
- }
- }
- return null;
- };
- Scene.prototype.getLensFlareSystemByName = function (name) {
- for (var index = 0; index < this.lensFlareSystems.length; index++) {
- if (this.lensFlareSystems[index].name === name) {
- return this.lensFlareSystems[index];
- }
- }
- return null;
- };
- Scene.prototype.getCameraByID = function (id) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].id === id) {
- return this.cameras[index];
- }
- }
- return null;
- };
- Scene.prototype.getCameraByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].uniqueId === uniqueId) {
- return this.cameras[index];
- }
- }
- return null;
- };
- /**
- * get a camera using its name
- * @param {string} the camera's name
- * @return {BABYLON.Camera|null} the camera or null if none found.
- */
- Scene.prototype.getCameraByName = function (name) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].name === name) {
- return this.cameras[index];
- }
- }
- return null;
- };
- /**
- * get a bone using its id
- * @param {string} the bone's id
- * @return {BABYLON.Bone|null} the bone or null if not found
- */
- Scene.prototype.getBoneByID = function (id) {
- for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
- var skeleton = this.skeletons[skeletonIndex];
- for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
- if (skeleton.bones[boneIndex].id === id) {
- return skeleton.bones[boneIndex];
- }
- }
- }
- return null;
- };
- /**
- * get a bone using its id
- * @param {string} the bone's name
- * @return {BABYLON.Bone|null} the bone or null if not found
- */
- Scene.prototype.getBoneByName = function (name) {
- for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
- var skeleton = this.skeletons[skeletonIndex];
- for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
- if (skeleton.bones[boneIndex].name === name) {
- return skeleton.bones[boneIndex];
- }
- }
- }
- return null;
- };
- /**
- * get a light node using its name
- * @param {string} the light's name
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByName = function (name) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].name === name) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a light node using its ID
- * @param {string} the light's id
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByID = function (id) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].id === id) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a light node using its scene-generated unique ID
- * @param {number} the light's unique id
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].uniqueId === uniqueId) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a particle system by id
- * @param id {number} the particle system id
- * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
- */
- Scene.prototype.getParticleSystemByID = function (id) {
- for (var index = 0; index < this.particleSystems.length; index++) {
- if (this.particleSystems[index].id === id) {
- return this.particleSystems[index];
- }
- }
- return null;
- };
- /**
- * get a geometry using its ID
- * @param {string} the geometry's id
- * @return {BABYLON.Geometry|null} the geometry or null if none found.
- */
- Scene.prototype.getGeometryByID = function (id) {
- for (var index = 0; index < this._geometries.length; index++) {
- if (this._geometries[index].id === id) {
- return this._geometries[index];
- }
- }
- return null;
- };
- /**
- * add a new geometry to this scene.
- * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
- * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
- * @return {boolean} was the geometry added or not
- */
- Scene.prototype.pushGeometry = function (geometry, force) {
- if (!force && this.getGeometryByID(geometry.id)) {
- return false;
- }
- this._geometries.push(geometry);
- //notify the collision coordinator
- this.collisionCoordinator.onGeometryAdded(geometry);
- if (this.onGeometryAdded) {
- this.onGeometryAdded(geometry);
- }
- return true;
- };
- /**
- * Removes an existing geometry
- * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
- * @return {boolean} was the geometry removed or not
- */
- Scene.prototype.removeGeometry = function (geometry) {
- var index = this._geometries.indexOf(geometry);
- if (index > -1) {
- this._geometries.splice(index, 1);
- //notify the collision coordinator
- this.collisionCoordinator.onGeometryDeleted(geometry);
- if (this.onGeometryRemoved) {
- this.onGeometryRemoved(geometry);
- }
- return true;
- }
- return false;
- };
- Scene.prototype.getGeometries = function () {
- return this._geometries;
- };
- /**
- * Get the first added mesh found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getMeshByID = function (id) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- };
- /**
- * Get a mesh with its auto-generated unique id
- * @param {number} uniqueId - the unique id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getMeshByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].uniqueId === uniqueId) {
- return this.meshes[index];
- }
- }
- return null;
- };
- /**
- * Get a the last added mesh found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getLastMeshByID = function (id) {
- for (var index = this.meshes.length - 1; index >= 0; index--) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- };
- /**
- * Get a the last added node (Mesh, Camera, Light) found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.Node|null} the node found or null if not found at all.
- */
- Scene.prototype.getLastEntryByID = function (id) {
- var index;
- for (index = this.meshes.length - 1; index >= 0; index--) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- for (index = this.cameras.length - 1; index >= 0; index--) {
- if (this.cameras[index].id === id) {
- return this.cameras[index];
- }
- }
- for (index = this.lights.length - 1; index >= 0; index--) {
- if (this.lights[index].id === id) {
- return this.lights[index];
- }
- }
- return null;
- };
- Scene.prototype.getNodeByID = function (id) {
- var mesh = this.getMeshByID(id);
- if (mesh) {
- return mesh;
- }
- var light = this.getLightByID(id);
- if (light) {
- return light;
- }
- var camera = this.getCameraByID(id);
- if (camera) {
- return camera;
- }
- var bone = this.getBoneByID(id);
- return bone;
- };
- Scene.prototype.getNodeByName = function (name) {
- var mesh = this.getMeshByName(name);
- if (mesh) {
- return mesh;
- }
- var light = this.getLightByName(name);
- if (light) {
- return light;
- }
- var camera = this.getCameraByName(name);
- if (camera) {
- return camera;
- }
- var bone = this.getBoneByName(name);
- return bone;
- };
- Scene.prototype.getMeshByName = function (name) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].name === name) {
- return this.meshes[index];
- }
- }
- return null;
- };
- Scene.prototype.getSoundByName = function (name) {
- var index;
- if (BABYLON.AudioEngine) {
- for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
- if (this.mainSoundTrack.soundCollection[index].name === name) {
- return this.mainSoundTrack.soundCollection[index];
- }
- }
- for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
- for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
- if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
- return this.soundTracks[sdIndex].soundCollection[index];
- }
- }
- }
- }
- return null;
- };
- Scene.prototype.getLastSkeletonByID = function (id) {
- for (var index = this.skeletons.length - 1; index >= 0; index--) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.getSkeletonById = function (id) {
- for (var index = 0; index < this.skeletons.length; index++) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.getSkeletonByName = function (name) {
- for (var index = 0; index < this.skeletons.length; index++) {
- if (this.skeletons[index].name === name) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.isActiveMesh = function (mesh) {
- return (this._activeMeshes.indexOf(mesh) !== -1);
- };
- Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
- if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
- var material = subMesh.getMaterial();
- if (mesh.showSubMeshesBoundingBox) {
- this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
- }
- if (material) {
- // Render targets
- if (material.getRenderTargetTextures) {
- if (this._processedMaterials.indexOf(material) === -1) {
- this._processedMaterials.push(material);
- this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
- }
- }
- // Dispatch
- this._activeIndices += subMesh.indexCount;
- this._renderingManager.dispatch(subMesh);
- }
- }
- };
- Scene.prototype._evaluateActiveMeshes = function () {
- this.activeCamera._activeMeshes.reset();
- this._activeMeshes.reset();
- this._renderingManager.reset();
- this._processedMaterials.reset();
- this._activeParticleSystems.reset();
- this._activeSkeletons.reset();
- this._softwareSkinnedMeshes.reset();
- this._boundingBoxRenderer.reset();
- this._edgesRenderers.reset();
- if (!this._frustumPlanes) {
- this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
- }
- else {
- BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
- }
- // Meshes
- var meshes;
- var len;
- if (this._selectionOctree) {
- var selection = this._selectionOctree.select(this._frustumPlanes);
- meshes = selection.data;
- len = selection.length;
- }
- else {
- len = this.meshes.length;
- meshes = this.meshes;
- }
- for (var meshIndex = 0; meshIndex < len; meshIndex++) {
- var mesh = meshes[meshIndex];
- if (mesh.isBlocked) {
- continue;
- }
- this._totalVertices += mesh.getTotalVertices();
- if (!mesh.isReady() || !mesh.isEnabled()) {
- continue;
- }
- mesh.computeWorldMatrix();
- // Intersections
- if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
- this._meshesForIntersections.pushNoDuplicate(mesh);
- }
- // Switch to current LOD
- var meshLOD = mesh.getLOD(this.activeCamera);
- if (!meshLOD) {
- continue;
- }
- mesh._preActivate();
- if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
- this._activeMeshes.push(mesh);
- this.activeCamera._activeMeshes.push(mesh);
- mesh._activate(this._renderId);
- this._activeMesh(meshLOD);
- }
- }
- // Particle systems
- var beforeParticlesDate = BABYLON.Tools.Now;
- if (this.particlesEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
- for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
- var particleSystem = this.particleSystems[particleIndex];
- if (!particleSystem.isStarted()) {
- continue;
- }
- if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
- this._activeParticleSystems.push(particleSystem);
- particleSystem.animate();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
- }
- this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
- };
- Scene.prototype._activeMesh = function (mesh) {
- if (mesh.skeleton && this.skeletonsEnabled) {
- this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
- if (!mesh.computeBonesUsingShaders) {
- this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
- }
- }
- if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
- this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
- }
- if (mesh._edgesRenderer) {
- this._edgesRenderers.push(mesh._edgesRenderer);
- }
- if (mesh && mesh.subMeshes) {
- // Submeshes Octrees
- var len;
- var subMeshes;
- if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
- var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = mesh.subMeshes;
- len = subMeshes.length;
- }
- for (var subIndex = 0; subIndex < len; subIndex++) {
- var subMesh = subMeshes[subIndex];
- this._evaluateSubMesh(subMesh, mesh);
- }
- }
- };
- Scene.prototype.updateTransformMatrix = function (force) {
- this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
- };
- Scene.prototype._renderForCamera = function (camera) {
- var engine = this._engine;
- this.activeCamera = camera;
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
- // Viewport
- engine.setViewport(this.activeCamera.viewport);
- // Camera
- this.resetCachedMaterial();
- this._renderId++;
- this.updateTransformMatrix();
- if (this.beforeCameraRender) {
- this.beforeCameraRender(this.activeCamera);
- }
- // Meshes
- var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
- BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
- this._evaluateActiveMeshes();
- this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
- BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
- // Skeletons
- for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
- var skeleton = this._activeSkeletons.data[skeletonIndex];
- skeleton.prepare();
- }
- // Software skinning
- for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
- var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
- mesh.applySkeleton(mesh.skeleton);
- }
- // Render targets
- var beforeRenderTargetDate = BABYLON.Tools.Now;
- if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
- BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
- for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
- var renderTarget = this._renderTargets.data[renderIndex];
- if (renderTarget._shouldRender()) {
- this._renderId++;
- var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
- renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
- this._renderId++;
- engine.restoreDefaultFramebuffer(); // Restore back buffer
- }
- this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
- // Prepare Frame
- this.postProcessManager._prepareFrame();
- var beforeRenderDate = BABYLON.Tools.Now;
- // Backgrounds
- var layerIndex;
- var layer;
- if (this.layers.length) {
- engine.setDepthBuffer(false);
- for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
- layer = this.layers[layerIndex];
- if (layer.isBackground) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- // Render
- BABYLON.Tools.StartPerformanceCounter("Main render");
- this._renderingManager.render(null, null, true, true);
- BABYLON.Tools.EndPerformanceCounter("Main render");
- // Bounding boxes
- this._boundingBoxRenderer.render();
- // Edges
- for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
- this._edgesRenderers.data[edgesRendererIndex].render();
- }
- // Lens flares
- if (this.lensFlaresEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
- for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
- var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
- if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
- lensFlareSystem.render();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
- }
- // Foregrounds
- if (this.layers.length) {
- engine.setDepthBuffer(false);
- for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
- layer = this.layers[layerIndex];
- if (!layer.isBackground) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
- // Finalize frame
- this.postProcessManager._finalizeFrame(camera.isIntermediate);
- // Update camera
- this.activeCamera._updateFromScene();
- // Reset some special arrays
- this._renderTargets.reset();
- if (this.afterCameraRender) {
- this.afterCameraRender(this.activeCamera);
- }
- BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
- };
- Scene.prototype._processSubCameras = function (camera) {
- if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
- this._renderForCamera(camera);
- return;
- }
- // rig cameras
- for (var index = 0; index < camera._rigCameras.length; index++) {
- this._renderForCamera(camera._rigCameras[index]);
- }
- this.activeCamera = camera;
- this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
- // Update camera
- this.activeCamera._updateFromScene();
- };
- Scene.prototype._checkIntersections = function () {
- for (var index = 0; index < this._meshesForIntersections.length; index++) {
- var sourceMesh = this._meshesForIntersections.data[index];
- for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
- var action = sourceMesh.actionManager.actions[actionIndex];
- if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- var parameters = action.getTriggerParameter();
- var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
- var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
- var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
- if (areIntersecting && currentIntersectionInProgress === -1) {
- if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
- action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
- sourceMesh._intersectionsInProgress.push(otherMesh);
- }
- else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- sourceMesh._intersectionsInProgress.push(otherMesh);
- }
- }
- else if (!areIntersecting && currentIntersectionInProgress > -1) {
- //They intersected, and now they don't.
- //is this trigger an exit trigger? execute an event.
- if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
- }
- //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
- if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
- }
- }
- }
- }
- }
- };
- Scene.prototype.render = function () {
- var startDate = BABYLON.Tools.Now;
- this._particlesDuration = 0;
- this._spritesDuration = 0;
- this._activeParticles = 0;
- this._renderDuration = 0;
- this._renderTargetsDuration = 0;
- this._evaluateActiveMeshesDuration = 0;
- this._totalVertices = 0;
- this._activeIndices = 0;
- this._activeBones = 0;
- this.getEngine().resetDrawCalls();
- this._meshesForIntersections.reset();
- this.resetCachedMaterial();
- BABYLON.Tools.StartPerformanceCounter("Scene rendering");
- // Actions
- if (this.actionManager) {
- this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
- }
- //Simplification Queue
- if (this.simplificationQueue && !this.simplificationQueue.running) {
- this.simplificationQueue.executeNext();
- }
- // Animations
- var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
- this._animationRatio = deltaTime * (60.0 / 1000.0);
- this._animate();
- // Physics
- if (this._physicsEngine) {
- BABYLON.Tools.StartPerformanceCounter("Physics");
- this._physicsEngine._runOneStep(deltaTime / 1000.0);
- BABYLON.Tools.EndPerformanceCounter("Physics");
- }
- // Before render
- if (this.beforeRender) {
- this.beforeRender();
- }
- var callbackIndex;
- for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
- this._onBeforeRenderCallbacks[callbackIndex]();
- }
- // Customs render targets
- var beforeRenderTargetDate = BABYLON.Tools.Now;
- var engine = this.getEngine();
- var currentActiveCamera = this.activeCamera;
- if (this.renderTargetsEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
- for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
- var renderTarget = this.customRenderTargets[customIndex];
- if (renderTarget._shouldRender()) {
- this._renderId++;
- this.activeCamera = renderTarget.activeCamera || this.activeCamera;
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- // Viewport
- engine.setViewport(this.activeCamera.viewport);
- // Camera
- this.updateTransformMatrix();
- renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
- this._renderId++;
- }
- if (this.customRenderTargets.length > 0) {
- engine.restoreDefaultFramebuffer();
- }
- this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
- this.activeCamera = currentActiveCamera;
- // Procedural textures
- if (this.proceduralTexturesEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
- for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
- var proceduralTexture = this._proceduralTextures[proceduralIndex];
- if (proceduralTexture._shouldRender()) {
- proceduralTexture.render();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
- }
- // Clear
- this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
- // Shadows
- if (this.shadowsEnabled) {
- for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
- var light = this.lights[lightIndex];
- var shadowGenerator = light.getShadowGenerator();
- if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
- this._renderTargets.push(shadowGenerator.getShadowMap());
- }
- }
- }
- // Depth renderer
- if (this._depthRenderer) {
- this._renderTargets.push(this._depthRenderer.getDepthMap());
- }
- // RenderPipeline
- this.postProcessRenderPipelineManager.update();
- // Multi-cameras?
- if (this.activeCameras.length > 0) {
- var currentRenderId = this._renderId;
- for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
- this._renderId = currentRenderId;
- if (cameraIndex > 0) {
- this._engine.clear(0, false, true);
- }
- this._processSubCameras(this.activeCameras[cameraIndex]);
- }
- }
- else {
- if (!this.activeCamera) {
- throw new Error("No camera defined");
- }
- this._processSubCameras(this.activeCamera);
- }
- // Intersection checks
- this._checkIntersections();
- // Update the audio listener attached to the camera
- if (BABYLON.AudioEngine) {
- this._updateAudioParameters();
- }
- // After render
- if (this.afterRender) {
- this.afterRender();
- }
- for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
- this._onAfterRenderCallbacks[callbackIndex]();
- }
- // Cleaning
- for (var index = 0; index < this._toBeDisposed.length; index++) {
- this._toBeDisposed.data[index].dispose();
- this._toBeDisposed[index] = null;
- }
- this._toBeDisposed.reset();
- if (this.dumpNextRenderTargets) {
- this.dumpNextRenderTargets = false;
- }
- BABYLON.Tools.EndPerformanceCounter("Scene rendering");
- this._lastFrameDuration = BABYLON.Tools.Now - startDate;
- };
- Scene.prototype._updateAudioParameters = function () {
- if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
- return;
- }
- var listeningCamera;
- var audioEngine = BABYLON.Engine.audioEngine;
- if (this.activeCameras.length > 0) {
- listeningCamera = this.activeCameras[0];
- }
- else {
- listeningCamera = this.activeCamera;
- }
- if (listeningCamera && audioEngine.canUseWebAudio) {
- audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
- var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
- var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
- cameraDirection.normalize();
- audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- var sound = this.mainSoundTrack.soundCollection[i];
- if (sound.useCustomAttenuation) {
- sound.updateDistanceFromListener();
- }
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- sound = this.soundTracks[i].soundCollection[j];
- if (sound.useCustomAttenuation) {
- sound.updateDistanceFromListener();
- }
- }
- }
- }
- };
- Object.defineProperty(Scene.prototype, "audioEnabled", {
- // Audio
- get: function () {
- return this._audioEnabled;
- },
- set: function (value) {
- this._audioEnabled = value;
- if (BABYLON.AudioEngine) {
- if (this._audioEnabled) {
- this._enableAudio();
- }
- else {
- this._disableAudio();
- }
- }
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype._disableAudio = function () {
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- this.mainSoundTrack.soundCollection[i].pause();
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- this.soundTracks[i].soundCollection[j].pause();
- }
- }
- };
- Scene.prototype._enableAudio = function () {
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- if (this.mainSoundTrack.soundCollection[i].isPaused) {
- this.mainSoundTrack.soundCollection[i].play();
- }
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- if (this.soundTracks[i].soundCollection[j].isPaused) {
- this.soundTracks[i].soundCollection[j].play();
- }
- }
- }
- };
- Object.defineProperty(Scene.prototype, "headphone", {
- get: function () {
- return this._headphone;
- },
- set: function (value) {
- this._headphone = value;
- if (BABYLON.AudioEngine) {
- if (this._headphone) {
- this._switchAudioModeForHeadphones();
- }
- else {
- this._switchAudioModeForNormalSpeakers();
- }
- }
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype._switchAudioModeForHeadphones = function () {
- this.mainSoundTrack.switchPanningModelToHRTF();
- for (var i = 0; i < this.soundTracks.length; i++) {
- this.soundTracks[i].switchPanningModelToHRTF();
- }
- };
- Scene.prototype._switchAudioModeForNormalSpeakers = function () {
- this.mainSoundTrack.switchPanningModelToEqualPower();
- for (var i = 0; i < this.soundTracks.length; i++) {
- this.soundTracks[i].switchPanningModelToEqualPower();
- }
- };
- Scene.prototype.enableDepthRenderer = function () {
- if (this._depthRenderer) {
- return this._depthRenderer;
- }
- this._depthRenderer = new BABYLON.DepthRenderer(this);
- return this._depthRenderer;
- };
- Scene.prototype.disableDepthRenderer = function () {
- if (!this._depthRenderer) {
- return;
- }
- this._depthRenderer.dispose();
- this._depthRenderer = null;
- };
- Scene.prototype.freezeMaterials = function () {
- for (var i = 0; i < this.materials.length; i++) {
- this.materials[i].freeze();
- }
- };
- Scene.prototype.unfreezeMaterials = function () {
- for (var i = 0; i < this.materials.length; i++) {
- this.materials[i].unfreeze();
- }
- };
- Scene.prototype.dispose = function () {
- this.beforeRender = null;
- this.afterRender = null;
- this.skeletons = [];
- this._boundingBoxRenderer.dispose();
- if (this._depthRenderer) {
- this._depthRenderer.dispose();
- }
- // Debug layer
- this.debugLayer.hide();
- // Events
- if (this.onDispose) {
- this.onDispose();
- }
- this._onBeforeRenderCallbacks = [];
- this._onAfterRenderCallbacks = [];
- this.detachControl();
- // Release sounds & sounds tracks
- if (BABYLON.AudioEngine) {
- this.disposeSounds();
- }
- // Detach cameras
- var canvas = this._engine.getRenderingCanvas();
- var index;
- for (index = 0; index < this.cameras.length; index++) {
- this.cameras[index].detachControl(canvas);
- }
- // Release lights
- while (this.lights.length) {
- this.lights[0].dispose();
- }
- // Release meshes
- while (this.meshes.length) {
- this.meshes[0].dispose(true);
- }
- // Release cameras
- while (this.cameras.length) {
- this.cameras[0].dispose();
- }
- // Release materials
- while (this.materials.length) {
- this.materials[0].dispose();
- }
- // Release particles
- while (this.particleSystems.length) {
- this.particleSystems[0].dispose();
- }
- // Release sprites
- while (this.spriteManagers.length) {
- this.spriteManagers[0].dispose();
- }
- // Release layers
- while (this.layers.length) {
- this.layers[0].dispose();
- }
- // Release textures
- while (this.textures.length) {
- this.textures[0].dispose();
- }
- // Post-processes
- this.postProcessManager.dispose();
- // Physics
- if (this._physicsEngine) {
- this.disablePhysicsEngine();
- }
- // Remove from engine
- index = this._engine.scenes.indexOf(this);
- if (index > -1) {
- this._engine.scenes.splice(index, 1);
- }
- this._engine.wipeCaches();
- };
- // Release sounds & sounds tracks
- Scene.prototype.disposeSounds = function () {
- this.mainSoundTrack.dispose();
- for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
- this.soundTracks[scIndex].dispose();
- }
- };
- // Octrees
- Scene.prototype.getWorldExtends = function () {
- var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = 0; index < this.meshes.length; index++) {
- var mesh = this.meshes[index];
- mesh.computeWorldMatrix(true);
- var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
- var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
- BABYLON.Tools.CheckExtends(minBox, min, max);
- BABYLON.Tools.CheckExtends(maxBox, min, max);
- }
- return {
- min: min,
- max: max
- };
- };
- Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
- if (maxCapacity === void 0) { maxCapacity = 64; }
- if (maxDepth === void 0) { maxDepth = 2; }
- if (!this._selectionOctree) {
- this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
- }
- var worldExtends = this.getWorldExtends();
- // Update octree
- this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
- return this._selectionOctree;
- };
- // Picking
- Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
- if (cameraViewSpace === void 0) { cameraViewSpace = false; }
- var engine = this._engine;
- if (!camera) {
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- camera = this.activeCamera;
- }
- var cameraViewport = camera.viewport;
- var viewport = cameraViewport.toGlobal(engine);
- // Moving coordinates to local viewport world
- x = x / this._engine.getHardwareScalingLevel() - viewport.x;
- y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
- return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
- // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
- };
- Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
- var engine = this._engine;
- if (!camera) {
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- camera = this.activeCamera;
- }
- var cameraViewport = camera.viewport;
- var viewport = cameraViewport.toGlobal(engine);
- var identity = BABYLON.Matrix.Identity();
- // Moving coordinates to local viewport world
- x = x / this._engine.getHardwareScalingLevel() - viewport.x;
- y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
- return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
- };
- Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
- var pickingInfo = null;
- for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
- var mesh = this.meshes[meshIndex];
- if (predicate) {
- if (!predicate(mesh)) {
- continue;
- }
- }
- else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
- continue;
- }
- var world = mesh.getWorldMatrix();
- var ray = rayFunction(world);
- var result = mesh.intersects(ray, fastCheck);
- if (!result || !result.hit)
- continue;
- if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
- continue;
- pickingInfo = result;
- if (fastCheck) {
- break;
- }
- }
- return pickingInfo || new BABYLON.PickingInfo();
- };
- Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
- var pickingInfo = null;
- camera = camera || this.activeCamera;
- if (this.spriteManagers.length > 0) {
- for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
- var spriteManager = this.spriteManagers[spriteIndex];
- if (!spriteManager.isPickable) {
- continue;
- }
- var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
- if (!result || !result.hit)
- continue;
- if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
- continue;
- pickingInfo = result;
- if (fastCheck) {
- break;
- }
- }
- }
- return pickingInfo || new BABYLON.PickingInfo();
- };
- Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
- var _this = this;
- /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
- /// <param name="x">X position on screen</param>
- /// <param name="y">Y position on screen</param>
- /// <param name="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</param>
- /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
- /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
- return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
- };
- Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
- /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
- /// <param name="x">X position on screen</param>
- /// <param name="y">Y position on screen</param>
- /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
- /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
- /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
- return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
- };
- Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
- var _this = this;
- return this._internalPick(function (world) {
- if (!_this._pickWithRayInverseMatrix) {
- _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
- }
- world.invertToRef(_this._pickWithRayInverseMatrix);
- return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
- }, predicate, fastCheck);
- };
- Scene.prototype.setPointerOverMesh = function (mesh) {
- if (this._pointerOverMesh === mesh) {
- return;
- }
- if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
- this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
- }
- this._pointerOverMesh = mesh;
- if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
- this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
- }
- };
- Scene.prototype.getPointerOverMesh = function () {
- return this._pointerOverMesh;
- };
- Scene.prototype.setPointerOverSprite = function (sprite) {
- if (this._pointerOverSprite === sprite) {
- return;
- }
- if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
- this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
- }
- this._pointerOverSprite = sprite;
- if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
- this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
- }
- };
- Scene.prototype.getPointerOverSprite = function () {
- return this._pointerOverSprite;
- };
- // Physics
- Scene.prototype.getPhysicsEngine = function () {
- return this._physicsEngine;
- };
- /**
- * Enables physics to the current scene
- * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
- * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
- * @return {boolean} was the physics engine initialized
- */
- Scene.prototype.enablePhysics = function (gravity, plugin) {
- if (this._physicsEngine) {
- return true;
- }
- this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
- if (!this._physicsEngine.isSupported()) {
- this._physicsEngine = null;
- return false;
- }
- this._physicsEngine._initialize(gravity);
- return true;
- };
- Scene.prototype.disablePhysicsEngine = function () {
- if (!this._physicsEngine) {
- return;
- }
- this._physicsEngine.dispose();
- this._physicsEngine = undefined;
- };
- Scene.prototype.isPhysicsEnabled = function () {
- return this._physicsEngine !== undefined;
- };
- /**
- * Sets the gravity of the physics engine (and NOT of the scene)
- * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
- */
- Scene.prototype.setGravity = function (gravity) {
- if (!this._physicsEngine) {
- return;
- }
- this._physicsEngine._setGravity(gravity);
- };
- Scene.prototype.createCompoundImpostor = function (parts, options) {
- if (parts.parts) {
- options = parts;
- parts = parts.parts;
- }
- if (!this._physicsEngine) {
- return null;
- }
- for (var index = 0; index < parts.length; index++) {
- var mesh = parts[index].mesh;
- mesh._physicImpostor = parts[index].impostor;
- mesh._physicsMass = options.mass / parts.length;
- mesh._physicsFriction = options.friction;
- mesh._physicRestitution = options.restitution;
- }
- return this._physicsEngine._registerMeshesAsCompound(parts, options);
- };
- Scene.prototype.deleteCompoundImpostor = function (compound) {
- for (var index = 0; index < compound.parts.length; index++) {
- var mesh = compound.parts[index].mesh;
- mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
- this._physicsEngine._unregisterMesh(mesh);
- }
- };
- // Misc.
- Scene.prototype.createDefaultCameraOrLight = function () {
- // Light
- if (this.lights.length === 0) {
- new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
- }
- // Camera
- if (!this.activeCamera) {
- var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
- // Compute position
- var worldExtends = this.getWorldExtends();
- var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
- camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
- camera.setTarget(worldCenter);
- this.activeCamera = camera;
- }
- };
- // Tags
- Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
- if (tagsQuery === undefined) {
- // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
- return list;
- }
- var listByTags = [];
- forEach = forEach || (function (item) { return; });
- for (var i in list) {
- var item = list[i];
- if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
- listByTags.push(item);
- forEach(item);
- }
- }
- return listByTags;
- };
- Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.meshes, tagsQuery, forEach);
- };
- Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.cameras, tagsQuery, forEach);
- };
- Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.lights, tagsQuery, forEach);
- };
- Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
- };
- // Statics
- Scene._FOGMODE_NONE = 0;
- Scene._FOGMODE_EXP = 1;
- Scene._FOGMODE_EXP2 = 2;
- Scene._FOGMODE_LINEAR = 3;
- Scene.MinDeltaTime = 1.0;
- Scene.MaxDeltaTime = 1000.0;
- return Scene;
- })();
- BABYLON.Scene = Scene;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VertexBuffer = (function () {
- function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
- if (engine instanceof BABYLON.Mesh) {
- this._engine = engine.getScene().getEngine();
- }
- else {
- this._engine = engine;
- }
- this._updatable = updatable;
- this._data = data;
- if (!postponeInternalCreation) {
- this.create();
- }
- this._kind = kind;
- if (stride) {
- this._strideSize = stride;
- return;
- }
- // Deduce stride from kind
- switch (kind) {
- case VertexBuffer.PositionKind:
- this._strideSize = 3;
- break;
- case VertexBuffer.NormalKind:
- this._strideSize = 3;
- break;
- case VertexBuffer.UVKind:
- case VertexBuffer.UV2Kind:
- case VertexBuffer.UV3Kind:
- case VertexBuffer.UV4Kind:
- case VertexBuffer.UV5Kind:
- case VertexBuffer.UV6Kind:
- this._strideSize = 2;
- break;
- case VertexBuffer.ColorKind:
- this._strideSize = 4;
- break;
- case VertexBuffer.MatricesIndicesKind:
- case VertexBuffer.MatricesIndicesExtraKind:
- this._strideSize = 4;
- break;
- case VertexBuffer.MatricesWeightsKind:
- case VertexBuffer.MatricesWeightsExtraKind:
- this._strideSize = 4;
- break;
- }
- }
- // Properties
- VertexBuffer.prototype.isUpdatable = function () {
- return this._updatable;
- };
- VertexBuffer.prototype.getData = function () {
- return this._data;
- };
- VertexBuffer.prototype.getBuffer = function () {
- return this._buffer;
- };
- VertexBuffer.prototype.getStrideSize = function () {
- return this._strideSize;
- };
- // Methods
- VertexBuffer.prototype.create = function (data) {
- if (!data && this._buffer) {
- return; // nothing to do
- }
- data = data || this._data;
- if (!this._buffer) {
- if (this._updatable) {
- this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
- }
- else {
- this._buffer = this._engine.createVertexBuffer(data);
- }
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data);
- this._data = data;
- }
- };
- VertexBuffer.prototype.update = function (data) {
- this.create(data);
- };
- VertexBuffer.prototype.updateDirectly = function (data, offset) {
- if (!this._buffer) {
- return;
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
- this._data = null;
- }
- };
- VertexBuffer.prototype.dispose = function () {
- if (!this._buffer) {
- return;
- }
- if (this._engine._releaseBuffer(this._buffer)) {
- this._buffer = null;
- }
- };
- Object.defineProperty(VertexBuffer, "PositionKind", {
- get: function () {
- return VertexBuffer._PositionKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "NormalKind", {
- get: function () {
- return VertexBuffer._NormalKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UVKind", {
- get: function () {
- return VertexBuffer._UVKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV2Kind", {
- get: function () {
- return VertexBuffer._UV2Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV3Kind", {
- get: function () {
- return VertexBuffer._UV3Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV4Kind", {
- get: function () {
- return VertexBuffer._UV4Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV5Kind", {
- get: function () {
- return VertexBuffer._UV5Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV6Kind", {
- get: function () {
- return VertexBuffer._UV6Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "ColorKind", {
- get: function () {
- return VertexBuffer._ColorKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
- get: function () {
- return VertexBuffer._MatricesIndicesKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
- get: function () {
- return VertexBuffer._MatricesWeightsKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
- get: function () {
- return VertexBuffer._MatricesIndicesExtraKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
- get: function () {
- return VertexBuffer._MatricesWeightsExtraKind;
- },
- enumerable: true,
- configurable: true
- });
- // Enums
- VertexBuffer._PositionKind = "position";
- VertexBuffer._NormalKind = "normal";
- VertexBuffer._UVKind = "uv";
- VertexBuffer._UV2Kind = "uv2";
- VertexBuffer._UV3Kind = "uv3";
- VertexBuffer._UV4Kind = "uv4";
- VertexBuffer._UV5Kind = "uv5";
- VertexBuffer._UV6Kind = "uv6";
- VertexBuffer._ColorKind = "color";
- VertexBuffer._MatricesIndicesKind = "matricesIndices";
- VertexBuffer._MatricesWeightsKind = "matricesWeights";
- VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
- VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
- return VertexBuffer;
- })();
- BABYLON.VertexBuffer = VertexBuffer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Creates an instance based on a source mesh.
- */
- var InstancedMesh = (function (_super) {
- __extends(InstancedMesh, _super);
- function InstancedMesh(name, source) {
- _super.call(this, name, source.getScene());
- source.instances.push(this);
- this._sourceMesh = source;
- this.position.copyFrom(source.position);
- this.rotation.copyFrom(source.rotation);
- this.scaling.copyFrom(source.scaling);
- if (source.rotationQuaternion) {
- this.rotationQuaternion = source.rotationQuaternion.clone();
- }
- this.infiniteDistance = source.infiniteDistance;
- this.setPivotMatrix(source.getPivotMatrix());
- this.refreshBoundingInfo();
- this._syncSubMeshes();
- }
- Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
- // Methods
- get: function () {
- return this._sourceMesh.receiveShadows;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "material", {
- get: function () {
- return this._sourceMesh.material;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "visibility", {
- get: function () {
- return this._sourceMesh.visibility;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "skeleton", {
- get: function () {
- return this._sourceMesh.skeleton;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
- get: function () {
- return this._sourceMesh.renderingGroupId;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.getTotalVertices = function () {
- return this._sourceMesh.getTotalVertices();
- };
- Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
- get: function () {
- return this._sourceMesh;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
- return this._sourceMesh.getVerticesData(kind, copyWhenShared);
- };
- InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
- return this._sourceMesh.isVerticesDataPresent(kind);
- };
- InstancedMesh.prototype.getIndices = function () {
- return this._sourceMesh.getIndices();
- };
- Object.defineProperty(InstancedMesh.prototype, "_positions", {
- get: function () {
- return this._sourceMesh._positions;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.refreshBoundingInfo = function () {
- var meshBB = this._sourceMesh.getBoundingInfo();
- this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
- this._updateBoundingInfo();
- };
- InstancedMesh.prototype._preActivate = function () {
- if (this._currentLOD) {
- this._currentLOD._preActivate();
- }
- };
- InstancedMesh.prototype._activate = function (renderId) {
- if (this._currentLOD) {
- this._currentLOD._registerInstanceForRenderId(this, renderId);
- }
- };
- InstancedMesh.prototype.getLOD = function (camera) {
- this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
- if (this._currentLOD === this.sourceMesh) {
- return this;
- }
- return this._currentLOD;
- };
- InstancedMesh.prototype._syncSubMeshes = function () {
- this.releaseSubMeshes();
- if (this._sourceMesh.subMeshes) {
- for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
- this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
- }
- }
- };
- InstancedMesh.prototype._generatePointsArray = function () {
- return this._sourceMesh._generatePointsArray();
- };
- // Clone
- InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- var result = this._sourceMesh.createInstance(name);
- // Deep copy
- BABYLON.Tools.DeepCopy(this, result, ["name"], []);
- // Bounding info
- this.refreshBoundingInfo();
- // Parent
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- // Children
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent === this) {
- mesh.clone(mesh.name, result);
- }
- }
- }
- result.computeWorldMatrix(true);
- return result;
- };
- // Dispoe
- InstancedMesh.prototype.dispose = function (doNotRecurse) {
- // Remove from mesh
- var index = this._sourceMesh.instances.indexOf(this);
- this._sourceMesh.instances.splice(index, 1);
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- return InstancedMesh;
- })(BABYLON.AbstractMesh);
- BABYLON.InstancedMesh = InstancedMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var _InstancesBatch = (function () {
- function _InstancesBatch() {
- this.mustReturn = false;
- this.visibleInstances = new Array();
- this.renderSelf = new Array();
- }
- return _InstancesBatch;
- })();
- BABYLON._InstancesBatch = _InstancesBatch;
- var Mesh = (function (_super) {
- __extends(Mesh, _super);
- /**
- * @constructor
- * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
- * @param {Scene} scene - The scene to add this mesh to.
- * @param {Node} parent - The parent of this mesh, if it has one
- * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
- * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
- * When false, achieved by calling a clone(), also passing False.
- * This will make creation of children, recursive.
- */
- function Mesh(name, scene, parent, source, doNotCloneChildren) {
- if (parent === void 0) { parent = null; }
- _super.call(this, name, scene);
- // Members
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.instances = new Array();
- this._LODLevels = new Array();
- this._onBeforeRenderCallbacks = new Array();
- this._onAfterRenderCallbacks = new Array();
- this._visibleInstances = {};
- this._renderIdForInstances = new Array();
- this._batchCache = new _InstancesBatch();
- this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
- this._sideOrientation = Mesh._DEFAULTSIDE;
- this._areNormalsFrozen = false; // Will be used by ribbons mainly
- if (source) {
- // Geometry
- if (source._geometry) {
- source._geometry.applyToMesh(this);
- }
- // Deep copy
- BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
- this.id = name + "." + source.id;
- // Material
- this.material = source.material;
- var index;
- if (!doNotCloneChildren) {
- // Children
- for (index = 0; index < scene.meshes.length; index++) {
- var mesh = scene.meshes[index];
- if (mesh.parent === source) {
- // doNotCloneChildren is always going to be False
- var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
- }
- }
- }
- // Particles
- for (index = 0; index < scene.particleSystems.length; index++) {
- var system = scene.particleSystems[index];
- if (system.emitter === source) {
- system.clone(system.name, this);
- }
- }
- this.computeWorldMatrix(true);
- }
- // Parent
- if (parent !== null) {
- this.parent = parent;
- }
- }
- Object.defineProperty(Mesh, "FRONTSIDE", {
- get: function () {
- return Mesh._FRONTSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "BACKSIDE", {
- get: function () {
- return Mesh._BACKSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "DOUBLESIDE", {
- get: function () {
- return Mesh._DOUBLESIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "DEFAULTSIDE", {
- get: function () {
- return Mesh._DEFAULTSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "NO_CAP", {
- get: function () {
- return Mesh._NO_CAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_START", {
- get: function () {
- return Mesh._CAP_START;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_END", {
- get: function () {
- return Mesh._CAP_END;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_ALL", {
- get: function () {
- return Mesh._CAP_ALL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "hasLODLevels", {
- // Methods
- get: function () {
- return this._LODLevels.length > 0;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype._sortLODLevels = function () {
- this._LODLevels.sort(function (a, b) {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- };
- /**
- * Add a mesh as LOD level triggered at the given distance.
- * @param {number} distance - the distance from the center of the object to show this level
- * @param {Mesh} mesh - the mesh to be added as LOD level
- * @return {Mesh} this mesh (for chaining)
- */
- Mesh.prototype.addLODLevel = function (distance, mesh) {
- if (mesh && mesh._masterMesh) {
- BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
- return this;
- }
- var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._masterMesh = this;
- }
- this._sortLODLevels();
- return this;
- };
- Mesh.prototype.getLODLevelAtDistance = function (distance) {
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance === distance) {
- return level.mesh;
- }
- }
- return null;
- };
- /**
- * Remove a mesh from the LOD array
- * @param {Mesh} mesh - the mesh to be removed.
- * @return {Mesh} this mesh (for chaining)
- */
- Mesh.prototype.removeLODLevel = function (mesh) {
- for (var index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === mesh) {
- this._LODLevels.splice(index, 1);
- if (mesh) {
- mesh._masterMesh = null;
- }
- }
- }
- this._sortLODLevels();
- return this;
- };
- Mesh.prototype.getLOD = function (camera, boundingSphere) {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
- }
- return this;
- }
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance < distanceToCamera) {
- if (level.mesh) {
- level.mesh._preActivate();
- level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, level.mesh);
- }
- return level.mesh;
- }
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this);
- }
- return this;
- };
- Object.defineProperty(Mesh.prototype, "geometry", {
- get: function () {
- return this._geometry;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype.getTotalVertices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalVertices();
- };
- Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind, copyWhenShared);
- };
- Mesh.prototype.getVertexBuffer = function (kind) {
- if (!this._geometry) {
- return undefined;
- }
- return this._geometry.getVertexBuffer(kind);
- };
- Mesh.prototype.isVerticesDataPresent = function (kind) {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVerticesDataPresent(kind);
- };
- Mesh.prototype.getVerticesDataKinds = function () {
- if (!this._geometry) {
- var result = [];
- if (this._delayInfo) {
- for (var kind in this._delayInfo) {
- result.push(kind);
- }
- }
- return result;
- }
- return this._geometry.getVerticesDataKinds();
- };
- Mesh.prototype.getTotalIndices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalIndices();
- };
- Mesh.prototype.getIndices = function (copyWhenShared) {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices(copyWhenShared);
- };
- Object.defineProperty(Mesh.prototype, "isBlocked", {
- get: function () {
- return this._masterMesh !== null && this._masterMesh !== undefined;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- return _super.prototype.isReady.call(this);
- };
- Mesh.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- Object.defineProperty(Mesh.prototype, "sideOrientation", {
- get: function () {
- return this._sideOrientation;
- },
- set: function (sideO) {
- this._sideOrientation = sideO;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
- get: function () {
- return this._areNormalsFrozen;
- },
- enumerable: true,
- configurable: true
- });
- /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
- Mesh.prototype.freezeNormals = function () {
- this._areNormalsFrozen = true;
- };
- /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
- Mesh.prototype.unfreezeNormals = function () {
- this._areNormalsFrozen = false;
- };
- // Methods
- Mesh.prototype._preActivate = function () {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId === sceneRenderId) {
- return;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- };
- Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
- if (!this._visibleInstances) {
- this._visibleInstances = {};
- this._visibleInstances.defaultRenderId = renderId;
- this._visibleInstances.selfDefaultRenderId = this._renderId;
- }
- if (!this._visibleInstances[renderId]) {
- this._visibleInstances[renderId] = new Array();
- }
- this._visibleInstances[renderId].push(instance);
- };
- Mesh.prototype.refreshBoundingInfo = function () {
- if (this._boundingInfo.isLocked) {
- return;
- }
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (data) {
- var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- }
- if (this.subMeshes) {
- for (var index = 0; index < this.subMeshes.length; index++) {
- this.subMeshes[index].refreshBoundingInfo();
- }
- }
- this._updateBoundingInfo();
- };
- Mesh.prototype._createGlobalSubMesh = function () {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- this.releaseSubMeshes();
- return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
- };
- Mesh.prototype.subdivide = function (count) {
- if (count < 1) {
- return;
- }
- var totalIndices = this.getTotalIndices();
- var subdivisionSize = (totalIndices / count) | 0;
- var offset = 0;
- // Ensure that subdivisionSize is a multiple of 3
- while (subdivisionSize % 3 !== 0) {
- subdivisionSize++;
- }
- this.releaseSubMeshes();
- for (var index = 0; index < count; index++) {
- if (offset >= totalIndices) {
- break;
- }
- BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- };
- Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setVerticesData(kind, data, updatable, stride);
- }
- };
- Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- };
- Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
- BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesDataDirectly(kind, data, offset);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesDataDirectly(kind, data, offset, false);
- }
- };
- // Mesh positions update function :
- // updates the mesh positions according to the positionFunction returned values.
- // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
- // This dedicated positionFunction computes new mesh positions according to the given mesh type.
- Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
- if (computeNormals === void 0) { computeNormals = true; }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- positionFunction(positions);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
- if (computeNormals) {
- var indices = this.getIndices();
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
- }
- };
- Mesh.prototype.makeGeometryUnique = function () {
- if (!this._geometry) {
- return;
- }
- var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
- geometry.applyToMesh(this);
- };
- Mesh.prototype.setIndices = function (indices, totalVertices) {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
- }
- else {
- this._geometry.setIndices(indices, totalVertices);
- }
- };
- Mesh.prototype._bind = function (subMesh, effect, fillMode) {
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- if (this._unIndexed) {
- indexToBind = null;
- }
- else {
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- indexToBind = null;
- break;
- case BABYLON.Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
- break;
- default:
- case BABYLON.Material.TriangleFillMode:
- indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
- break;
- }
- }
- // VBOs
- engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
- };
- Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- if (this.onBeforeDraw) {
- this.onBeforeDraw();
- }
- var engine = this.getScene().getEngine();
- // Draw order
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- break;
- case BABYLON.Material.WireFrameFillMode:
- if (this._unIndexed) {
- engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- }
- else {
- engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
- }
- break;
- default:
- if (this._unIndexed) {
- engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- }
- else {
- engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- }
- };
- Mesh.prototype.registerBeforeRender = function (func) {
- this._onBeforeRenderCallbacks.push(func);
- };
- Mesh.prototype.unregisterBeforeRender = function (func) {
- var index = this._onBeforeRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforeRenderCallbacks.splice(index, 1);
- }
- };
- Mesh.prototype.registerAfterRender = function (func) {
- this._onAfterRenderCallbacks.push(func);
- };
- Mesh.prototype.unregisterAfterRender = function (func) {
- var index = this._onAfterRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onAfterRenderCallbacks.splice(index, 1);
- }
- };
- Mesh.prototype._getInstancesRenderList = function (subMeshId) {
- var scene = this.getScene();
- this._batchCache.mustReturn = false;
- this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
- this._batchCache.visibleInstances[subMeshId] = null;
- if (this._visibleInstances) {
- var currentRenderId = scene.getRenderId();
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
- currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
- selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
- }
- if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
- if (this._renderIdForInstances[subMeshId] === currentRenderId) {
- this._batchCache.mustReturn = true;
- return this._batchCache;
- }
- if (currentRenderId !== selfRenderId) {
- this._batchCache.renderSelf[subMeshId] = false;
- }
- }
- this._renderIdForInstances[subMeshId] = currentRenderId;
- }
- return this._batchCache;
- };
- Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
- var visibleInstances = batch.visibleInstances[subMesh._id];
- var matricesCount = visibleInstances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
- if (this._worldMatricesInstancesBuffer) {
- engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- }
- this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
- this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- }
- var offsetLocation0 = effect.getAttributeLocationByName("world0");
- var offsetLocation1 = effect.getAttributeLocationByName("world1");
- var offsetLocation2 = effect.getAttributeLocationByName("world2");
- var offsetLocation3 = effect.getAttributeLocationByName("world3");
- var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
- engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
- };
- Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- }
- else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- if (onBeforeDraw) {
- onBeforeDraw(false, this.getWorldMatrix());
- }
- this._draw(subMesh, fillMode);
- }
- if (batch.visibleInstances[subMesh._id]) {
- for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
- var instance = batch.visibleInstances[subMesh._id][instanceIndex];
- // World
- var world = instance.getWorldMatrix();
- if (onBeforeDraw) {
- onBeforeDraw(true, world);
- }
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- };
- Mesh.prototype.render = function (subMesh, enableAlphaMode) {
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var callbackIndex;
- for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
- this._onBeforeRenderCallbacks[callbackIndex](this);
- }
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // Material
- var effectiveMaterial = subMesh.getMaterial();
- if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return;
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setDepthWrite(savedDepthWrite);
- }
- effectiveMaterial._preBind();
- var effect = effectiveMaterial.getEffect();
- // Bind
- var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
- this._bind(subMesh, effect, fillMode);
- var world = this.getWorldMatrix();
- effectiveMaterial.bind(world, this);
- // Alpha mode
- if (enableAlphaMode) {
- engine.setAlphaMode(effectiveMaterial.alphaMode);
- }
- // Draw
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
- if (isInstance) {
- effectiveMaterial.bindOnlyWorldMatrix(world);
- }
- });
- // Unbind
- effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- // Overlay
- if (this.renderOverlay) {
- var currentMode = engine.getAlphaMode();
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- scene.getOutlineRenderer().render(subMesh, batch, true);
- engine.setAlphaMode(currentMode);
- }
- for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
- this._onAfterRenderCallbacks[callbackIndex](this);
- }
- };
- Mesh.prototype.getEmittedParticleSystems = function () {
- var results = new Array();
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (particleSystem.emitter === this) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
- var results = new Array();
- var descendants = this.getDescendants();
- descendants.push(this);
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (descendants.indexOf(particleSystem.emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype.getChildren = function () {
- var results = [];
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent === this) {
- results.push(mesh);
- }
- }
- return results;
- };
- Mesh.prototype._checkDelayState = function () {
- var _this = this;
- var that = this;
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(that);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
- BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
- if (data instanceof ArrayBuffer) {
- _this._delayLoadingFunction(data, _this);
- }
- else {
- _this._delayLoadingFunction(JSON.parse(data), _this);
- }
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(_this);
- }, function () { }, scene.database, getBinaryData);
- }
- };
- Mesh.prototype.isInFrustum = function (frustumPlanes) {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
- return false;
- }
- this._checkDelayState();
- return true;
- };
- Mesh.prototype.setMaterialByID = function (id) {
- var materials = this.getScene().materials;
- var index;
- for (index = 0; index < materials.length; index++) {
- if (materials[index].id === id) {
- this.material = materials[index];
- return;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = 0; index < multiMaterials.length; index++) {
- if (multiMaterials[index].id === id) {
- this.material = multiMaterials[index];
- return;
- }
- }
- };
- Mesh.prototype.getAnimatables = function () {
- var results = [];
- if (this.material) {
- results.push(this.material);
- }
- if (this.skeleton) {
- results.push(this.skeleton);
- }
- return results;
- };
- // Geometry
- Mesh.prototype.bakeTransformIntoVertices = function (transform) {
- // Position
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return;
- }
- this._resetPointsArrayCache();
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var temp = [];
- var index;
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return;
- }
- data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- temp = [];
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
- // flip faces?
- if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
- this.flipFaces();
- }
- };
- // Will apply current transform to mesh and reset world matrix
- Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
- this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
- this.scaling.copyFromFloats(1, 1, 1);
- this.position.copyFromFloats(0, 0, 0);
- this.rotation.copyFromFloats(0, 0, 0);
- //only if quaternion is already set
- if (this.rotationQuaternion) {
- this.rotationQuaternion = BABYLON.Quaternion.Identity();
- }
- this._worldMatrix = BABYLON.Matrix.Identity();
- };
- // Cache
- Mesh.prototype._resetPointsArrayCache = function () {
- this._positions = null;
- };
- Mesh.prototype._generatePointsArray = function () {
- if (this._positions)
- return true;
- this._positions = [];
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- return false;
- }
- for (var index = 0; index < data.length; index += 3) {
- this._positions.push(BABYLON.Vector3.FromArray(data, index));
- }
- return true;
- };
- // Clone
- Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
- };
- // Dispose
- Mesh.prototype.dispose = function (doNotRecurse) {
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Instances
- if (this._worldMatricesInstancesBuffer) {
- this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- this._worldMatricesInstancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- // Geometric tools
- Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
- var _this = this;
- var scene = this.getScene();
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
- //execute success callback, if set
- if (onSuccess) {
- onSuccess(_this);
- }
- };
- BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
- };
- Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
- || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
- || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
- return;
- }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var position = BABYLON.Vector3.Zero();
- var normal = BABYLON.Vector3.Zero();
- var uv = BABYLON.Vector2.Zero();
- for (var index = 0; index < positions.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(positions, index, position);
- BABYLON.Vector3.FromArrayToRef(normals, index, normal);
- BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
- // Compute height
- var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
- var pos = (u + v * heightMapWidth) * 4;
- var r = buffer[pos] / 255.0;
- var g = buffer[pos + 1] / 255.0;
- var b = buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- normal.normalize();
- normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
- position = position.add(normal);
- position.toArray(positions, index);
- }
- BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
- };
- Mesh.prototype.convertToFlatShadedMesh = function () {
- /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
- /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- var kindIndex;
- var kind;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- if (kind === BABYLON.VertexBuffer.NormalKind) {
- updatableNormals = vertexBuffer.isUpdatable();
- kinds.splice(kindIndex, 1);
- kindIndex--;
- continue;
- }
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating faces & normal
- var normals = [];
- var positions = newdata[BABYLON.VertexBuffer.PositionKind];
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
- var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
- // Store same normals for every vertex
- for (var localIndex = 0; localIndex < 3; localIndex++) {
- normals.push(normal.x);
- normals.push(normal.y);
- normals.push(normal.z);
- }
- }
- this.setIndices(indices);
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- };
- Mesh.prototype.convertToUnIndexedMesh = function () {
- /// <summary>Remove indices by unfolding faces into buffers</summary>
- /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- var kindIndex;
- var kind;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating indices
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- }
- this.setIndices(indices);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this._unIndexed = true;
- this.synchronizeInstances();
- };
- // will inverse faces orientations, and invert normals too if specified
- Mesh.prototype.flipFaces = function (flipNormals) {
- if (flipNormals === void 0) { flipNormals = false; }
- var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
- var i;
- if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- for (i = 0; i < vertex_data.normals.length; i++) {
- vertex_data.normals[i] *= -1;
- }
- }
- var temp;
- for (i = 0; i < vertex_data.indices.length; i += 3) {
- // reassign indices
- temp = vertex_data.indices[i + 1];
- vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
- vertex_data.indices[i + 2] = temp;
- }
- vertex_data.applyToMesh(this);
- };
- // Instances
- Mesh.prototype.createInstance = function (name) {
- return new BABYLON.InstancedMesh(name, this);
- };
- Mesh.prototype.synchronizeInstances = function () {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- };
- /**
- * Simplify the mesh according to the given array of settings.
- * Function will return immediately and will simplify async.
- * @param settings a collection of simplification settings.
- * @param parallelProcessing should all levels calculate parallel or one after the other.
- * @param type the type of simplification to run.
- * @param successCallback optional success callback to be called after the simplification finished processing all settings.
- */
- Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
- if (parallelProcessing === void 0) { parallelProcessing = true; }
- if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
- this.getScene().simplificationQueue.addTask({
- settings: settings,
- parallelProcessing: parallelProcessing,
- mesh: this,
- simplificationType: simplificationType,
- successCallback: successCallback
- });
- };
- /**
- * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
- * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
- * This should be used together with the simplification to avoid disappearing triangles.
- * @param successCallback an optional success callback to be called after the optimization finished.
- */
- Mesh.prototype.optimizeIndices = function (successCallback) {
- var _this = this;
- var indices = this.getIndices();
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var vectorPositions = [];
- for (var pos = 0; pos < positions.length; pos = pos + 3) {
- vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
- }
- var dupes = [];
- BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
- var realPos = vectorPositions.length - 1 - iteration;
- var testedPosition = vectorPositions[realPos];
- for (var j = 0; j < realPos; ++j) {
- var againstPosition = vectorPositions[j];
- if (testedPosition.equals(againstPosition)) {
- dupes[realPos] = j;
- break;
- }
- }
- }, function () {
- for (var i = 0; i < indices.length; ++i) {
- indices[i] = dupes[indices[i]] || indices[i];
- }
- //indices are now reordered
- var originalSubMeshes = _this.subMeshes.slice(0);
- _this.setIndices(indices);
- _this.subMeshes = originalSubMeshes;
- if (successCallback) {
- successCallback(_this);
- }
- });
- };
- // Statics
- Mesh.Parse = function (parsedMesh, scene, rootUrl) {
- var mesh = new Mesh(parsedMesh.name, scene);
- mesh.id = parsedMesh.id;
- BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
- mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
- if (parsedMesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
- }
- else if (parsedMesh.rotation) {
- mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
- }
- mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
- if (parsedMesh.localMatrix) {
- mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
- }
- else if (parsedMesh.pivotMatrix) {
- mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
- }
- mesh.setEnabled(parsedMesh.isEnabled);
- mesh.isVisible = parsedMesh.isVisible;
- mesh.infiniteDistance = parsedMesh.infiniteDistance;
- mesh.showBoundingBox = parsedMesh.showBoundingBox;
- mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
- if (parsedMesh.applyFog !== undefined) {
- mesh.applyFog = parsedMesh.applyFog;
- }
- if (parsedMesh.pickable !== undefined) {
- mesh.isPickable = parsedMesh.pickable;
- }
- if (parsedMesh.alphaIndex !== undefined) {
- mesh.alphaIndex = parsedMesh.alphaIndex;
- }
- mesh.receiveShadows = parsedMesh.receiveShadows;
- mesh.billboardMode = parsedMesh.billboardMode;
- if (parsedMesh.visibility !== undefined) {
- mesh.visibility = parsedMesh.visibility;
- }
- mesh.checkCollisions = parsedMesh.checkCollisions;
- mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
- // freezeWorldMatrix
- if (parsedMesh.freezeWorldMatrix) {
- mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
- }
- // Parent
- if (parsedMesh.parentId) {
- mesh._waitingParentId = parsedMesh.parentId;
- }
- // Actions
- if (parsedMesh.actions !== undefined) {
- mesh._waitingActions = parsedMesh.actions;
- }
- // Geometry
- mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
- if (parsedMesh.delayLoadingFile) {
- mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
- mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
- if (parsedMesh._binaryInfo) {
- mesh._binaryInfo = parsedMesh._binaryInfo;
- }
- mesh._delayInfo = [];
- if (parsedMesh.hasUVs) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
- }
- if (parsedMesh.hasUVs2) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (parsedMesh.hasUVs3) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
- }
- if (parsedMesh.hasUVs4) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
- }
- if (parsedMesh.hasUVs5) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
- }
- if (parsedMesh.hasUVs6) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
- }
- if (parsedMesh.hasColors) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
- }
- if (parsedMesh.hasMatricesIndices) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- if (parsedMesh.hasMatricesWeights) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
- if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
- mesh._checkDelayState();
- }
- }
- else {
- BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
- }
- // Material
- if (parsedMesh.materialId) {
- mesh.setMaterialByID(parsedMesh.materialId);
- }
- else {
- mesh.material = null;
- }
- // Skeleton
- if (parsedMesh.skeletonId > -1) {
- mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
- if (parsedMesh.numBoneInfluencers) {
- mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
- }
- }
- // Physics
- if (parsedMesh.physicsImpostor) {
- if (!scene.isPhysicsEnabled()) {
- scene.enablePhysics();
- }
- mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
- }
- // Animations
- if (parsedMesh.animations) {
- for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- var parsedAnimation = parsedMesh.animations[animationIndex];
- mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
- }
- if (parsedMesh.autoAnimate) {
- scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
- }
- // Layer Mask
- if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
- mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
- }
- else {
- mesh.layerMask = 0x0FFFFFFF;
- }
- // Instances
- if (parsedMesh.instances) {
- for (var index = 0; index < parsedMesh.instances.length; index++) {
- var parsedInstance = parsedMesh.instances[index];
- var instance = mesh.createInstance(parsedInstance.name);
- BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
- instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
- if (parsedInstance.rotationQuaternion) {
- instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
- }
- else if (parsedInstance.rotation) {
- instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
- }
- instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
- instance.checkCollisions = mesh.checkCollisions;
- if (parsedMesh.animations) {
- for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- parsedAnimation = parsedMesh.animations[animationIndex];
- instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
- }
- }
- }
- return mesh;
- };
- Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
- return BABYLON.MeshBuilder.CreateRibbon(name, {
- pathArray: pathArray,
- closeArray: closeArray,
- closePath: closePath,
- offset: offset,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }, scene);
- };
- Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
- var options = {
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
- };
- Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
- var options = {
- size: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateBox(name, options, scene);
- };
- Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
- var options = {
- segments: segments,
- diameterX: diameter,
- diameterY: diameter,
- diameterZ: diameter,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
- };
- // Cylinder and cone
- Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
- if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
- if (scene !== undefined) {
- sideOrientation = updatable || Mesh.DEFAULTSIDE;
- updatable = scene;
- }
- scene = subdivisions;
- subdivisions = 1;
- }
- var options = {
- height: height,
- diameterTop: diameterTop,
- diameterBottom: diameterBottom,
- tessellation: tessellation,
- subdivisions: subdivisions,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
- };
- // Torus (Code from SharpDX.org)
- Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
- var options = {
- diameter: diameter,
- thickness: thickness,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
- };
- Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
- var options = {
- radius: radius,
- tube: tube,
- radialSegments: radialSegments,
- tubularSegments: tubularSegments,
- p: p,
- q: q,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
- };
- // Lines
- Mesh.CreateLines = function (name, points, scene, updatable, instance) {
- var options = {
- points: points,
- updatable: updatable,
- instance: instance
- };
- return BABYLON.MeshBuilder.CreateLines(name, options, scene);
- };
- // Dashed Lines
- Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
- var options = {
- points: points,
- dashSize: dashSize,
- gapSize: gapSize,
- dashNb: dashNb,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
- };
- // Extrusion
- Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- shape: shape,
- path: path,
- scale: scale,
- rotation: rotation,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
- };
- Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- shape: shape,
- path: path,
- scaleFunction: scaleFunction,
- rotationFunction: rotationFunction,
- ribbonCloseArray: ribbonCloseArray,
- ribbonClosePath: ribbonClosePath,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
- };
- // Lathe
- Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
- var options = {
- shape: shape,
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
- };
- // Plane & ground
- Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
- var options = {
- size: size,
- width: size,
- height: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
- };
- Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateGround(name, options, scene);
- };
- Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
- var options = {
- xmin: xmin,
- zmin: zmin,
- xmax: xmax,
- zmax: zmax,
- subdivisions: subdivisions,
- precision: precision,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
- };
- Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- minHeight: minHeight,
- maxHeight: maxHeight,
- updatable: updatable,
- onReady: onReady
- };
- return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
- };
- Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- path: path,
- radius: radius,
- tessellation: tessellation,
- radiusFunction: radiusFunction,
- arc: 1,
- cap: cap,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- };
- return BABYLON.MeshBuilder.CreateTube(name, options, scene);
- };
- Mesh.CreatePolyhedron = function (name, options, scene) {
- return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
- };
- Mesh.CreateIcoSphere = function (name, options, scene) {
- return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
- };
- // Decals
- Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
- var options = {
- position: position,
- normal: normal,
- size: size,
- angle: angle
- };
- return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
- };
- // Skeletons
- /**
- * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- Mesh.prototype.setPositionsForCPUSkinning = function () {
- var source;
- if (!this._sourcePositions) {
- source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- this._sourcePositions = new Float32Array(source);
- if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
- }
- }
- return this._sourcePositions;
- };
- /**
- * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- Mesh.prototype.setNormalsForCPUSkinning = function () {
- var source;
- if (!this._sourceNormals) {
- source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- this._sourceNormals = new Float32Array(source);
- if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
- }
- }
- return this._sourceNormals;
- };
- /**
- * Update the vertex buffers by applying transformation from the bones
- * @param {skeleton} skeleton to apply
- */
- Mesh.prototype.applySkeleton = function (skeleton) {
- if (!this.geometry) {
- return;
- }
- if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
- return;
- }
- this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- return this;
- }
- if (!this._sourcePositions) {
- this.setPositionsForCPUSkinning();
- }
- if (!this._sourceNormals) {
- this.setNormalsForCPUSkinning();
- }
- // positionsData checks for not being Float32Array will only pass at most once
- var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!(positionsData instanceof Float32Array)) {
- positionsData = new Float32Array(positionsData);
- }
- // normalsData checks for not being Float32Array will only pass at most once
- var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- if (!(normalsData instanceof Float32Array)) {
- normalsData = new Float32Array(normalsData);
- }
- var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- var needExtras = this.numBoneInfluencers > 4;
- var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
- var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
- var skeletonMatrices = skeleton.getTransformMatrices(this);
- var tempVector3 = BABYLON.Vector3.Zero();
- var finalMatrix = new BABYLON.Matrix();
- var tempMatrix = new BABYLON.Matrix();
- var matWeightIdx = 0;
- var inf;
- for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
- var weight;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight > 0) {
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- else
- break;
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData[matWeightIdx + inf];
- if (weight > 0) {
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- else
- break;
- }
- }
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(positionsData, index);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(normalsData, index);
- finalMatrix.reset();
- }
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
- return this;
- };
- // Tools
- Mesh.MinMax = function (meshes) {
- var minVector = null;
- var maxVector = null;
- for (var i in meshes) {
- var mesh = meshes[i];
- var boundingBox = mesh.getBoundingInfo().boundingBox;
- if (!minVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- continue;
- }
- minVector.MinimizeInPlace(boundingBox.minimumWorld);
- maxVector.MaximizeInPlace(boundingBox.maximumWorld);
- }
- return {
- min: minVector,
- max: maxVector
- };
- };
- Mesh.Center = function (meshesOrMinMaxVector) {
- var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
- return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
- };
- /**
- * Merge the array of meshes into a single mesh for performance reasons.
- * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
- * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
- * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
- * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
- */
- Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
- if (disposeSource === void 0) { disposeSource = true; }
- var index;
- if (!allow32BitsIndices) {
- var totalVertices = 0;
- // Counting vertices
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- totalVertices += meshes[index].getTotalVertices();
- if (totalVertices > 65536) {
- BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
- return null;
- }
- }
- }
- }
- // Merge
- var vertexData;
- var otherVertexData;
- var source;
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].computeWorldMatrix(true);
- otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
- otherVertexData.transform(meshes[index].getWorldMatrix());
- if (vertexData) {
- vertexData.merge(otherVertexData);
- }
- else {
- vertexData = otherVertexData;
- source = meshes[index];
- }
- }
- }
- if (!meshSubclass) {
- meshSubclass = new Mesh(source.name + "_merged", source.getScene());
- }
- vertexData.applyToMesh(meshSubclass);
- // Setting properties
- meshSubclass.material = source.material;
- meshSubclass.checkCollisions = source.checkCollisions;
- // Cleaning
- if (disposeSource) {
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].dispose();
- }
- }
- }
- return meshSubclass;
- };
- // Consts
- Mesh._FRONTSIDE = 0;
- Mesh._BACKSIDE = 1;
- Mesh._DOUBLESIDE = 2;
- Mesh._DEFAULTSIDE = 0;
- Mesh._NO_CAP = 0;
- Mesh._CAP_START = 1;
- Mesh._CAP_END = 2;
- Mesh._CAP_ALL = 3;
- return Mesh;
- })(BABYLON.AbstractMesh);
- BABYLON.Mesh = Mesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SubMesh = (function () {
- function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
- if (createBoundingBox === void 0) { createBoundingBox = true; }
- this.materialIndex = materialIndex;
- this.verticesStart = verticesStart;
- this.verticesCount = verticesCount;
- this.indexStart = indexStart;
- this.indexCount = indexCount;
- this._renderId = 0;
- this._mesh = mesh;
- this._renderingMesh = renderingMesh || mesh;
- mesh.subMeshes.push(this);
- this._trianglePlanes = [];
- this._id = mesh.subMeshes.length - 1;
- if (createBoundingBox) {
- this.refreshBoundingInfo();
- mesh.computeWorldMatrix(true);
- }
- }
- Object.defineProperty(SubMesh.prototype, "IsGlobal", {
- get: function () {
- return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
- },
- enumerable: true,
- configurable: true
- });
- SubMesh.prototype.getBoundingInfo = function () {
- if (this.IsGlobal) {
- return this._mesh.getBoundingInfo();
- }
- return this._boundingInfo;
- };
- SubMesh.prototype.getMesh = function () {
- return this._mesh;
- };
- SubMesh.prototype.getRenderingMesh = function () {
- return this._renderingMesh;
- };
- SubMesh.prototype.getMaterial = function () {
- var rootMaterial = this._renderingMesh.material;
- if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
- var multiMaterial = rootMaterial;
- return multiMaterial.getSubMaterial(this.materialIndex);
- }
- if (!rootMaterial) {
- return this._mesh.getScene().defaultMaterial;
- }
- return rootMaterial;
- };
- // Methods
- SubMesh.prototype.refreshBoundingInfo = function () {
- if (this.IsGlobal) {
- return;
- }
- var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- this._boundingInfo = this._mesh._boundingInfo;
- return;
- }
- var indices = this._renderingMesh.getIndices();
- var extend;
- //is this the only submesh?
- if (this.indexStart === 0 && this.indexCount === indices.length) {
- //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
- extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
- }
- else {
- extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
- }
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- };
- SubMesh.prototype._checkCollision = function (collider) {
- return this.getBoundingInfo()._checkCollision(collider);
- };
- SubMesh.prototype.updateBoundingInfo = function (world) {
- if (!this.getBoundingInfo()) {
- this.refreshBoundingInfo();
- }
- this.getBoundingInfo().update(world);
- };
- SubMesh.prototype.isInFrustum = function (frustumPlanes) {
- return this.getBoundingInfo().isInFrustum(frustumPlanes);
- };
- SubMesh.prototype.render = function (enableAlphaMode) {
- this._renderingMesh.render(this, enableAlphaMode);
- };
- SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
- if (!this._linesIndexBuffer) {
- var linesIndices = [];
- for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
- linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
- }
- this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
- this.linesIndexCount = linesIndices.length;
- }
- return this._linesIndexBuffer;
- };
- SubMesh.prototype.canIntersects = function (ray) {
- return ray.intersectsBox(this.getBoundingInfo().boundingBox);
- };
- SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
- var intersectInfo = null;
- // Triangles test
- for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
- var p0 = positions[indices[index]];
- var p1 = positions[indices[index + 1]];
- var p2 = positions[indices[index + 2]];
- var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
- if (currentIntersectInfo) {
- if (currentIntersectInfo.distance < 0) {
- continue;
- }
- if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
- intersectInfo = currentIntersectInfo;
- intersectInfo.faceId = index / 3;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- return intersectInfo;
- };
- // Clone
- SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
- var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
- if (!this.IsGlobal) {
- result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
- }
- return result;
- };
- // Dispose
- SubMesh.prototype.dispose = function () {
- if (this._linesIndexBuffer) {
- this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
- this._linesIndexBuffer = null;
- }
- // Remove from mesh
- var index = this._mesh.subMeshes.indexOf(this);
- this._mesh.subMeshes.splice(index, 1);
- };
- // Statics
- SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
- var minVertexIndex = Number.MAX_VALUE;
- var maxVertexIndex = -Number.MAX_VALUE;
- renderingMesh = renderingMesh || mesh;
- var indices = renderingMesh.getIndices();
- for (var index = startIndex; index < startIndex + indexCount; index++) {
- var vertexIndex = indices[index];
- if (vertexIndex < minVertexIndex)
- minVertexIndex = vertexIndex;
- if (vertexIndex > maxVertexIndex)
- maxVertexIndex = vertexIndex;
- }
- return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
- };
- return SubMesh;
- })();
- BABYLON.SubMesh = SubMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MeshBuilder = (function () {
- function MeshBuilder() {
- }
- MeshBuilder.CreateBox = function (name, options, scene) {
- var box = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateBox(options);
- vertexData.applyToMesh(box, options.updatable);
- return box;
- };
- MeshBuilder.CreateSphere = function (name, options, scene) {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateSphere(options);
- vertexData.applyToMesh(sphere, options.updatable);
- return sphere;
- };
- MeshBuilder.CreateDisc = function (name, options, scene) {
- var disc = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateDisc(options);
- vertexData.applyToMesh(disc, options.updatable);
- return disc;
- };
- MeshBuilder.CreateIcoSphere = function (name, options, scene) {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
- vertexData.applyToMesh(sphere, options.updatable);
- return sphere;
- };
- ;
- MeshBuilder.CreateRibbon = function (name, options, scene) {
- var pathArray = options.pathArray;
- var closeArray = options.closeArray;
- var closePath = options.closePath;
- var offset = options.offset;
- var sideOrientation = options.sideOrientation;
- var instance = options.instance;
- var updatable = options.updatable;
- if (instance) {
- // positionFunction : ribbon case
- // only pathArray and sideOrientation parameters are taken into account for positions update
- var positionFunction = function (positions) {
- var minlg = pathArray[0].length;
- var i = 0;
- var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
- for (var si = 1; si <= ns; si++) {
- for (var p = 0; p < pathArray.length; p++) {
- var path = pathArray[p];
- var l = path.length;
- minlg = (minlg < l) ? minlg : l;
- var j = 0;
- while (j < minlg) {
- positions[i] = path[j].x;
- positions[i + 1] = path[j].y;
- positions[i + 2] = path[j].z;
- j++;
- i += 3;
- }
- if (instance._closePath) {
- positions[i] = path[0].x;
- positions[i + 1] = path[0].y;
- positions[i + 2] = path[0].z;
- i += 3;
- }
- }
- }
- };
- var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- positionFunction(positions);
- instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
- if (!(instance.areNormalsFrozen)) {
- var indices = instance.getIndices();
- var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- if (instance._closePath) {
- var indexFirst = 0;
- var indexLast = 0;
- for (var p = 0; p < pathArray.length; p++) {
- indexFirst = instance._idx[p] * 3;
- if (p + 1 < pathArray.length) {
- indexLast = (instance._idx[p + 1] - 1) * 3;
- }
- else {
- indexLast = normals.length - 3;
- }
- normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
- normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
- normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
- normals[indexLast] = normals[indexFirst];
- normals[indexLast + 1] = normals[indexFirst + 1];
- normals[indexLast + 2] = normals[indexFirst + 2];
- }
- }
- instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
- }
- return instance;
- }
- else {
- var ribbon = new BABYLON.Mesh(name, scene);
- ribbon.sideOrientation = sideOrientation;
- var vertexData = BABYLON.VertexData.CreateRibbon(options);
- if (closePath) {
- ribbon._idx = vertexData._idx;
- }
- ribbon._closePath = closePath;
- ribbon._closeArray = closeArray;
- vertexData.applyToMesh(ribbon, updatable);
- return ribbon;
- }
- };
- MeshBuilder.CreateCylinder = function (name, options, scene) {
- var cylinder = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateCylinder(options);
- vertexData.applyToMesh(cylinder, options.updatable);
- return cylinder;
- };
- MeshBuilder.CreateTorus = function (name, options, scene) {
- var torus = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorus(options);
- vertexData.applyToMesh(torus, options.updatable);
- return torus;
- };
- MeshBuilder.CreateTorusKnot = function (name, options, scene) {
- var torusKnot = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
- vertexData.applyToMesh(torusKnot, options.updatable);
- return torusKnot;
- };
- MeshBuilder.CreateLines = function (name, options, scene) {
- var instance = options.instance;
- var points = options.points;
- if (instance) {
- var positionFunction = function (positions) {
- var i = 0;
- for (var p = 0; p < points.length; p++) {
- positions[i] = points[p].x;
- positions[i + 1] = points[p].y;
- positions[i + 2] = points[p].z;
- i += 3;
- }
- };
- instance.updateMeshPositions(positionFunction, false);
- return instance;
- }
- // lines creation
- var lines = new BABYLON.LinesMesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateLines(options);
- vertexData.applyToMesh(lines, options.updatable);
- return lines;
- };
- MeshBuilder.CreateDashedLines = function (name, options, scene) {
- var points = options.points;
- var instance = options.instance;
- var gapSize = options.gapSize;
- var dashNb = options.dashNb;
- var dashSize = options.dashSize;
- if (instance) {
- var positionFunction = function (positions) {
- var curvect = BABYLON.Vector3.Zero();
- var nbSeg = positions.length / 6;
- var lg = 0;
- var nb = 0;
- var shft = 0;
- var dashshft = 0;
- var curshft = 0;
- var p = 0;
- var i = 0;
- var j = 0;
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- lg += curvect.length();
- }
- shft = lg / nbSeg;
- dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- nb = Math.floor(curvect.length() / shft);
- curvect.normalize();
- j = 0;
- while (j < nb && p < positions.length) {
- curshft = shft * j;
- positions[p] = points[i].x + curshft * curvect.x;
- positions[p + 1] = points[i].y + curshft * curvect.y;
- positions[p + 2] = points[i].z + curshft * curvect.z;
- positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
- positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
- positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
- p += 6;
- j++;
- }
- }
- while (p < positions.length) {
- positions[p] = points[i].x;
- positions[p + 1] = points[i].y;
- positions[p + 2] = points[i].z;
- p += 3;
- }
- };
- instance.updateMeshPositions(positionFunction, false);
- return instance;
- }
- // dashed lines creation
- var dashedLines = new BABYLON.LinesMesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateDashedLines(options);
- vertexData.applyToMesh(dashedLines, options.updatable);
- dashedLines.dashSize = dashSize;
- dashedLines.gapSize = gapSize;
- return dashedLines;
- };
- MeshBuilder.ExtrudeShape = function (name, options, scene) {
- var path = options.path;
- var shape = options.shape;
- var scale = options.scale || 1;
- var rotation = options.rotation || 0;
- var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
- };
- MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
- var path = options.path;
- var shape = options.shape;
- var scaleFunction = options.scaleFunction || (function () { return 1; });
- var rotationFunction = options.rotationFunction || (function () { return 0; });
- var ribbonCloseArray = options.ribbonCloseArray || false;
- var ribbonClosePath = options.ribbonClosePath || false;
- var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
- };
- MeshBuilder.CreateLathe = function (name, options, scene) {
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var closed = (options.closed === undefined) ? true : options.closed;
- var shape = options.shape;
- var radius = options.radius || 1;
- var tessellation = options.tessellation || 64;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var cap = options.cap || BABYLON.Mesh.NO_CAP;
- var pi2 = Math.PI * 2;
- var paths = new Array();
- var i = 0;
- var p = 0;
- var step = pi2 / tessellation * arc;
- var rotated;
- var path = new Array();
- ;
- for (i = 0; i <= tessellation; i++) {
- var path = [];
- if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
- path.push(new BABYLON.Vector3(0, shape[0].y, 0));
- path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
- }
- for (p = 0; p < shape.length; p++) {
- rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
- path.push(rotated);
- }
- if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
- 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));
- path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
- }
- paths.push(path);
- }
- // lathe ribbon
- var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
- return lathe;
- };
- MeshBuilder.CreatePlane = function (name, options, scene) {
- var plane = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePlane(options);
- vertexData.applyToMesh(plane, options.updatable);
- if (options.sourcePlane) {
- plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
- var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
- var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
- plane.rotate(vectorProduct, product);
- }
- return plane;
- };
- MeshBuilder.CreateGround = function (name, options, scene) {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._setReady(false);
- ground._subdivisions = options.subdivisions || 1;
- ground._width = options.width || 1;
- ground._height = options.height || 1;
- ground._maxX = ground._width / 2;
- ground._maxZ = ground._height / 2;
- ground._minX = -ground._maxX;
- ground._minZ = -ground._maxZ;
- var vertexData = BABYLON.VertexData.CreateGround(options);
- vertexData.applyToMesh(ground, options.updatable);
- ground._setReady(true);
- return ground;
- };
- MeshBuilder.CreateTiledGround = function (name, options, scene) {
- var tiledGround = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTiledGround(options);
- vertexData.applyToMesh(tiledGround, options.updatable);
- return tiledGround;
- };
- MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
- var width = options.width || 10;
- var height = options.height || 10;
- var subdivisions = options.subdivisions || 1;
- var minHeight = options.minHeight;
- var maxHeight = options.maxHeight || 10;
- var updatable = options.updatable;
- var onReady = options.onReady;
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._subdivisions = subdivisions;
- ground._width = width;
- ground._height = height;
- ground._maxX = ground._width / 2;
- ground._maxZ = ground._height / 2;
- ground._minX = -ground._maxX;
- ground._minZ = -ground._maxZ;
- ground._setReady(false);
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var bufferWidth = img.width;
- var bufferHeight = img.height;
- canvas.width = bufferWidth;
- canvas.height = bufferHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
- var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
- width: width, height: height,
- subdivisions: subdivisions,
- minHeight: minHeight, maxHeight: maxHeight,
- buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
- });
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- //execute ready callback, if set
- if (onReady) {
- onReady(ground);
- }
- };
- BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
- return ground;
- };
- MeshBuilder.CreateTube = function (name, options, scene) {
- var path = options.path;
- var radius = options.radius || 1;
- var tessellation = options.tessellation || 64;
- var radiusFunction = options.radiusFunction;
- var cap = options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
- // tube geometry
- var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
- var tangents = path3D.getTangents();
- var normals = path3D.getNormals();
- var distances = path3D.getDistances();
- var pi2 = Math.PI * 2;
- var step = pi2 / tessellation * arc;
- var returnRadius = function () { return radius; };
- var radiusFunctionFinal = radiusFunction || returnRadius;
- var circlePath;
- var rad;
- var normal;
- var rotated;
- var rotationMatrix = BABYLON.Tmp.Matrix[0];
- var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
- for (var i = 0; i < path.length; i++) {
- rad = radiusFunctionFinal(i, distances[i]); // current radius
- circlePath = Array(); // current circle array
- normal = normals[i]; // current normal
- for (var t = 0; t < tessellation; t++) {
- BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
- rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
- BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
- rotated.scaleInPlace(rad).addInPlace(path[i]);
- circlePath[t] = rotated;
- }
- circlePaths[index] = circlePath;
- index++;
- }
- // cap
- var capPath = function (nbPoints, pathIndex) {
- var pointCap = Array();
- for (var i = 0; i < nbPoints; i++) {
- pointCap.push(path[pathIndex]);
- }
- return pointCap;
- };
- switch (cap) {
- case BABYLON.Mesh.NO_CAP:
- break;
- case BABYLON.Mesh.CAP_START:
- circlePaths[0] = capPath(tessellation, 0);
- circlePaths[1] = circlePaths[2].slice(0);
- break;
- case BABYLON.Mesh.CAP_END:
- circlePaths[index] = circlePaths[index - 1].slice(0);
- circlePaths[index + 1] = capPath(tessellation, path.length - 1);
- break;
- case BABYLON.Mesh.CAP_ALL:
- circlePaths[0] = capPath(tessellation, 0);
- circlePaths[1] = circlePaths[2].slice(0);
- circlePaths[index] = circlePaths[index - 1].slice(0);
- circlePaths[index + 1] = capPath(tessellation, path.length - 1);
- break;
- default:
- break;
- }
- return circlePaths;
- };
- var path3D;
- var pathArray;
- if (instance) {
- var arc = options.arc || instance.arc;
- path3D = (instance.path3D).update(path);
- pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
- instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
- instance.path3D = path3D;
- instance.pathArray = pathArray;
- instance.arc = arc;
- return instance;
- }
- // tube creation
- path3D = new BABYLON.Path3D(path);
- var newPathArray = new Array();
- cap = (cap < 0 || cap > 3) ? 0 : cap;
- pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
- var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
- tube.pathArray = pathArray;
- tube.path3D = path3D;
- tube.tessellation = tessellation;
- tube.cap = cap;
- tube.arc = options.arc;
- return tube;
- };
- MeshBuilder.CreatePolyhedron = function (name, options, scene) {
- var polyhedron = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
- vertexData.applyToMesh(polyhedron, options.updatable);
- return polyhedron;
- };
- MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
- var indices = sourceMesh.getIndices();
- var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var position = options.position || BABYLON.Vector3.Zero();
- var normal = options.normal || BABYLON.Vector3.Up();
- var size = options.size || new BABYLON.Vector3(1, 1, 1);
- var angle = options.angle || 0;
- // Getting correct rotation
- if (!normal) {
- var target = new BABYLON.Vector3(0, 0, 1);
- var camera = sourceMesh.getScene().activeCamera;
- var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
- normal = camera.globalPosition.subtract(cameraWorldTarget);
- }
- var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
- var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
- var pitch = Math.atan2(normal.y, len);
- // Matrix
- var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
- var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
- var meshWorldMatrix = sourceMesh.getWorldMatrix();
- var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = [];
- vertexData.positions = [];
- vertexData.normals = [];
- vertexData.uvs = [];
- var currentVertexDataIndex = 0;
- var extractDecalVector3 = function (indexId) {
- var vertexId = indices[indexId];
- var result = new BABYLON.PositionNormalVertex();
- result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
- // Send vector to decal local world
- result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
- // Get normal
- result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
- return result;
- }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
- var clip = function (vertices, axis) {
- if (vertices.length === 0) {
- return vertices;
- }
- var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
- var clipVertices = function (v0, v1) {
- var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
- return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
- };
- var result = new Array();
- for (var index = 0; index < vertices.length; index += 3) {
- var v1Out;
- var v2Out;
- var v3Out;
- var total = 0;
- var nV1, nV2, nV3, nV4;
- var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
- var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
- var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
- v1Out = d1 > 0;
- v2Out = d2 > 0;
- v3Out = d3 > 0;
- total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
- switch (total) {
- case 0:
- result.push(vertices[index]);
- result.push(vertices[index + 1]);
- result.push(vertices[index + 2]);
- break;
- case 1:
- if (v1Out) {
- nV1 = vertices[index + 1];
- nV2 = vertices[index + 2];
- nV3 = clipVertices(vertices[index], nV1);
- nV4 = clipVertices(vertices[index], nV2);
- }
- if (v2Out) {
- nV1 = vertices[index];
- nV2 = vertices[index + 2];
- nV3 = clipVertices(vertices[index + 1], nV1);
- nV4 = clipVertices(vertices[index + 1], nV2);
- result.push(nV3);
- result.push(nV2.clone());
- result.push(nV1.clone());
- result.push(nV2.clone());
- result.push(nV3.clone());
- result.push(nV4);
- break;
- }
- if (v3Out) {
- nV1 = vertices[index];
- nV2 = vertices[index + 1];
- nV3 = clipVertices(vertices[index + 2], nV1);
- nV4 = clipVertices(vertices[index + 2], nV2);
- }
- result.push(nV1.clone());
- result.push(nV2.clone());
- result.push(nV3);
- result.push(nV4);
- result.push(nV3.clone());
- result.push(nV2.clone());
- break;
- case 2:
- if (!v1Out) {
- nV1 = vertices[index].clone();
- nV2 = clipVertices(nV1, vertices[index + 1]);
- nV3 = clipVertices(nV1, vertices[index + 2]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- if (!v2Out) {
- nV1 = vertices[index + 1].clone();
- nV2 = clipVertices(nV1, vertices[index + 2]);
- nV3 = clipVertices(nV1, vertices[index]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- if (!v3Out) {
- nV1 = vertices[index + 2].clone();
- nV2 = clipVertices(nV1, vertices[index]);
- nV3 = clipVertices(nV1, vertices[index + 1]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- break;
- case 3:
- break;
- }
- }
- return result;
- };
- for (var index = 0; index < indices.length; index += 3) {
- var faceVertices = new Array();
- faceVertices.push(extractDecalVector3(index));
- faceVertices.push(extractDecalVector3(index + 1));
- faceVertices.push(extractDecalVector3(index + 2));
- // Clip
- faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
- if (faceVertices.length === 0) {
- continue;
- }
- // Add UVs and get back to world
- for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
- var vertex = faceVertices[vIndex];
- //TODO check for Int32Array
- vertexData.indices.push(currentVertexDataIndex);
- vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
- vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
- vertexData.uvs.push(0.5 + vertex.position.x / size.x);
- vertexData.uvs.push(0.5 + vertex.position.y / size.y);
- currentVertexDataIndex++;
- }
- }
- // Return mesh
- var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
- vertexData.applyToMesh(decal);
- decal.position = position.clone();
- decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
- return decal;
- };
- // Privates
- MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
- // extrusion geometry
- var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
- var tangents = path3D.getTangents();
- var normals = path3D.getNormals();
- var binormals = path3D.getBinormals();
- var distances = path3D.getDistances();
- var angle = 0;
- var returnScale = function () { return scale; };
- var returnRotation = function () { return rotation; };
- var rotate = custom ? rotateFunction : returnRotation;
- var scl = custom ? scaleFunction : returnScale;
- var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
- var rotationMatrix = BABYLON.Tmp.Matrix[0];
- for (var i = 0; i < curve.length; i++) {
- var shapePath = new Array();
- var angleStep = rotate(i, distances[i]);
- var scaleRatio = scl(i, distances[i]);
- for (var p = 0; p < shape.length; p++) {
- BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
- var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
- var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
- BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
- rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
- shapePath[p] = rotated;
- }
- shapePaths[index] = shapePath;
- angle += angleStep;
- index++;
- }
- // cap
- var capPath = function (shapePath) {
- var pointCap = Array();
- var barycenter = BABYLON.Vector3.Zero();
- var i;
- for (i = 0; i < shapePath.length; i++) {
- barycenter.addInPlace(shapePath[i]);
- }
- barycenter.scaleInPlace(1 / shapePath.length);
- for (i = 0; i < shapePath.length; i++) {
- pointCap.push(barycenter);
- }
- return pointCap;
- };
- switch (cap) {
- case BABYLON.Mesh.NO_CAP:
- break;
- case BABYLON.Mesh.CAP_START:
- shapePaths[0] = capPath(shapePaths[2]);
- shapePaths[1] = shapePaths[2].slice(0);
- break;
- case BABYLON.Mesh.CAP_END:
- shapePaths[index] = shapePaths[index - 1];
- shapePaths[index + 1] = capPath(shapePaths[index - 1]);
- break;
- case BABYLON.Mesh.CAP_ALL:
- shapePaths[0] = capPath(shapePaths[2]);
- shapePaths[1] = shapePaths[2].slice(0);
- shapePaths[index] = shapePaths[index - 1];
- shapePaths[index + 1] = capPath(shapePaths[index - 1]);
- break;
- default:
- break;
- }
- return shapePaths;
- };
- var path3D;
- var pathArray;
- if (instance) {
- path3D = (instance.path3D).update(curve);
- pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
- instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
- return instance;
- }
- // extruded shape creation
- path3D = new BABYLON.Path3D(curve);
- var newShapePaths = new Array();
- cap = (cap < 0 || cap > 3) ? 0 : cap;
- pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
- var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
- extrudedGeneric.pathArray = pathArray;
- extrudedGeneric.path3D = path3D;
- extrudedGeneric.cap = cap;
- return extrudedGeneric;
- };
- return MeshBuilder;
- })();
- BABYLON.MeshBuilder = MeshBuilder;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BaseTexture = (function () {
- function BaseTexture(scene) {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.hasAlpha = false;
- this.getAlphaFromRGB = false;
- this.level = 1;
- this.isCube = false;
- this.isRenderTarget = false;
- this.animations = new Array();
- this.coordinatesIndex = 0;
- this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
- this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.anisotropicFilteringLevel = 4;
- this._scene = scene;
- this._scene.textures.push(this);
- }
- BaseTexture.prototype.getScene = function () {
- return this._scene;
- };
- BaseTexture.prototype.getTextureMatrix = function () {
- return null;
- };
- BaseTexture.prototype.getReflectionTextureMatrix = function () {
- return null;
- };
- BaseTexture.prototype.getInternalTexture = function () {
- return this._texture;
- };
- BaseTexture.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return true;
- }
- if (this._texture) {
- return this._texture.isReady;
- }
- return false;
- };
- BaseTexture.prototype.getSize = function () {
- if (this._texture._width) {
- return { width: this._texture._width, height: this._texture._height };
- }
- if (this._texture._size) {
- return { width: this._texture._size, height: this._texture._size };
- }
- return { width: 0, height: 0 };
- };
- BaseTexture.prototype.getBaseSize = function () {
- if (!this.isReady())
- return { width: 0, height: 0 };
- if (this._texture._size) {
- return { width: this._texture._size, height: this._texture._size };
- }
- return { width: this._texture._baseWidth, height: this._texture._baseHeight };
- };
- BaseTexture.prototype.scale = function (ratio) {
- };
- Object.defineProperty(BaseTexture.prototype, "canRescale", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
- var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
- for (var index = 0; index < texturesCache.length; index++) {
- var texturesCacheEntry = texturesCache[index];
- if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
- texturesCache.splice(index, 1);
- return;
- }
- }
- };
- BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
- var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
- for (var index = 0; index < texturesCache.length; index++) {
- var texturesCacheEntry = texturesCache[index];
- if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
- if (!sampling || sampling === texturesCacheEntry.samplingMode) {
- texturesCacheEntry.references++;
- return texturesCacheEntry;
- }
- }
- }
- return null;
- };
- BaseTexture.prototype.delayLoad = function () {
- };
- BaseTexture.prototype.clone = function () {
- return null;
- };
- BaseTexture.prototype.releaseInternalTexture = function () {
- if (this._texture) {
- this._scene.getEngine().releaseInternalTexture(this._texture);
- delete this._texture;
- }
- };
- BaseTexture.prototype.dispose = function () {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- var index = this._scene.textures.indexOf(this);
- if (index >= 0) {
- this._scene.textures.splice(index, 1);
- }
- if (this._texture === undefined) {
- return;
- }
- // Release
- this.releaseInternalTexture();
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- BaseTexture.prototype.serialize = function () {
- var serializationObject = {};
- if (!this.name) {
- return null;
- }
- serializationObject.name = this.name;
- serializationObject.hasAlpha = this.hasAlpha;
- serializationObject.level = this.level;
- serializationObject.coordinatesIndex = this.coordinatesIndex;
- serializationObject.coordinatesMode = this.coordinatesMode;
- serializationObject.wrapU = this.wrapU;
- serializationObject.wrapV = this.wrapV;
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- return serializationObject;
- };
- return BaseTexture;
- })();
- BABYLON.BaseTexture = BaseTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Texture = (function (_super) {
- __extends(Texture, _super);
- function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (buffer === void 0) { buffer = null; }
- if (deleteBuffer === void 0) { deleteBuffer = false; }
- _super.call(this, scene);
- this.uOffset = 0;
- this.vOffset = 0;
- this.uScale = 1.0;
- this.vScale = 1.0;
- this.uAng = 0;
- this.vAng = 0;
- this.wAng = 0;
- this.name = url;
- this.url = url;
- this._noMipmap = noMipmap;
- this._invertY = invertY;
- this._samplingMode = samplingMode;
- this._buffer = buffer;
- this._deleteBuffer = deleteBuffer;
- if (!url) {
- return;
- }
- this._texture = this._getFromCache(url, noMipmap, samplingMode);
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
- if (deleteBuffer) {
- delete this._buffer;
- }
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- else {
- BABYLON.Tools.SetImmediate(function () {
- if (onLoad) {
- onLoad();
- }
- });
- }
- }
- Texture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
- if (!this._texture) {
- this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
- if (this._deleteBuffer) {
- delete this._buffer;
- }
- }
- };
- Texture.prototype.updateSamplingMode = function (samplingMode) {
- if (!this._texture) {
- return;
- }
- this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
- };
- Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
- x *= this.uScale;
- y *= this.vScale;
- x -= 0.5 * this.uScale;
- y -= 0.5 * this.vScale;
- z -= 0.5;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
- t.x += 0.5 * this.uScale + this.uOffset;
- t.y += 0.5 * this.vScale + this.vOffset;
- t.z += 0.5;
- };
- Texture.prototype.getTextureMatrix = function () {
- if (this.uOffset === this._cachedUOffset &&
- this.vOffset === this._cachedVOffset &&
- this.uScale === this._cachedUScale &&
- this.vScale === this._cachedVScale &&
- this.uAng === this._cachedUAng &&
- this.vAng === this._cachedVAng &&
- this.wAng === this._cachedWAng) {
- return this._cachedTextureMatrix;
- }
- this._cachedUOffset = this.uOffset;
- this._cachedVOffset = this.vOffset;
- this._cachedUScale = this.uScale;
- this._cachedVScale = this.vScale;
- this._cachedUAng = this.uAng;
- this._cachedVAng = this.vAng;
- this._cachedWAng = this.wAng;
- if (!this._cachedTextureMatrix) {
- this._cachedTextureMatrix = BABYLON.Matrix.Zero();
- this._rowGenerationMatrix = new BABYLON.Matrix();
- this._t0 = BABYLON.Vector3.Zero();
- this._t1 = BABYLON.Vector3.Zero();
- this._t2 = BABYLON.Vector3.Zero();
- }
- BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
- this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
- this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
- this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
- this._t1.subtractInPlace(this._t0);
- this._t2.subtractInPlace(this._t0);
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- this._cachedTextureMatrix.m[0] = this._t1.x;
- this._cachedTextureMatrix.m[1] = this._t1.y;
- this._cachedTextureMatrix.m[2] = this._t1.z;
- this._cachedTextureMatrix.m[4] = this._t2.x;
- this._cachedTextureMatrix.m[5] = this._t2.y;
- this._cachedTextureMatrix.m[6] = this._t2.z;
- this._cachedTextureMatrix.m[8] = this._t0.x;
- this._cachedTextureMatrix.m[9] = this._t0.y;
- this._cachedTextureMatrix.m[10] = this._t0.z;
- return this._cachedTextureMatrix;
- };
- Texture.prototype.getReflectionTextureMatrix = function () {
- if (this.uOffset === this._cachedUOffset &&
- this.vOffset === this._cachedVOffset &&
- this.uScale === this._cachedUScale &&
- this.vScale === this._cachedVScale &&
- this.coordinatesMode === this._cachedCoordinatesMode) {
- return this._cachedTextureMatrix;
- }
- if (!this._cachedTextureMatrix) {
- this._cachedTextureMatrix = BABYLON.Matrix.Zero();
- this._projectionModeMatrix = BABYLON.Matrix.Zero();
- }
- this._cachedCoordinatesMode = this.coordinatesMode;
- switch (this.coordinatesMode) {
- case Texture.PLANAR_MODE:
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- this._cachedTextureMatrix[0] = this.uScale;
- this._cachedTextureMatrix[5] = this.vScale;
- this._cachedTextureMatrix[12] = this.uOffset;
- this._cachedTextureMatrix[13] = this.vOffset;
- break;
- case Texture.PROJECTION_MODE:
- BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
- this._projectionModeMatrix.m[0] = 0.5;
- this._projectionModeMatrix.m[5] = -0.5;
- this._projectionModeMatrix.m[10] = 0.0;
- this._projectionModeMatrix.m[12] = 0.5;
- this._projectionModeMatrix.m[13] = 0.5;
- this._projectionModeMatrix.m[14] = 1.0;
- this._projectionModeMatrix.m[15] = 1.0;
- this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
- break;
- default:
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- break;
- }
- return this._cachedTextureMatrix;
- };
- Texture.prototype.clone = function () {
- var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- newTexture.coordinatesIndex = this.coordinatesIndex;
- newTexture.coordinatesMode = this.coordinatesMode;
- // Texture
- newTexture.uOffset = this.uOffset;
- newTexture.vOffset = this.vOffset;
- newTexture.uScale = this.uScale;
- newTexture.vScale = this.vScale;
- newTexture.uAng = this.uAng;
- newTexture.vAng = this.vAng;
- newTexture.wAng = this.wAng;
- return newTexture;
- };
- Texture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.uOffset = this.uOffset;
- serializationObject.vOffset = this.vOffset;
- serializationObject.uScale = this.uScale;
- serializationObject.vScale = this.vScale;
- serializationObject.uAng = this.uAng;
- serializationObject.vAng = this.vAng;
- serializationObject.wAng = this.wAng;
- return serializationObject;
- };
- // Statics
- Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
- };
- Texture.Parse = function (parsedTexture, scene, rootUrl) {
- if (parsedTexture.isCube) {
- return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
- }
- if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
- return null;
- }
- var texture;
- if (parsedTexture.mirrorPlane) {
- texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
- texture._waitingRenderList = parsedTexture.renderList;
- texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
- }
- else if (parsedTexture.isRenderTarget) {
- texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
- texture._waitingRenderList = parsedTexture.renderList;
- }
- else {
- if (parsedTexture.base64String) {
- texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
- }
- else {
- texture = new Texture(rootUrl + parsedTexture.name, scene);
- }
- }
- texture.name = parsedTexture.name;
- texture.hasAlpha = parsedTexture.hasAlpha;
- texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
- texture.level = parsedTexture.level;
- texture.coordinatesIndex = parsedTexture.coordinatesIndex;
- texture.coordinatesMode = parsedTexture.coordinatesMode;
- texture.uOffset = parsedTexture.uOffset;
- texture.vOffset = parsedTexture.vOffset;
- texture.uScale = parsedTexture.uScale;
- texture.vScale = parsedTexture.vScale;
- texture.uAng = parsedTexture.uAng;
- texture.vAng = parsedTexture.vAng;
- texture.wAng = parsedTexture.wAng;
- texture.wrapU = parsedTexture.wrapU;
- texture.wrapV = parsedTexture.wrapV;
- // Animations
- if (parsedTexture.animations) {
- for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
- var parsedAnimation = parsedTexture.animations[animationIndex];
- texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- return texture;
- };
- // Constants
- Texture.NEAREST_SAMPLINGMODE = 1;
- Texture.BILINEAR_SAMPLINGMODE = 2;
- Texture.TRILINEAR_SAMPLINGMODE = 3;
- Texture.EXPLICIT_MODE = 0;
- Texture.SPHERICAL_MODE = 1;
- Texture.PLANAR_MODE = 2;
- Texture.CUBIC_MODE = 3;
- Texture.PROJECTION_MODE = 4;
- Texture.SKYBOX_MODE = 5;
- Texture.INVCUBIC_MODE = 6;
- Texture.EQUIRECTANGULAR_MODE = 7;
- Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
- Texture.CLAMP_ADDRESSMODE = 0;
- Texture.WRAP_ADDRESSMODE = 1;
- Texture.MIRROR_ADDRESSMODE = 2;
- return Texture;
- })(BABYLON.BaseTexture);
- BABYLON.Texture = Texture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CubeTexture = (function (_super) {
- __extends(CubeTexture, _super);
- function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
- _super.call(this, scene);
- this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
- this.name = rootUrl;
- this.url = rootUrl;
- this._noMipmap = noMipmap;
- this.hasAlpha = false;
- if (!rootUrl && !files) {
- return;
- }
- this._texture = this._getFromCache(rootUrl, noMipmap);
- if (!files) {
- if (!extensions) {
- extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
- }
- files = [];
- for (var index = 0; index < extensions.length; index++) {
- files.push(rootUrl + extensions[index]);
- }
- this._extensions = extensions;
- }
- this._files = files;
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- this.isCube = true;
- this._textureMatrix = BABYLON.Matrix.Identity();
- }
- CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
- return new CubeTexture("", scene, null, noMipmap, files);
- };
- CubeTexture.prototype.clone = function () {
- var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
- // Base texture
- newTexture.level = this.level;
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- newTexture.coordinatesIndex = this.coordinatesIndex;
- newTexture.coordinatesMode = this.coordinatesMode;
- return newTexture;
- };
- // Methods
- CubeTexture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap);
- if (!this._texture) {
- this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
- }
- };
- CubeTexture.prototype.getReflectionTextureMatrix = function () {
- return this._textureMatrix;
- };
- CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
- var texture = null;
- if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
- texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
- texture.name = parsedTexture.name;
- texture.hasAlpha = parsedTexture.hasAlpha;
- texture.level = parsedTexture.level;
- texture.coordinatesMode = parsedTexture.coordinatesMode;
- }
- return texture;
- };
- CubeTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.hasAlpha = this.hasAlpha;
- serializationObject.isCube = true;
- serializationObject.level = this.level;
- serializationObject.coordinatesMode = this.coordinatesMode;
- return serializationObject;
- };
- return CubeTexture;
- })(BABYLON.BaseTexture);
- BABYLON.CubeTexture = CubeTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderTargetTexture = (function (_super) {
- __extends(RenderTargetTexture, _super);
- function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
- if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
- if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- if (isCube === void 0) { isCube = false; }
- _super.call(this, null, scene, !generateMipMaps);
- this.isCube = isCube;
- this.renderList = new Array();
- this.renderParticles = true;
- this.renderSprites = false;
- this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
- this._currentRefreshId = -1;
- this._refreshRate = 1;
- this.name = name;
- this.isRenderTarget = true;
- this._size = size;
- this._generateMipMaps = generateMipMaps;
- this._doNotChangeAspectRatio = doNotChangeAspectRatio;
- if (isCube) {
- this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
- this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
- this._textureMatrix = BABYLON.Matrix.Identity();
- }
- else {
- this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
- }
- // Rendering groups
- this._renderingManager = new BABYLON.RenderingManager(scene);
- }
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype.resetRefreshCounter = function () {
- this._currentRefreshId = -1;
- };
- Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
- get: function () {
- return this._refreshRate;
- },
- // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
- set: function (value) {
- this._refreshRate = value;
- this.resetRefreshCounter();
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype._shouldRender = function () {
- if (this._currentRefreshId === -1) {
- this._currentRefreshId = 1;
- return true;
- }
- if (this.refreshRate === this._currentRefreshId) {
- this._currentRefreshId = 1;
- return true;
- }
- this._currentRefreshId++;
- return false;
- };
- RenderTargetTexture.prototype.isReady = function () {
- if (!this.getScene().renderTargetsEnabled) {
- return false;
- }
- return _super.prototype.isReady.call(this);
- };
- RenderTargetTexture.prototype.getRenderSize = function () {
- return this._size;
- };
- Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype.scale = function (ratio) {
- var newSize = this._size * ratio;
- this.resize(newSize, this._generateMipMaps);
- };
- RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
- if (this.isCube) {
- return this._textureMatrix;
- }
- return _super.prototype.getReflectionTextureMatrix.call(this);
- };
- RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
- this.releaseInternalTexture();
- if (this.isCube) {
- this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
- }
- else {
- this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
- }
- };
- RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
- var scene = this.getScene();
- if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
- scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
- }
- if (this._waitingRenderList) {
- this.renderList = [];
- for (var index = 0; index < this._waitingRenderList.length; index++) {
- var id = this._waitingRenderList[index];
- this.renderList.push(scene.getMeshByID(id));
- }
- delete this._waitingRenderList;
- }
- if (this.renderList && this.renderList.length === 0) {
- return;
- }
- // Prepare renderingManager
- this._renderingManager.reset();
- var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
- for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
- var mesh = currentRenderList[meshIndex];
- if (mesh) {
- if (!mesh.isReady()) {
- // Reset _currentRefreshId
- this.resetRefreshCounter();
- continue;
- }
- if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
- mesh._activate(scene.getRenderId());
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- scene._activeIndices += subMesh.indexCount;
- this._renderingManager.dispatch(subMesh);
- }
- }
- }
- }
- if (this.isCube) {
- for (var face = 0; face < 6; face++) {
- this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
- scene.incrementRenderId();
- }
- }
- else {
- this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
- }
- if (this.onAfterUnbind) {
- this.onAfterUnbind();
- }
- if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
- scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
- }
- scene.resetCachedMaterial();
- };
- RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- // Bind
- if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
- if (this.isCube) {
- engine.bindFramebuffer(this._texture, faceIndex);
- }
- else {
- engine.bindFramebuffer(this._texture);
- }
- }
- if (this.onBeforeRender) {
- this.onBeforeRender(faceIndex);
- }
- // Clear
- if (this.onClear) {
- this.onClear(engine);
- }
- else {
- engine.clear(scene.clearColor, true, true);
- }
- if (!this._doNotChangeAspectRatio) {
- scene.updateTransformMatrix(true);
- }
- // Render
- this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
- if (useCameraPostProcess) {
- scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
- }
- if (!this._doNotChangeAspectRatio) {
- scene.updateTransformMatrix(true);
- }
- if (this.onAfterRender) {
- this.onAfterRender(faceIndex);
- }
- // Dump ?
- if (dumpForDebug) {
- BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
- }
- // Unbind
- if (!this.isCube || faceIndex === 5) {
- if (this.isCube) {
- if (faceIndex === 5) {
- engine.generateMipMapsForCubemap(this._texture);
- }
- }
- engine.unBindFramebuffer(this._texture, this.isCube);
- }
- };
- RenderTargetTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // RenderTarget Texture
- newTexture.coordinatesMode = this.coordinatesMode;
- newTexture.renderList = this.renderList.slice(0);
- return newTexture;
- };
- RenderTargetTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.renderTargetSize = this.getRenderSize();
- serializationObject.renderList = [];
- for (var index = 0; index < this.renderList.length; index++) {
- serializationObject.renderList.push(this.renderList[index].id);
- }
- return serializationObject;
- };
- RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
- RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
- RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
- return RenderTargetTexture;
- })(BABYLON.Texture);
- BABYLON.RenderTargetTexture = RenderTargetTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ProceduralTexture = (function (_super) {
- __extends(ProceduralTexture, _super);
- function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (isCube === void 0) { isCube = false; }
- _super.call(this, null, scene, !generateMipMaps);
- this.isCube = isCube;
- this.isEnabled = true;
- this._currentRefreshId = -1;
- this._refreshRate = 1;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._uniforms = new Array();
- this._samplers = new Array();
- this._textures = new Array();
- this._floats = new Array();
- this._floatsArrays = {};
- this._colors3 = new Array();
- this._colors4 = new Array();
- this._vectors2 = new Array();
- this._vectors3 = new Array();
- this._matrices = new Array();
- this._fallbackTextureUsed = false;
- scene._proceduralTextures.push(this);
- this.name = name;
- this.isRenderTarget = true;
- this._size = size;
- this._generateMipMaps = generateMipMaps;
- this.setFragment(fragment);
- this._fallbackTexture = fallbackTexture;
- if (isCube) {
- this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
- this.setFloat("face", 0);
- }
- else {
- this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
- }
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- }
- ProceduralTexture.prototype.reset = function () {
- if (this._effect === undefined) {
- return;
- }
- var engine = this.getScene().getEngine();
- engine._releaseEffect(this._effect);
- };
- ProceduralTexture.prototype.isReady = function () {
- var _this = this;
- var engine = this.getScene().getEngine();
- var shaders;
- if (!this._fragment) {
- return false;
- }
- if (this._fallbackTextureUsed) {
- return true;
- }
- if (this._fragment.fragmentElement !== undefined) {
- shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
- }
- else {
- shaders = { vertex: "procedural", fragment: this._fragment };
- }
- this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
- _this.releaseInternalTexture();
- if (_this._fallbackTexture) {
- _this._texture = _this._fallbackTexture._texture;
- _this._texture.references++;
- }
- _this._fallbackTextureUsed = true;
- });
- return this._effect.isReady();
- };
- ProceduralTexture.prototype.resetRefreshCounter = function () {
- this._currentRefreshId = -1;
- };
- ProceduralTexture.prototype.setFragment = function (fragment) {
- this._fragment = fragment;
- };
- Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
- get: function () {
- return this._refreshRate;
- },
- // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
- set: function (value) {
- this._refreshRate = value;
- this.resetRefreshCounter();
- },
- enumerable: true,
- configurable: true
- });
- ProceduralTexture.prototype._shouldRender = function () {
- if (!this.isEnabled || !this.isReady() || !this._texture) {
- return false;
- }
- if (this._fallbackTextureUsed) {
- return false;
- }
- if (this._currentRefreshId === -1) {
- this._currentRefreshId = 1;
- return true;
- }
- if (this.refreshRate === this._currentRefreshId) {
- this._currentRefreshId = 1;
- return true;
- }
- this._currentRefreshId++;
- return false;
- };
- ProceduralTexture.prototype.getRenderSize = function () {
- return this._size;
- };
- ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
- if (this._fallbackTextureUsed) {
- return;
- }
- this.releaseInternalTexture();
- this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
- };
- ProceduralTexture.prototype._checkUniform = function (uniformName) {
- if (this._uniforms.indexOf(uniformName) === -1) {
- this._uniforms.push(uniformName);
- }
- };
- ProceduralTexture.prototype.setTexture = function (name, texture) {
- if (this._samplers.indexOf(name) === -1) {
- this._samplers.push(name);
- }
- this._textures[name] = texture;
- return this;
- };
- ProceduralTexture.prototype.setFloat = function (name, value) {
- this._checkUniform(name);
- this._floats[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setFloats = function (name, value) {
- this._checkUniform(name);
- this._floatsArrays[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setColor3 = function (name, value) {
- this._checkUniform(name);
- this._colors3[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setColor4 = function (name, value) {
- this._checkUniform(name);
- this._colors4[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setVector2 = function (name, value) {
- this._checkUniform(name);
- this._vectors2[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setVector3 = function (name, value) {
- this._checkUniform(name);
- this._vectors3[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setMatrix = function (name, value) {
- this._checkUniform(name);
- this._matrices[name] = value;
- return this;
- };
- ProceduralTexture.prototype.render = function (useCameraPostProcess) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- // Render
- engine.enableEffect(this._effect);
- engine.setState(false);
- // Texture
- for (var name in this._textures) {
- this._effect.setTexture(name, this._textures[name]);
- }
- // Float
- for (name in this._floats) {
- this._effect.setFloat(name, this._floats[name]);
- }
- // Floats
- for (name in this._floatsArrays) {
- this._effect.setArray(name, this._floatsArrays[name]);
- }
- // Color3
- for (name in this._colors3) {
- this._effect.setColor3(name, this._colors3[name]);
- }
- // Color4
- for (name in this._colors4) {
- var color = this._colors4[name];
- this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
- }
- // Vector2
- for (name in this._vectors2) {
- this._effect.setVector2(name, this._vectors2[name]);
- }
- // Vector3
- for (name in this._vectors3) {
- this._effect.setVector3(name, this._vectors3[name]);
- }
- // Matrix
- for (name in this._matrices) {
- this._effect.setMatrix(name, this._matrices[name]);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
- if (this.isCube) {
- for (var face = 0; face < 6; face++) {
- engine.bindFramebuffer(this._texture, face);
- this._effect.setFloat("face", face);
- // Clear
- engine.clear(scene.clearColor, true, true);
- // Draw order
- engine.draw(true, 0, 6);
- // Mipmaps
- if (face === 5) {
- engine.generateMipMapsForCubemap(this._texture);
- }
- }
- }
- else {
- engine.bindFramebuffer(this._texture);
- // Clear
- engine.clear(scene.clearColor, true, true);
- // Draw order
- engine.draw(true, 0, 6);
- }
- // Unbind
- engine.unBindFramebuffer(this._texture, this.isCube);
- if (this.onGenerated) {
- this.onGenerated();
- }
- };
- ProceduralTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // RenderTarget Texture
- newTexture.coordinatesMode = this.coordinatesMode;
- return newTexture;
- };
- ProceduralTexture.prototype.dispose = function () {
- var index = this.getScene()._proceduralTextures.indexOf(this);
- if (index >= 0) {
- this.getScene()._proceduralTextures.splice(index, 1);
- }
- _super.prototype.dispose.call(this);
- };
- return ProceduralTexture;
- })(BABYLON.Texture);
- BABYLON.ProceduralTexture = ProceduralTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MirrorTexture = (function (_super) {
- __extends(MirrorTexture, _super);
- function MirrorTexture(name, size, scene, generateMipMaps) {
- var _this = this;
- _super.call(this, name, size, scene, generateMipMaps, true);
- this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._mirrorMatrix = BABYLON.Matrix.Zero();
- this.onBeforeRender = function () {
- BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
- _this._savedViewMatrix = scene.getViewMatrix();
- _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
- scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
- scene.clipPlane = _this.mirrorPlane;
- scene.getEngine().cullBackFaces = false;
- scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
- };
- this.onAfterRender = function () {
- scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
- scene.getEngine().cullBackFaces = true;
- scene._mirroredCameraPosition = null;
- delete scene.clipPlane;
- };
- }
- MirrorTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Mirror Texture
- newTexture.mirrorPlane = this.mirrorPlane.clone();
- newTexture.renderList = this.renderList.slice(0);
- return newTexture;
- };
- MirrorTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.mirrorPlane = this.mirrorPlane.asArray();
- return serializationObject;
- };
- return MirrorTexture;
- })(BABYLON.RenderTargetTexture);
- BABYLON.MirrorTexture = MirrorTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Creates a refraction texture used by refraction channel of the standard material.
- * @param name the texture name
- * @param size size of the underlying texture
- * @param scene root scene
- */
- var RefractionTexture = (function (_super) {
- __extends(RefractionTexture, _super);
- function RefractionTexture(name, size, scene, generateMipMaps) {
- var _this = this;
- _super.call(this, name, size, scene, generateMipMaps, true);
- this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
- this.depth = 2.0;
- this.onBeforeRender = function () {
- scene.clipPlane = _this.refractionPlane;
- };
- this.onAfterRender = function () {
- delete scene.clipPlane;
- };
- }
- RefractionTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Refraction Texture
- newTexture.refractionPlane = this.refractionPlane.clone();
- newTexture.renderList = this.renderList.slice(0);
- newTexture.depth = this.depth;
- return newTexture;
- };
- RefractionTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.mirrorPlane = this.refractionPlane.asArray();
- serializationObject.depth = this.depth;
- return serializationObject;
- };
- return RefractionTexture;
- })(BABYLON.RenderTargetTexture);
- BABYLON.RefractionTexture = RefractionTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DynamicTexture = (function (_super) {
- __extends(DynamicTexture, _super);
- function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps);
- this.name = name;
- this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._generateMipMaps = generateMipMaps;
- if (options.getContext) {
- this._canvas = options;
- this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
- }
- else {
- this._canvas = document.createElement("canvas");
- if (options.width) {
- this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
- }
- else {
- this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
- }
- }
- var textureSize = this.getSize();
- this._canvas.width = textureSize.width;
- this._canvas.height = textureSize.height;
- this._context = this._canvas.getContext("2d");
- }
- Object.defineProperty(DynamicTexture.prototype, "canRescale", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- DynamicTexture.prototype.scale = function (ratio) {
- var textureSize = this.getSize();
- textureSize.width *= ratio;
- textureSize.height *= ratio;
- this._canvas.width = textureSize.width;
- this._canvas.height = textureSize.height;
- this.releaseInternalTexture();
- this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
- };
- DynamicTexture.prototype.getContext = function () {
- return this._context;
- };
- DynamicTexture.prototype.clear = function () {
- var size = this.getSize();
- this._context.fillRect(0, 0, size.width, size.height);
- };
- DynamicTexture.prototype.update = function (invertY) {
- this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
- };
- DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
- if (update === void 0) { update = true; }
- var size = this.getSize();
- if (clearColor) {
- this._context.fillStyle = clearColor;
- this._context.fillRect(0, 0, size.width, size.height);
- }
- this._context.font = font;
- if (x === null) {
- var textSize = this._context.measureText(text);
- x = (size.width - textSize.width) / 2;
- }
- this._context.fillStyle = color;
- this._context.fillText(text, x, y);
- if (update) {
- this.update(invertY);
- }
- };
- DynamicTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Dynamic Texture
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- return newTexture;
- };
- return DynamicTexture;
- })(BABYLON.Texture);
- BABYLON.DynamicTexture = DynamicTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VideoTexture = (function (_super) {
- __extends(VideoTexture, _super);
- function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
- var _this = this;
- if (generateMipMaps === void 0) { generateMipMaps = false; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps, invertY);
- this._autoLaunch = true;
- this.name = name;
- this.video = document.createElement("video");
- this.video.autoplay = false;
- this.video.loop = true;
- this.video.addEventListener("canplaythrough", function () {
- if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
- _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- }
- else {
- _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- generateMipMaps = false;
- }
- _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
- _this._texture.isReady = true;
- });
- urls.forEach(function (url) {
- //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
- var source = document.createElement("source");
- source.src = url;
- _this.video.appendChild(source);
- });
- this._lastUpdate = BABYLON.Tools.Now;
- }
- VideoTexture.prototype.update = function () {
- if (this._autoLaunch) {
- this._autoLaunch = false;
- this.video.play();
- }
- var now = BABYLON.Tools.Now;
- if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
- return false;
- }
- this._lastUpdate = now;
- this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
- return true;
- };
- return VideoTexture;
- })(BABYLON.Texture);
- BABYLON.VideoTexture = VideoTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CustomProceduralTexture = (function (_super) {
- __extends(CustomProceduralTexture, _super);
- function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
- _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
- this._animate = true;
- this._time = 0;
- this._texturePath = texturePath;
- //Try to load json
- this.loadJson(texturePath);
- this.refreshRate = 1;
- }
- CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
- var _this = this;
- var that = this;
- function noConfigFile() {
- BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
- try {
- that.setFragment(that._texturePath);
- }
- catch (ex) {
- BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
- }
- }
- var configFileUrl = jsonUrl + "/config.json";
- var xhr = new XMLHttpRequest();
- xhr.open("GET", configFileUrl, true);
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
- try {
- _this._config = JSON.parse(xhr.response);
- _this.updateShaderUniforms();
- _this.updateTextures();
- _this.setFragment(_this._texturePath + "/custom");
- _this._animate = _this._config.animate;
- _this.refreshRate = _this._config.refreshrate;
- }
- catch (ex) {
- noConfigFile();
- }
- }
- else {
- noConfigFile();
- }
- }, false);
- xhr.addEventListener("error", function () {
- noConfigFile();
- }, false);
- try {
- xhr.send();
- }
- catch (ex) {
- BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
- }
- };
- CustomProceduralTexture.prototype.isReady = function () {
- if (!_super.prototype.isReady.call(this)) {
- return false;
- }
- for (var name in this._textures) {
- var texture = this._textures[name];
- if (!texture.isReady()) {
- return false;
- }
- }
- return true;
- };
- CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
- if (this._animate) {
- this._time += this.getScene().getAnimationRatio() * 0.03;
- this.updateShaderUniforms();
- }
- _super.prototype.render.call(this, useCameraPostProcess);
- };
- CustomProceduralTexture.prototype.updateTextures = function () {
- for (var i = 0; i < this._config.sampler2Ds.length; i++) {
- this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
- }
- };
- CustomProceduralTexture.prototype.updateShaderUniforms = function () {
- if (this._config) {
- for (var j = 0; j < this._config.uniforms.length; j++) {
- var uniform = this._config.uniforms[j];
- switch (uniform.type) {
- case "float":
- this.setFloat(uniform.name, uniform.value);
- break;
- case "color3":
- this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
- break;
- case "color4":
- this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
- break;
- case "vector2":
- this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
- break;
- case "vector3":
- this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
- break;
- }
- }
- }
- this.setFloat("time", this._time);
- };
- Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
- get: function () {
- return this._animate;
- },
- set: function (value) {
- this._animate = value;
- },
- enumerable: true,
- configurable: true
- });
- return CustomProceduralTexture;
- })(BABYLON.ProceduralTexture);
- BABYLON.CustomProceduralTexture = CustomProceduralTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var EffectFallbacks = (function () {
- function EffectFallbacks() {
- this._defines = {};
- this._currentRank = 32;
- this._maxRank = -1;
- }
- EffectFallbacks.prototype.addFallback = function (rank, define) {
- if (!this._defines[rank]) {
- if (rank < this._currentRank) {
- this._currentRank = rank;
- }
- if (rank > this._maxRank) {
- this._maxRank = rank;
- }
- this._defines[rank] = new Array();
- }
- this._defines[rank].push(define);
- };
- EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
- this._meshRank = rank;
- this._mesh = mesh;
- if (rank > this._maxRank) {
- this._maxRank = rank;
- }
- };
- Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
- get: function () {
- return this._currentRank <= this._maxRank;
- },
- enumerable: true,
- configurable: true
- });
- EffectFallbacks.prototype.reduce = function (currentDefines) {
- var currentFallbacks = this._defines[this._currentRank];
- for (var index = 0; index < currentFallbacks.length; index++) {
- currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
- }
- if (this._mesh && this._currentRank === this._meshRank) {
- this._mesh.computeBonesUsingShaders = false;
- currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
- BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
- }
- this._currentRank++;
- return currentDefines;
- };
- return EffectFallbacks;
- })();
- BABYLON.EffectFallbacks = EffectFallbacks;
- var Effect = (function () {
- function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
- var _this = this;
- this._isReady = false;
- this._compilationError = "";
- this._valueCache = [];
- this._engine = engine;
- this.name = baseName;
- this.defines = defines;
- this._uniformsNames = uniformsNames.concat(samplers);
- this._samplers = samplers;
- this._attributesNames = attributesNames;
- this.onError = onError;
- this.onCompiled = onCompiled;
- var vertexSource;
- var fragmentSource;
- if (baseName.vertexElement) {
- vertexSource = document.getElementById(baseName.vertexElement);
- if (!vertexSource) {
- vertexSource = baseName.vertexElement;
- }
- }
- else {
- vertexSource = baseName.vertex || baseName;
- }
- if (baseName.fragmentElement) {
- fragmentSource = document.getElementById(baseName.fragmentElement);
- if (!fragmentSource) {
- fragmentSource = baseName.fragmentElement;
- }
- }
- else {
- fragmentSource = baseName.fragment || baseName;
- }
- this._loadVertexShader(vertexSource, function (vertexCode) {
- _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
- _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
- _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
- _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
- });
- });
- });
- });
- }
- // Properties
- Effect.prototype.isReady = function () {
- return this._isReady;
- };
- Effect.prototype.getProgram = function () {
- return this._program;
- };
- Effect.prototype.getAttributesNames = function () {
- return this._attributesNames;
- };
- Effect.prototype.getAttributeLocation = function (index) {
- return this._attributes[index];
- };
- Effect.prototype.getAttributeLocationByName = function (name) {
- var index = this._attributesNames.indexOf(name);
- return this._attributes[index];
- };
- Effect.prototype.getAttributesCount = function () {
- return this._attributes.length;
- };
- Effect.prototype.getUniformIndex = function (uniformName) {
- return this._uniformsNames.indexOf(uniformName);
- };
- Effect.prototype.getUniform = function (uniformName) {
- return this._uniforms[this._uniformsNames.indexOf(uniformName)];
- };
- Effect.prototype.getSamplers = function () {
- return this._samplers;
- };
- Effect.prototype.getCompilationError = function () {
- return this._compilationError;
- };
- // Methods
- Effect.prototype._loadVertexShader = function (vertex, callback) {
- // DOM element ?
- if (vertex instanceof HTMLElement) {
- var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
- callback(vertexCode);
- return;
- }
- // Is in local store ?
- if (Effect.ShadersStore[vertex + "VertexShader"]) {
- callback(Effect.ShadersStore[vertex + "VertexShader"]);
- return;
- }
- var vertexShaderUrl;
- if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
- vertexShaderUrl = vertex;
- }
- else {
- vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
- }
- // Vertex shader
- BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
- };
- Effect.prototype._loadFragmentShader = function (fragment, callback) {
- // DOM element ?
- if (fragment instanceof HTMLElement) {
- var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
- callback(fragmentCode);
- return;
- }
- // Is in local store ?
- if (Effect.ShadersStore[fragment + "PixelShader"]) {
- callback(Effect.ShadersStore[fragment + "PixelShader"]);
- return;
- }
- if (Effect.ShadersStore[fragment + "FragmentShader"]) {
- callback(Effect.ShadersStore[fragment + "FragmentShader"]);
- return;
- }
- var fragmentShaderUrl;
- if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
- fragmentShaderUrl = fragment;
- }
- else {
- fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
- }
- // Fragment shader
- BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
- };
- Effect.prototype._dumpShadersName = function () {
- if (this.name.vertexElement) {
- BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
- BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
- }
- else if (this.name.vertex) {
- BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
- BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
- }
- else {
- BABYLON.Tools.Error("Vertex shader:" + this.name);
- BABYLON.Tools.Error("Fragment shader:" + this.name);
- }
- };
- Effect.prototype._processIncludes = function (sourceCode, callback) {
- var _this = this;
- var regex = /#include<(.+)>(\((.*)\))*/g;
- var match = regex.exec(sourceCode);
- var returnValue = new String(sourceCode);
- while (match != null) {
- var includeFile = match[1];
- if (Effect.IncludesShadersStore[includeFile]) {
- // Substitution
- var includeContent = Effect.IncludesShadersStore[includeFile];
- if (match[2]) {
- var splits = match[2].substr(1, match[2].length - 2).split(",");
- for (var index = 0; index < splits.length; index += 2) {
- var source = new RegExp(splits[index], "g");
- var dest = splits[index + 1];
- includeContent = includeContent.replace(source, dest);
- }
- }
- // Replace
- returnValue = returnValue.replace(match[0], includeContent);
- }
- else {
- var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
- BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
- Effect.IncludesShadersStore[includeFile] = fileContent;
- _this._processIncludes(returnValue, callback);
- });
- return;
- }
- match = regex.exec(sourceCode);
- }
- callback(returnValue);
- };
- Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
- try {
- var engine = this._engine;
- // Precision
- if (!engine.getCaps().highPrecisionShaderSupported) {
- vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
- fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
- }
- this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
- this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
- this._attributes = engine.getAttributes(this._program, attributesNames);
- for (var index = 0; index < this._samplers.length; index++) {
- var sampler = this.getUniform(this._samplers[index]);
- if (sampler == null) {
- this._samplers.splice(index, 1);
- index--;
- }
- }
- engine.bindSamplers(this);
- this._isReady = true;
- if (this.onCompiled) {
- this.onCompiled(this);
- }
- }
- catch (e) {
- // Is it a problem with precision?
- if (e.message.indexOf("highp") !== -1) {
- vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
- fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
- this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
- return;
- }
- // Let's go through fallbacks then
- if (fallbacks && fallbacks.isMoreFallbacks) {
- BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
- this._dumpShadersName();
- defines = fallbacks.reduce(defines);
- this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
- }
- else {
- BABYLON.Tools.Error("Unable to compile effect: ");
- this._dumpShadersName();
- BABYLON.Tools.Error("Defines: " + defines);
- BABYLON.Tools.Error("Error: " + e.message);
- this._compilationError = e.message;
- if (this.onError) {
- this.onError(this, this._compilationError);
- }
- }
- }
- };
- Object.defineProperty(Effect.prototype, "isSupported", {
- get: function () {
- return this._compilationError === "";
- },
- enumerable: true,
- configurable: true
- });
- Effect.prototype._bindTexture = function (channel, texture) {
- this._engine._bindTexture(this._samplers.indexOf(channel), texture);
- };
- Effect.prototype.setTexture = function (channel, texture) {
- this._engine.setTexture(this._samplers.indexOf(channel), texture);
- };
- Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
- };
- Effect.prototype._cacheMatrix = function (uniformName, matrix) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = new BABYLON.Matrix();
- }
- for (var index = 0; index < 16; index++) {
- this._valueCache[uniformName].m[index] = matrix.m[index];
- }
- };
- Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- };
- Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y, z];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- this._valueCache[uniformName][2] = z;
- };
- Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y, z, w];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- this._valueCache[uniformName][2] = z;
- this._valueCache[uniformName][3] = w;
- };
- Effect.prototype.setArray = function (uniformName, array) {
- this._engine.setArray(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray2 = function (uniformName, array) {
- this._engine.setArray2(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray3 = function (uniformName, array) {
- this._engine.setArray3(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray4 = function (uniformName, array) {
- this._engine.setArray4(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setMatrices = function (uniformName, matrices) {
- this._engine.setMatrices(this.getUniform(uniformName), matrices);
- return this;
- };
- Effect.prototype.setMatrix = function (uniformName, matrix) {
- //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
- // return this;
- // this._cacheMatrix(uniformName, matrix);
- this._engine.setMatrix(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
- this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
- this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
- return this;
- };
- Effect.prototype.setFloat = function (uniformName, value) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
- return this;
- this._valueCache[uniformName] = value;
- this._engine.setFloat(this.getUniform(uniformName), value);
- return this;
- };
- Effect.prototype.setBool = function (uniformName, bool) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
- return this;
- this._valueCache[uniformName] = bool;
- this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
- return this;
- };
- Effect.prototype.setVector2 = function (uniformName, vector2) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
- return this;
- this._cacheFloat2(uniformName, vector2.x, vector2.y);
- this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
- return this;
- };
- Effect.prototype.setFloat2 = function (uniformName, x, y) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
- return this;
- this._cacheFloat2(uniformName, x, y);
- this._engine.setFloat2(this.getUniform(uniformName), x, y);
- return this;
- };
- Effect.prototype.setVector3 = function (uniformName, vector3) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
- return this;
- this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
- this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
- return this;
- };
- Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
- return this;
- this._cacheFloat3(uniformName, x, y, z);
- this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
- return this;
- };
- Effect.prototype.setVector4 = function (uniformName, vector4) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
- return this;
- this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
- this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
- return this;
- };
- Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
- return this;
- this._cacheFloat4(uniformName, x, y, z, w);
- this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
- return this;
- };
- Effect.prototype.setColor3 = function (uniformName, color3) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
- return this;
- this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
- this._engine.setColor3(this.getUniform(uniformName), color3);
- return this;
- };
- Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
- return this;
- this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
- this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
- return this;
- };
- // Statics
- Effect.ShadersStore = {};
- Effect.IncludesShadersStore = {};
- return Effect;
- })();
- BABYLON.Effect = Effect;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MaterialDefines = (function () {
- function MaterialDefines() {
- }
- MaterialDefines.prototype.isEqual = function (other) {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (this[prop] !== other[prop]) {
- return false;
- }
- }
- return true;
- };
- MaterialDefines.prototype.cloneTo = function (other) {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- other[prop] = this[prop];
- }
- };
- MaterialDefines.prototype.reset = function () {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (typeof (this[prop]) === "number") {
- this[prop] = 0;
- }
- else {
- this[prop] = false;
- }
- }
- };
- MaterialDefines.prototype.toString = function () {
- var result = "";
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (typeof (this[prop]) === "number") {
- result += "#define " + prop + " " + this[prop] + "\n";
- }
- else if (this[prop]) {
- result += "#define " + prop + "\n";
- }
- }
- return result;
- };
- return MaterialDefines;
- })();
- BABYLON.MaterialDefines = MaterialDefines;
- var Material = (function () {
- function Material(name, scene, doNotAdd) {
- this.name = name;
- this.checkReadyOnEveryCall = false;
- this.checkReadyOnlyOnce = false;
- this.state = "";
- this.alpha = 1.0;
- this.backFaceCulling = true;
- this.sideOrientation = Material.CounterClockWiseSideOrientation;
- this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
- this.disableDepthWrite = false;
- this.fogEnabled = true;
- this._wasPreviouslyReady = false;
- this._fillMode = Material.TriangleFillMode;
- this.pointSize = 1.0;
- this.zOffset = 0;
- this.id = name;
- this._scene = scene;
- if (!doNotAdd) {
- scene.materials.push(this);
- }
- }
- Object.defineProperty(Material, "TriangleFillMode", {
- get: function () {
- return Material._TriangleFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "WireFrameFillMode", {
- get: function () {
- return Material._WireFrameFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "PointFillMode", {
- get: function () {
- return Material._PointFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "ClockWiseSideOrientation", {
- get: function () {
- return Material._ClockWiseSideOrientation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
- get: function () {
- return Material._CounterClockWiseSideOrientation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "wireframe", {
- get: function () {
- return this._fillMode === Material.WireFrameFillMode;
- },
- set: function (value) {
- this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "pointsCloud", {
- get: function () {
- return this._fillMode === Material.PointFillMode;
- },
- set: function (value) {
- this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "fillMode", {
- get: function () {
- return this._fillMode;
- },
- set: function (value) {
- this._fillMode = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "isFrozen", {
- get: function () {
- return this.checkReadyOnlyOnce;
- },
- enumerable: true,
- configurable: true
- });
- Material.prototype.freeze = function () {
- this.checkReadyOnlyOnce = true;
- };
- Material.prototype.unfreeze = function () {
- this.checkReadyOnlyOnce = false;
- };
- Material.prototype.isReady = function (mesh, useInstances) {
- return true;
- };
- Material.prototype.getEffect = function () {
- return this._effect;
- };
- Material.prototype.getScene = function () {
- return this._scene;
- };
- Material.prototype.needAlphaBlending = function () {
- return (this.alpha < 1.0);
- };
- Material.prototype.needAlphaTesting = function () {
- return false;
- };
- Material.prototype.getAlphaTestTexture = function () {
- return null;
- };
- Material.prototype.trackCreation = function (onCompiled, onError) {
- };
- Material.prototype.markDirty = function () {
- this._wasPreviouslyReady = false;
- };
- Material.prototype._preBind = function () {
- var engine = this._scene.getEngine();
- engine.enableEffect(this._effect);
- engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
- };
- Material.prototype.bind = function (world, mesh) {
- this._scene._cachedMaterial = this;
- if (this.onBind) {
- this.onBind(this, mesh);
- }
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- this._cachedDepthWriteState = engine.getDepthWrite();
- engine.setDepthWrite(false);
- }
- };
- Material.prototype.bindOnlyWorldMatrix = function (world) {
- };
- Material.prototype.unbind = function () {
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- engine.setDepthWrite(this._cachedDepthWriteState);
- }
- };
- Material.prototype.clone = function (name) {
- return null;
- };
- Material.prototype.getBindedMeshes = function () {
- var result = new Array();
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.material === this) {
- result.push(mesh);
- }
- }
- return result;
- };
- Material.prototype.dispose = function (forceDisposeEffect) {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- var index = this._scene.materials.indexOf(this);
- if (index >= 0) {
- this._scene.materials.splice(index, 1);
- }
- // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
- if (forceDisposeEffect && this._effect) {
- this._scene.getEngine()._releaseEffect(this._effect);
- this._effect = null;
- }
- // Remove from meshes
- for (index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.material === this) {
- mesh.material = null;
- }
- }
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- Material.prototype.copyTo = function (other) {
- other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
- other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
- other.alpha = this.alpha;
- other.fillMode = this.fillMode;
- other.backFaceCulling = this.backFaceCulling;
- other.fogEnabled = this.fogEnabled;
- other.wireframe = this.wireframe;
- other.zOffset = this.zOffset;
- other.alphaMode = this.alphaMode;
- other.sideOrientation = this.sideOrientation;
- other.disableDepthWrite = this.disableDepthWrite;
- other.pointSize = this.pointSize;
- other.pointsCloud = this.pointsCloud;
- };
- Material.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.alpha = this.alpha;
- serializationObject.id = this.id;
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- serializationObject.backFaceCulling = this.backFaceCulling;
- serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
- serializationObject.disableDepthWrite = this.disableDepthWrite;
- return serializationObject;
- };
- Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
- var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
- multiMaterial.id = parsedMultiMaterial.id;
- BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
- for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
- var subMatId = parsedMultiMaterial.materials[matIndex];
- if (subMatId) {
- multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
- }
- else {
- multiMaterial.subMaterials.push(null);
- }
- }
- return multiMaterial;
- };
- Material.Parse = function (parsedMaterial, scene, rootUrl) {
- if (!parsedMaterial.customType) {
- return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
- }
- var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
- return materialType.Parse(parsedMaterial, scene, rootUrl);
- ;
- };
- Material._TriangleFillMode = 0;
- Material._WireFrameFillMode = 1;
- Material._PointFillMode = 2;
- Material._ClockWiseSideOrientation = 0;
- Material._CounterClockWiseSideOrientation = 1;
- return Material;
- })();
- BABYLON.Material = Material;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var maxSimultaneousLights = 4;
- var FresnelParameters = (function () {
- function FresnelParameters() {
- this.isEnabled = true;
- this.leftColor = BABYLON.Color3.White();
- this.rightColor = BABYLON.Color3.Black();
- this.bias = 0;
- this.power = 1;
- }
- FresnelParameters.prototype.clone = function () {
- var newFresnelParameters = new FresnelParameters();
- BABYLON.Tools.DeepCopy(this, newFresnelParameters);
- return new FresnelParameters;
- };
- FresnelParameters.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.isEnabled = this.isEnabled;
- serializationObject.leftColor = this.leftColor;
- serializationObject.rightColor = this.rightColor;
- serializationObject.bias = this.bias;
- serializationObject.power = this.power;
- return serializationObject;
- };
- FresnelParameters.Parse = function (parsedFresnelParameters) {
- var fresnelParameters = new FresnelParameters();
- fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
- fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
- fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
- fresnelParameters.bias = parsedFresnelParameters.bias;
- fresnelParameters.power = parsedFresnelParameters.power || 1.0;
- return fresnelParameters;
- };
- return FresnelParameters;
- })();
- BABYLON.FresnelParameters = FresnelParameters;
- var StandardMaterialDefines = (function (_super) {
- __extends(StandardMaterialDefines, _super);
- function StandardMaterialDefines() {
- _super.call(this);
- this.DIFFUSE = false;
- this.AMBIENT = false;
- this.OPACITY = false;
- this.OPACITYRGB = false;
- this.REFLECTION = false;
- this.EMISSIVE = false;
- this.SPECULAR = false;
- this.BUMP = false;
- this.SPECULAROVERALPHA = false;
- this.CLIPPLANE = false;
- this.ALPHATEST = false;
- this.ALPHAFROMDIFFUSE = false;
- this.POINTSIZE = false;
- this.FOG = false;
- this.LIGHT0 = false;
- this.LIGHT1 = false;
- this.LIGHT2 = false;
- this.LIGHT3 = false;
- this.SPOTLIGHT0 = false;
- this.SPOTLIGHT1 = false;
- this.SPOTLIGHT2 = false;
- this.SPOTLIGHT3 = false;
- this.HEMILIGHT0 = false;
- this.HEMILIGHT1 = false;
- this.HEMILIGHT2 = false;
- this.HEMILIGHT3 = false;
- this.POINTLIGHT0 = false;
- this.POINTLIGHT1 = false;
- this.POINTLIGHT2 = false;
- this.POINTLIGHT3 = false;
- this.DIRLIGHT0 = false;
- this.DIRLIGHT1 = false;
- this.DIRLIGHT2 = false;
- this.DIRLIGHT3 = false;
- this.SPECULARTERM = false;
- this.SHADOW0 = false;
- this.SHADOW1 = false;
- this.SHADOW2 = false;
- this.SHADOW3 = false;
- this.SHADOWS = false;
- this.SHADOWVSM0 = false;
- this.SHADOWVSM1 = false;
- this.SHADOWVSM2 = false;
- this.SHADOWVSM3 = false;
- this.SHADOWPCF0 = false;
- this.SHADOWPCF1 = false;
- this.SHADOWPCF2 = false;
- this.SHADOWPCF3 = false;
- this.DIFFUSEFRESNEL = false;
- this.OPACITYFRESNEL = false;
- this.REFLECTIONFRESNEL = false;
- this.REFRACTIONFRESNEL = false;
- this.EMISSIVEFRESNEL = false;
- this.FRESNEL = false;
- this.NORMAL = false;
- this.UV1 = false;
- this.UV2 = false;
- this.VERTEXCOLOR = false;
- this.VERTEXALPHA = false;
- this.NUM_BONE_INFLUENCERS = 0;
- this.BonesPerMesh = 0;
- this.INSTANCES = false;
- this.GLOSSINESS = false;
- this.ROUGHNESS = false;
- this.EMISSIVEASILLUMINATION = false;
- this.LINKEMISSIVEWITHDIFFUSE = false;
- this.REFLECTIONFRESNELFROMSPECULAR = false;
- this.LIGHTMAP = false;
- this.USELIGHTMAPASSHADOWMAP = false;
- this.REFLECTIONMAP_3D = false;
- this.REFLECTIONMAP_SPHERICAL = false;
- this.REFLECTIONMAP_PLANAR = false;
- this.REFLECTIONMAP_CUBIC = false;
- this.REFLECTIONMAP_PROJECTION = false;
- this.REFLECTIONMAP_SKYBOX = false;
- this.REFLECTIONMAP_EXPLICIT = false;
- this.REFLECTIONMAP_EQUIRECTANGULAR = false;
- this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
- this.INVERTCUBICMAP = false;
- this.LOGARITHMICDEPTH = false;
- this.REFRACTION = false;
- this.REFRACTIONMAP_3D = false;
- this._keys = Object.keys(this);
- }
- return StandardMaterialDefines;
- })(BABYLON.MaterialDefines);
- var StandardMaterial = (function (_super) {
- __extends(StandardMaterial, _super);
- function StandardMaterial(name, scene) {
- var _this = this;
- _super.call(this, name, scene);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- this.diffuseColor = new BABYLON.Color3(1, 1, 1);
- this.specularColor = new BABYLON.Color3(1, 1, 1);
- this.specularPower = 64;
- this.emissiveColor = new BABYLON.Color3(0, 0, 0);
- this.useAlphaFromDiffuseTexture = false;
- this.useEmissiveAsIllumination = false;
- this.linkEmissiveWithDiffuse = false;
- this.useReflectionFresnelFromSpecular = false;
- this.useSpecularOverAlpha = false;
- this.disableLighting = false;
- this.roughness = 0;
- this.indexOfRefraction = 0.98;
- this.invertRefractionY = true;
- this.useLightmapAsShadowmap = false;
- this.useGlossinessFromSpecularMapAlpha = false;
- this._renderTargets = new BABYLON.SmartArray(16);
- this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
- this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
- this._defines = new StandardMaterialDefines();
- this._cachedDefines = new StandardMaterialDefines();
- this._cachedDefines.BonesPerMesh = -1;
- this.getRenderTargetTextures = function () {
- _this._renderTargets.reset();
- if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.reflectionTexture);
- }
- if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.refractionTexture);
- }
- return _this._renderTargets;
- };
- }
- Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
- get: function () {
- return this._useLogarithmicDepth;
- },
- set: function (value) {
- this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
- },
- enumerable: true,
- configurable: true
- });
- StandardMaterial.prototype.needAlphaBlending = function () {
- return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
- };
- StandardMaterial.prototype.needAlphaTesting = function () {
- return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
- };
- StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
- return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
- };
- StandardMaterial.prototype.getAlphaTestTexture = function () {
- return this.diffuseTexture;
- };
- // Methods
- StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
- if (!mesh) {
- return true;
- }
- if (this._defines.INSTANCES !== useInstances) {
- return false;
- }
- if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
- return true;
- }
- return false;
- };
- StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
- var lightIndex = 0;
- var needNormals = false;
- for (var index = 0; index < scene.lights.length; index++) {
- var light = scene.lights[index];
- if (!light.isEnabled()) {
- continue;
- }
- // Excluded check
- if (light._excludedMeshesIds.length > 0) {
- for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
- var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
- if (excludedMesh) {
- light.excludedMeshes.push(excludedMesh);
- }
- }
- light._excludedMeshesIds = [];
- }
- // Included check
- if (light._includedOnlyMeshesIds.length > 0) {
- for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
- var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
- if (includedOnlyMesh) {
- light.includedOnlyMeshes.push(includedOnlyMesh);
- }
- }
- light._includedOnlyMeshesIds = [];
- }
- if (!light.canAffectMesh(mesh)) {
- continue;
- }
- needNormals = true;
- defines["LIGHT" + lightIndex] = true;
- var type;
- if (light instanceof BABYLON.SpotLight) {
- type = "SPOTLIGHT" + lightIndex;
- }
- else if (light instanceof BABYLON.HemisphericLight) {
- type = "HEMILIGHT" + lightIndex;
- }
- else if (light instanceof BABYLON.PointLight) {
- type = "POINTLIGHT" + lightIndex;
- }
- else {
- type = "DIRLIGHT" + lightIndex;
- }
- defines[type] = true;
- // Specular
- if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
- defines["SPECULARTERM"] = true;
- }
- // Shadows
- if (scene.shadowsEnabled) {
- var shadowGenerator = light.getShadowGenerator();
- if (mesh && mesh.receiveShadows && shadowGenerator) {
- defines["SHADOW" + lightIndex] = true;
- defines["SHADOWS"] = true;
- if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
- defines["SHADOWVSM" + lightIndex] = true;
- }
- if (shadowGenerator.usePoissonSampling) {
- defines["SHADOWPCF" + lightIndex] = true;
- }
- }
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- return needNormals;
- };
- StandardMaterial.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
- var shadowGenerator = light.getShadowGenerator();
- if (mesh.receiveShadows && shadowGenerator) {
- if (!light.needCube()) {
- effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
- }
- else {
- if (!depthValuesAlreadySet) {
- depthValuesAlreadySet = true;
- effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- }
- effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
- effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
- }
- return depthValuesAlreadySet;
- };
- StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
- var lightIndex = 0;
- var depthValuesAlreadySet = false;
- for (var index = 0; index < scene.lights.length; index++) {
- var light = scene.lights[index];
- if (!light.isEnabled()) {
- continue;
- }
- if (!light.canAffectMesh(mesh)) {
- continue;
- }
- if (light instanceof BABYLON.PointLight) {
- // Point Light
- light.transferToEffect(effect, "vLightData" + lightIndex);
- }
- else if (light instanceof BABYLON.DirectionalLight) {
- // Directional Light
- light.transferToEffect(effect, "vLightData" + lightIndex);
- }
- else if (light instanceof BABYLON.SpotLight) {
- // Spot Light
- light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
- }
- else if (light instanceof BABYLON.HemisphericLight) {
- // Hemispheric Light
- light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
- }
- light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
- effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
- if (defines["SPECULARTERM"]) {
- light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
- effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
- }
- // Shadows
- if (scene.shadowsEnabled) {
- depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- };
- StandardMaterial.HandleFallbacksForShadows = function (defines, fallbacks) {
- for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
- if (!defines["LIGHT" + lightIndex]) {
- continue;
- }
- if (lightIndex > 0) {
- fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
- }
- if (defines["SHADOW" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOW" + lightIndex);
- }
- if (defines["SHADOWPCF" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
- }
- if (defines["SHADOWVSM" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
- }
- }
- };
- StandardMaterial.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
- if (defines["NUM_BONE_INFLUENCERS"] > 0) {
- fallbacks.addCPUSkinningFallback(0, mesh);
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (defines["NUM_BONE_INFLUENCERS"] > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- }
- };
- StandardMaterial.PrepareAttributesForInstances = function (attribs, defines) {
- if (defines["INSTANCES"]) {
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- };
- StandardMaterial.prototype.isReady = function (mesh, useInstances) {
- if (this.isFrozen) {
- if (this._wasPreviouslyReady) {
- return true;
- }
- }
- var scene = this.getScene();
- if (!this.checkReadyOnEveryCall) {
- if (this._renderId === scene.getRenderId()) {
- if (this._checkCache(scene, mesh, useInstances)) {
- return true;
- }
- }
- }
- var engine = scene.getEngine();
- var needNormals = false;
- var needUVs = false;
- this._defines.reset();
- // Textures
- if (scene.texturesEnabled) {
- if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- if (!this.diffuseTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.DIFFUSE = true;
- }
- }
- if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- if (!this.ambientTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.AMBIENT = true;
- }
- }
- if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- if (!this.opacityTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.OPACITY = true;
- if (this.opacityTexture.getAlphaFromRGB) {
- this._defines.OPACITYRGB = true;
- }
- }
- }
- if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (!this.reflectionTexture.isReady()) {
- return false;
- }
- else {
- needNormals = true;
- this._defines.REFLECTION = true;
- if (this.roughness > 0) {
- this._defines.ROUGHNESS = true;
- }
- if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
- this._defines.INVERTCUBICMAP = true;
- }
- this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
- switch (this.reflectionTexture.coordinatesMode) {
- case BABYLON.Texture.CUBIC_MODE:
- case BABYLON.Texture.INVCUBIC_MODE:
- this._defines.REFLECTIONMAP_CUBIC = true;
- break;
- case BABYLON.Texture.EXPLICIT_MODE:
- this._defines.REFLECTIONMAP_EXPLICIT = true;
- break;
- case BABYLON.Texture.PLANAR_MODE:
- this._defines.REFLECTIONMAP_PLANAR = true;
- break;
- case BABYLON.Texture.PROJECTION_MODE:
- this._defines.REFLECTIONMAP_PROJECTION = true;
- break;
- case BABYLON.Texture.SKYBOX_MODE:
- this._defines.REFLECTIONMAP_SKYBOX = true;
- break;
- case BABYLON.Texture.SPHERICAL_MODE:
- this._defines.REFLECTIONMAP_SPHERICAL = true;
- break;
- case BABYLON.Texture.EQUIRECTANGULAR_MODE:
- this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
- break;
- case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
- this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
- break;
- }
- }
- }
- if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- if (!this.emissiveTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.EMISSIVE = true;
- }
- }
- if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- if (!this.lightmapTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.LIGHTMAP = true;
- this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
- }
- }
- if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
- if (!this.specularTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.SPECULAR = true;
- this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
- }
- }
- if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
- if (!this.bumpTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.BUMP = true;
- }
- }
- if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- if (!this.refractionTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.REFRACTION = true;
- this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
- }
- }
- }
- // Effect
- if (scene.clipPlane) {
- this._defines.CLIPPLANE = true;
- }
- if (engine.getAlphaTesting()) {
- this._defines.ALPHATEST = true;
- }
- if (this._shouldUseAlphaFromDiffuseTexture()) {
- this._defines.ALPHAFROMDIFFUSE = true;
- }
- if (this.useEmissiveAsIllumination) {
- this._defines.EMISSIVEASILLUMINATION = true;
- }
- if (this.linkEmissiveWithDiffuse) {
- this._defines.LINKEMISSIVEWITHDIFFUSE = true;
- }
- if (this.useReflectionFresnelFromSpecular) {
- this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
- }
- if (this.useLogarithmicDepth) {
- this._defines.LOGARITHMICDEPTH = true;
- }
- // Point size
- if (this.pointsCloud || scene.forcePointsCloud) {
- this._defines.POINTSIZE = true;
- }
- // Fog
- if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- this._defines.FOG = true;
- }
- if (scene.lightsEnabled && !this.disableLighting) {
- needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
- }
- if (StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
- this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
- this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
- this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
- this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
- this._defines.DIFFUSEFRESNEL = true;
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._defines.OPACITYFRESNEL = true;
- }
- if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- this._defines.REFLECTIONFRESNEL = true;
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
- this._defines.REFRACTIONFRESNEL = true;
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._defines.EMISSIVEFRESNEL = true;
- }
- needNormals = true;
- this._defines.FRESNEL = true;
- }
- }
- if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
- this._defines.SPECULAROVERALPHA = true;
- }
- // Attribs
- if (mesh) {
- if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- this._defines.NORMAL = true;
- }
- if (needUVs) {
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- this._defines.UV1 = true;
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- this._defines.UV2 = true;
- }
- }
- if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- this._defines.VERTEXCOLOR = true;
- if (mesh.hasVertexAlpha) {
- this._defines.VERTEXALPHA = true;
- }
- }
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
- this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
- }
- // Instances
- if (useInstances) {
- this._defines.INSTANCES = true;
- }
- }
- // Get correct effect
- if (!this._defines.isEqual(this._cachedDefines)) {
- this._defines.cloneTo(this._cachedDefines);
- scene.resetCachedMaterial();
- // Fallbacks
- var fallbacks = new BABYLON.EffectFallbacks();
- if (this._defines.REFLECTION) {
- fallbacks.addFallback(0, "REFLECTION");
- }
- if (this._defines.SPECULAR) {
- fallbacks.addFallback(0, "SPECULAR");
- }
- if (this._defines.BUMP) {
- fallbacks.addFallback(0, "BUMP");
- }
- if (this._defines.SPECULAROVERALPHA) {
- fallbacks.addFallback(0, "SPECULAROVERALPHA");
- }
- if (this._defines.FOG) {
- fallbacks.addFallback(1, "FOG");
- }
- if (this._defines.POINTSIZE) {
- fallbacks.addFallback(0, "POINTSIZE");
- }
- if (this._defines.LOGARITHMICDEPTH) {
- fallbacks.addFallback(0, "LOGARITHMICDEPTH");
- }
- StandardMaterial.HandleFallbacksForShadows(this._defines, fallbacks);
- if (this._defines.SPECULARTERM) {
- fallbacks.addFallback(0, "SPECULARTERM");
- }
- if (this._defines.DIFFUSEFRESNEL) {
- fallbacks.addFallback(1, "DIFFUSEFRESNEL");
- }
- if (this._defines.OPACITYFRESNEL) {
- fallbacks.addFallback(2, "OPACITYFRESNEL");
- }
- if (this._defines.REFLECTIONFRESNEL) {
- fallbacks.addFallback(3, "REFLECTIONFRESNEL");
- }
- if (this._defines.EMISSIVEFRESNEL) {
- fallbacks.addFallback(4, "EMISSIVEFRESNEL");
- }
- if (this._defines.FRESNEL) {
- fallbacks.addFallback(4, "FRESNEL");
- }
- //Attributes
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- if (this._defines.NORMAL) {
- attribs.push(BABYLON.VertexBuffer.NormalKind);
- }
- if (this._defines.UV1) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- }
- if (this._defines.UV2) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (this._defines.VERTEXCOLOR) {
- attribs.push(BABYLON.VertexBuffer.ColorKind);
- }
- StandardMaterial.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
- StandardMaterial.PrepareAttributesForInstances(attribs, this._defines);
- // Legacy browser patch
- var shaderName = "default";
- if (!scene.getEngine().getCaps().standardDerivatives) {
- shaderName = "legacydefault";
- }
- var join = this._defines.toString();
- this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
- "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
- "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
- "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
- "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
- "vFogInfos", "vFogColor", "pointSize",
- "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
- "mBones",
- "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
- "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
- "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
- "logarithmicDepthConstant"
- ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
- "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
- ], join, fallbacks, this.onCompiled, this.onError);
- }
- if (!this._effect.isReady()) {
- return false;
- }
- this._renderId = scene.getRenderId();
- this._wasPreviouslyReady = true;
- if (mesh) {
- if (!mesh._materialDefines) {
- mesh._materialDefines = new StandardMaterialDefines();
- }
- this._defines.cloneTo(mesh._materialDefines);
- }
- return true;
- };
- StandardMaterial.prototype.unbind = function () {
- if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
- this._effect.setTexture("reflection2DSampler", null);
- }
- if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
- this._effect.setTexture("refraction2DSampler", null);
- }
- _super.prototype.unbind.call(this);
- };
- StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- this._effect.setMatrix("world", world);
- };
- StandardMaterial.prototype.bind = function (world, mesh) {
- var scene = this.getScene();
- // Matrices
- this.bindOnlyWorldMatrix(world);
- // Bones
- StandardMaterial.BindBonesParameters(mesh, this._effect);
- if (scene.getCachedMaterial() !== this) {
- this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- if (StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
- this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
- this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
- }
- if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
- this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
- this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
- this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
- this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
- }
- }
- // Textures
- if (scene.texturesEnabled) {
- if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- this._effect.setTexture("diffuseSampler", this.diffuseTexture);
- this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
- this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
- }
- if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- this._effect.setTexture("ambientSampler", this.ambientTexture);
- this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
- this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
- }
- if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- this._effect.setTexture("opacitySampler", this.opacityTexture);
- this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
- this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
- }
- if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (this.reflectionTexture.isCube) {
- this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
- }
- else {
- this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
- }
- this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
- this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
- }
- if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- this._effect.setTexture("emissiveSampler", this.emissiveTexture);
- this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
- this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
- }
- if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- this._effect.setTexture("lightmapSampler", this.lightmapTexture);
- this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
- this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
- }
- if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
- this._effect.setTexture("specularSampler", this.specularTexture);
- this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
- this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
- }
- if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
- this._effect.setTexture("bumpSampler", this.bumpTexture);
- this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
- this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
- }
- if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- var depth = 1.0;
- if (this.refractionTexture.isCube) {
- this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
- }
- else {
- this._effect.setTexture("refraction2DSampler", this.refractionTexture);
- this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
- if (this.refractionTexture.depth) {
- depth = this.refractionTexture.depth;
- }
- }
- this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
- }
- }
- // Clip plane
- if (scene.clipPlane) {
- var clipPlane = scene.clipPlane;
- this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
- }
- // Point size
- if (this.pointsCloud) {
- this._effect.setFloat("pointSize", this.pointSize);
- }
- // Colors
- scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
- this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
- this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
- if (this._defines.SPECULARTERM) {
- this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
- }
- this._effect.setColor3("vEmissiveColor", this.emissiveColor);
- }
- if (scene.getCachedMaterial() !== this || !this.isFrozen) {
- // Diffuse
- this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
- // Lights
- if (scene.lightsEnabled && !this.disableLighting) {
- StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
- }
- // View
- if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
- this._effect.setMatrix("view", scene.getViewMatrix());
- }
- // Fog
- StandardMaterial.BindFogParameters(scene, mesh, this._effect);
- // Log. depth
- if (this._defines.LOGARITHMICDEPTH) {
- this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
- }
- }
- _super.prototype.bind.call(this, world, mesh);
- };
- StandardMaterial.BindFogParameters = function (scene, mesh, effect) {
- if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
- effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
- effect.setColor3("vFogColor", scene.fogColor);
- }
- };
- StandardMaterial.BindBonesParameters = function (mesh, effect) {
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- };
- StandardMaterial.prototype.getAnimatables = function () {
- var results = [];
- if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
- results.push(this.diffuseTexture);
- }
- if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
- results.push(this.ambientTexture);
- }
- if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
- results.push(this.opacityTexture);
- }
- if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
- results.push(this.reflectionTexture);
- }
- if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
- results.push(this.emissiveTexture);
- }
- if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
- results.push(this.specularTexture);
- }
- if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
- results.push(this.bumpTexture);
- }
- if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
- results.push(this.lightmapTexture);
- }
- if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
- results.push(this.refractionTexture);
- }
- return results;
- };
- StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
- if (this.diffuseTexture) {
- this.diffuseTexture.dispose();
- }
- if (this.ambientTexture) {
- this.ambientTexture.dispose();
- }
- if (this.opacityTexture) {
- this.opacityTexture.dispose();
- }
- if (this.reflectionTexture) {
- this.reflectionTexture.dispose();
- }
- if (this.emissiveTexture) {
- this.emissiveTexture.dispose();
- }
- if (this.specularTexture) {
- this.specularTexture.dispose();
- }
- if (this.bumpTexture) {
- this.bumpTexture.dispose();
- }
- if (this.lightmapTexture) {
- this.lightmapTexture.dispose();
- }
- if (this.refractionTexture) {
- this.refractionTexture.dispose();
- }
- _super.prototype.dispose.call(this, forceDisposeEffect);
- };
- StandardMaterial.prototype.clone = function (name) {
- var newStandardMaterial = new StandardMaterial(name, this.getScene());
- // Base material
- this.copyTo(newStandardMaterial);
- // Standard material
- if (this.diffuseTexture && this.diffuseTexture.clone) {
- newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
- }
- if (this.ambientTexture && this.ambientTexture.clone) {
- newStandardMaterial.ambientTexture = this.ambientTexture.clone();
- }
- if (this.opacityTexture && this.opacityTexture.clone) {
- newStandardMaterial.opacityTexture = this.opacityTexture.clone();
- }
- if (this.reflectionTexture && this.reflectionTexture.clone) {
- newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
- }
- if (this.emissiveTexture && this.emissiveTexture.clone) {
- newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
- }
- if (this.specularTexture && this.specularTexture.clone) {
- newStandardMaterial.specularTexture = this.specularTexture.clone();
- }
- if (this.bumpTexture && this.bumpTexture.clone) {
- newStandardMaterial.bumpTexture = this.bumpTexture.clone();
- }
- if (this.lightmapTexture && this.lightmapTexture.clone) {
- newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
- newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
- }
- if (this.refractionTexture && this.refractionTexture.clone) {
- newStandardMaterial.refractionTexture = this.refractionTexture.clone();
- }
- newStandardMaterial.ambientColor = this.ambientColor.clone();
- newStandardMaterial.diffuseColor = this.diffuseColor.clone();
- newStandardMaterial.specularColor = this.specularColor.clone();
- newStandardMaterial.specularPower = this.specularPower;
- newStandardMaterial.emissiveColor = this.emissiveColor.clone();
- newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
- newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
- newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
- newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
- newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
- newStandardMaterial.roughness = this.roughness;
- newStandardMaterial.indexOfRefraction = this.indexOfRefraction;
- newStandardMaterial.invertRefractionY = this.invertRefractionY;
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
- newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
- newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
- }
- if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
- newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
- newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
- newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
- }
- return newStandardMaterial;
- };
- StandardMaterial.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.ambient = this.ambientColor.asArray();
- serializationObject.diffuse = this.diffuseColor.asArray();
- serializationObject.specular = this.specularColor.asArray();
- serializationObject.specularPower = this.specularPower;
- serializationObject.emissive = this.emissiveColor.asArray();
- serializationObject.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
- serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
- serializationObject.indexOfRefraction = this.indexOfRefraction;
- serializationObject.invertRefractionY = this.invertRefractionY;
- if (this.diffuseTexture) {
- serializationObject.diffuseTexture = this.diffuseTexture.serialize();
- }
- if (this.diffuseFresnelParameters) {
- serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
- }
- if (this.ambientTexture) {
- serializationObject.ambientTexture = this.ambientTexture.serialize();
- }
- if (this.opacityTexture) {
- serializationObject.opacityTexture = this.opacityTexture.serialize();
- }
- if (this.opacityFresnelParameters) {
- serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
- }
- if (this.reflectionTexture) {
- serializationObject.reflectionTexture = this.reflectionTexture.serialize();
- }
- if (this.reflectionFresnelParameters) {
- serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
- }
- if (this.refractionFresnelParameters) {
- serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
- }
- if (this.emissiveTexture) {
- serializationObject.emissiveTexture = this.emissiveTexture.serialize();
- }
- if (this.lightmapTexture) {
- serializationObject.lightmapTexture = this.lightmapTexture.serialize();
- serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
- }
- if (this.emissiveFresnelParameters) {
- serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
- }
- if (this.specularTexture) {
- serializationObject.specularTexture = this.specularTexture.serialize();
- }
- if (this.bumpTexture) {
- serializationObject.bumpTexture = this.bumpTexture.serialize();
- }
- if (this.refractionTexture) {
- serializationObject.refractionTexture = this.refractionTexture.serialize();
- }
- return serializationObject;
- };
- StandardMaterial.Parse = function (source, scene, rootUrl) {
- var material = new StandardMaterial(source.name, scene);
- material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
- material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
- material.specularColor = BABYLON.Color3.FromArray(source.specular);
- material.specularPower = source.specularPower;
- material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
- material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
- material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
- material.indexOfRefraction = source.indexOfRefraction;
- material.invertRefractionY = source.invertRefractionY;
- material.alpha = source.alpha;
- material.id = source.id;
- if (source.disableDepthWrite) {
- material.disableDepthWrite = source.disableDepthWrite;
- }
- BABYLON.Tags.AddTagsTo(material, source.tags);
- material.backFaceCulling = source.backFaceCulling;
- material.wireframe = source.wireframe;
- if (source.diffuseTexture) {
- material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
- }
- if (source.diffuseFresnelParameters) {
- material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
- }
- if (source.ambientTexture) {
- material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
- }
- if (source.opacityTexture) {
- material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
- }
- if (source.opacityFresnelParameters) {
- material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
- }
- if (source.reflectionTexture) {
- material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
- }
- if (source.reflectionFresnelParameters) {
- material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
- }
- if (source.refractionFresnelParameters) {
- material.refractionFresnelParameters = FresnelParameters.Parse(source.refractionFresnelParameters);
- }
- if (source.emissiveTexture) {
- material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
- }
- if (source.lightmapTexture) {
- material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
- material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
- }
- if (source.emissiveFresnelParameters) {
- material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
- }
- if (source.specularTexture) {
- material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
- }
- if (source.bumpTexture) {
- material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
- }
- if (source.refractionTexture) {
- material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
- }
- if (source.checkReadyOnlyOnce) {
- material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
- }
- return material;
- };
- StandardMaterial._scaledDiffuse = new BABYLON.Color3();
- StandardMaterial._scaledSpecular = new BABYLON.Color3();
- // Statics
- // Flags used to enable or disable a type of texture for all Standard Materials
- StandardMaterial.DiffuseTextureEnabled = true;
- StandardMaterial.AmbientTextureEnabled = true;
- StandardMaterial.OpacityTextureEnabled = true;
- StandardMaterial.ReflectionTextureEnabled = true;
- StandardMaterial.EmissiveTextureEnabled = true;
- StandardMaterial.SpecularTextureEnabled = true;
- StandardMaterial.BumpTextureEnabled = true;
- StandardMaterial.FresnelEnabled = true;
- StandardMaterial.LightmapTextureEnabled = true;
- StandardMaterial.RefractionTextureEnabled = true;
- return StandardMaterial;
- })(BABYLON.Material);
- BABYLON.StandardMaterial = StandardMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MultiMaterial = (function (_super) {
- __extends(MultiMaterial, _super);
- function MultiMaterial(name, scene) {
- _super.call(this, name, scene, true);
- this.subMaterials = new Array();
- scene.multiMaterials.push(this);
- }
- // Properties
- MultiMaterial.prototype.getSubMaterial = function (index) {
- if (index < 0 || index >= this.subMaterials.length) {
- return this.getScene().defaultMaterial;
- }
- return this.subMaterials[index];
- };
- // Methods
- MultiMaterial.prototype.isReady = function (mesh) {
- for (var index = 0; index < this.subMaterials.length; index++) {
- var subMaterial = this.subMaterials[index];
- if (subMaterial) {
- if (!this.subMaterials[index].isReady(mesh)) {
- return false;
- }
- }
- }
- return true;
- };
- MultiMaterial.prototype.clone = function (name, cloneChildren) {
- var newMultiMaterial = new MultiMaterial(name, this.getScene());
- for (var index = 0; index < this.subMaterials.length; index++) {
- var subMaterial = null;
- if (cloneChildren) {
- subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
- }
- else {
- subMaterial = this.subMaterials[index];
- }
- newMultiMaterial.subMaterials.push(subMaterial);
- }
- return newMultiMaterial;
- };
- MultiMaterial.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- serializationObject.materials = [];
- for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
- var subMat = this.subMaterials[matIndex];
- if (subMat) {
- serializationObject.materials.push(subMat.id);
- }
- else {
- serializationObject.materials.push(null);
- }
- }
- return serializationObject;
- };
- return MultiMaterial;
- })(BABYLON.Material);
- BABYLON.MultiMaterial = MultiMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SceneLoader = (function () {
- function SceneLoader() {
- }
- Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
- get: function () {
- return SceneLoader._ForceFullSceneLoadingForIncremental;
- },
- set: function (value) {
- SceneLoader._ForceFullSceneLoadingForIncremental = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
- get: function () {
- return SceneLoader._ShowLoadingScreen;
- },
- set: function (value) {
- SceneLoader._ShowLoadingScreen = value;
- },
- enumerable: true,
- configurable: true
- });
- SceneLoader._getPluginForFilename = function (sceneFilename) {
- var dotPosition = sceneFilename.lastIndexOf(".");
- var queryStringPosition = sceneFilename.indexOf("?");
- if (queryStringPosition === -1) {
- queryStringPosition = sceneFilename.length;
- }
- var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
- for (var index = 0; index < this._registeredPlugins.length; index++) {
- var plugin = this._registeredPlugins[index];
- if (plugin.extensions.indexOf(extension) !== -1) {
- return plugin;
- }
- }
- return this._registeredPlugins[this._registeredPlugins.length - 1];
- };
- // Public functions
- SceneLoader.GetPluginForExtension = function (extension) {
- for (var index = 0; index < this._registeredPlugins.length; index++) {
- var plugin = this._registeredPlugins[index];
- if (plugin.extensions.indexOf(extension) !== -1) {
- return plugin;
- }
- }
- return null;
- };
- SceneLoader.RegisterPlugin = function (plugin) {
- plugin.extensions = plugin.extensions.toLowerCase();
- SceneLoader._registeredPlugins.push(plugin);
- };
- SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
- if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
- BABYLON.Tools.Error("Wrong sceneFilename parameter");
- return;
- }
- var loadingToken = {};
- scene._addPendingData(loadingToken);
- var manifestChecked = function (success) {
- scene.database = database;
- var plugin = SceneLoader._getPluginForFilename(sceneFilename);
- var importMeshFromData = function (data) {
- var meshes = [];
- var particleSystems = [];
- var skeletons = [];
- try {
- if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
- if (onerror) {
- onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
- }
- scene._removePendingData(loadingToken);
- return;
- }
- }
- catch (e) {
- if (onerror) {
- onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
- }
- scene._removePendingData(loadingToken);
- return;
- }
- if (onsuccess) {
- scene.importedMeshesFiles.push(rootUrl + sceneFilename);
- onsuccess(meshes, particleSystems, skeletons);
- scene._removePendingData(loadingToken);
- }
- };
- if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
- // Direct load
- importMeshFromData(sceneFilename.substr(5));
- return;
- }
- BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
- importMeshFromData(data);
- }, progressCallBack, database);
- };
- if (scene.getEngine().enableOfflineSupport) {
- // Checking if a manifest file has been set for this scene and if offline mode has been requested
- var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
- }
- else {
- manifestChecked(true);
- }
- };
- /**
- * Load a scene
- * @param rootUrl a string that defines the root url for scene and resources
- * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
- * @param engine is the instance of BABYLON.Engine to use to create the scene
- */
- SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
- SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
- };
- /**
- * Append a scene
- * @param rootUrl a string that defines the root url for scene and resources
- * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
- * @param scene is the instance of BABYLON.Scene to append to
- */
- SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
- if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
- BABYLON.Tools.Error("Wrong sceneFilename parameter");
- return;
- }
- var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
- var database;
- var loadingToken = {};
- scene._addPendingData(loadingToken);
- if (SceneLoader.ShowLoadingScreen) {
- scene.getEngine().displayLoadingUI();
- }
- var loadSceneFromData = function (data) {
- scene.database = database;
- if (!plugin.load(scene, data, rootUrl)) {
- if (onerror) {
- onerror(scene);
- }
- scene._removePendingData(loadingToken);
- scene.getEngine().hideLoadingUI();
- return;
- }
- if (onsuccess) {
- onsuccess(scene);
- }
- scene._removePendingData(loadingToken);
- if (SceneLoader.ShowLoadingScreen) {
- scene.executeWhenReady(function () {
- scene.getEngine().hideLoadingUI();
- });
- }
- };
- var manifestChecked = function (success) {
- BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
- };
- if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
- // Direct load
- loadSceneFromData(sceneFilename.substr(5));
- return;
- }
- if (rootUrl.indexOf("file:") === -1) {
- if (scene.getEngine().enableOfflineSupport) {
- // Checking if a manifest file has been set for this scene and if offline mode has been requested
- database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
- }
- else {
- manifestChecked(true);
- }
- }
- else {
- BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
- }
- };
- // Flags
- SceneLoader._ForceFullSceneLoadingForIncremental = false;
- SceneLoader._ShowLoadingScreen = true;
- // Members
- SceneLoader._registeredPlugins = new Array();
- return SceneLoader;
- })();
- BABYLON.SceneLoader = SceneLoader;
- ;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var parseMaterialById = function (id, parsedData, scene, rootUrl) {
- for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
- var parsedMaterial = parsedData.materials[index];
- if (parsedMaterial.id === id) {
- return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
- }
- }
- return null;
- };
- var isDescendantOf = function (mesh, names, hierarchyIds) {
- names = (names instanceof Array) ? names : [names];
- for (var i in names) {
- if (mesh.name === names[i]) {
- hierarchyIds.push(mesh.id);
- return true;
- }
- }
- if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
- hierarchyIds.push(mesh.id);
- return true;
- }
- return false;
- };
- BABYLON.SceneLoader.RegisterPlugin({
- extensions: ".babylon",
- importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
- var parsedData = JSON.parse(data);
- var loadedSkeletonsIds = [];
- var loadedMaterialsIds = [];
- var hierarchyIds = [];
- var index;
- var cache;
- for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
- var parsedMesh = parsedData.meshes[index];
- if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
- if (meshesNames instanceof Array) {
- // Remove found mesh name from list.
- delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
- }
- //Geometry?
- if (parsedMesh.geometryId) {
- //does the file contain geometries?
- if (parsedData.geometries) {
- //find the correct geometry and add it to the scene
- var found = false;
- ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
- if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
- return;
- }
- else {
- parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
- if (parsedGeometryData.id === parsedMesh.geometryId) {
- switch (geometryType) {
- case "boxes":
- BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
- break;
- case "spheres":
- BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
- break;
- case "cylinders":
- BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
- break;
- case "toruses":
- BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
- break;
- case "grounds":
- BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
- break;
- case "planes":
- BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
- break;
- case "torusKnots":
- BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
- break;
- case "vertexData":
- BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
- break;
- }
- found = true;
- }
- });
- }
- });
- if (!found) {
- BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
- }
- }
- }
- // Material ?
- if (parsedMesh.materialId) {
- var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
- if (!materialFound && parsedData.multiMaterials) {
- for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
- var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
- if (parsedMultiMaterial.id === parsedMesh.materialId) {
- for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
- var subMatId = parsedMultiMaterial.materials[matIndex];
- loadedMaterialsIds.push(subMatId);
- parseMaterialById(subMatId, parsedData, scene, rootUrl);
- }
- loadedMaterialsIds.push(parsedMultiMaterial.id);
- BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
- materialFound = true;
- break;
- }
- }
- }
- if (!materialFound) {
- loadedMaterialsIds.push(parsedMesh.materialId);
- if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
- BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
- }
- }
- }
- // Skeleton ?
- if (parsedMesh.skeletonId > -1 && scene.skeletons) {
- var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
- if (!skeletonAlreadyLoaded) {
- for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
- var parsedSkeleton = parsedData.skeletons[skeletonIndex];
- if (parsedSkeleton.id === parsedMesh.skeletonId) {
- skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
- loadedSkeletonsIds.push(parsedSkeleton.id);
- }
- }
- }
- }
- var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
- meshes.push(mesh);
- }
- }
- // Connecting parents
- var currentMesh;
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- currentMesh = scene.meshes[index];
- if (currentMesh._waitingParentId) {
- currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
- currentMesh._waitingParentId = undefined;
- }
- }
- // freeze and compute world matrix application
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- currentMesh = scene.meshes[index];
- if (currentMesh._waitingFreezeWorldMatrix) {
- currentMesh.freezeWorldMatrix();
- currentMesh._waitingFreezeWorldMatrix = undefined;
- }
- else {
- currentMesh.computeWorldMatrix(true);
- }
- }
- // Particles
- if (parsedData.particleSystems) {
- for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
- var parsedParticleSystem = parsedData.particleSystems[index];
- if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
- particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
- }
- }
- }
- return true;
- },
- load: function (scene, data, rootUrl) {
- var parsedData = JSON.parse(data);
- // Scene
- scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
- scene.autoClear = parsedData.autoClear;
- scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
- scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
- if (parsedData.gravity) {
- scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
- }
- // Fog
- if (parsedData.fogMode && parsedData.fogMode !== 0) {
- scene.fogMode = parsedData.fogMode;
- scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
- scene.fogStart = parsedData.fogStart;
- scene.fogEnd = parsedData.fogEnd;
- scene.fogDensity = parsedData.fogDensity;
- }
- //Physics
- if (parsedData.physicsEnabled) {
- var physicsPlugin;
- if (parsedData.physicsEngine === "cannon") {
- physicsPlugin = new BABYLON.CannonJSPlugin();
- }
- else if (parsedData.physicsEngine === "oimo") {
- physicsPlugin = new BABYLON.OimoJSPlugin();
- }
- //else - default engine, which is currently oimo
- var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
- scene.enablePhysics(physicsGravity, physicsPlugin);
- }
- //collisions, if defined. otherwise, default is true
- if (parsedData.collisionsEnabled != undefined) {
- scene.collisionsEnabled = parsedData.collisionsEnabled;
- }
- scene.workerCollisions = !!parsedData.workerCollisions;
- var index;
- var cache;
- // Lights
- for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
- var parsedLight = parsedData.lights[index];
- BABYLON.Light.Parse(parsedLight, scene);
- }
- // Animations
- if (parsedData.animations) {
- for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
- var parsedAnimation = parsedData.animations[index];
- scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- // Materials
- if (parsedData.materials) {
- for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
- var parsedMaterial = parsedData.materials[index];
- BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
- }
- }
- if (parsedData.multiMaterials) {
- for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
- var parsedMultiMaterial = parsedData.multiMaterials[index];
- BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
- }
- }
- // Skeletons
- if (parsedData.skeletons) {
- for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
- var parsedSkeleton = parsedData.skeletons[index];
- BABYLON.Skeleton.Parse(parsedSkeleton, scene);
- }
- }
- // Geometries
- var geometries = parsedData.geometries;
- if (geometries) {
- // Boxes
- var boxes = geometries.boxes;
- if (boxes) {
- for (index = 0, cache = boxes.length; index < cache; index++) {
- var parsedBox = boxes[index];
- BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
- }
- }
- // Spheres
- var spheres = geometries.spheres;
- if (spheres) {
- for (index = 0, cache = spheres.length; index < cache; index++) {
- var parsedSphere = spheres[index];
- BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
- }
- }
- // Cylinders
- var cylinders = geometries.cylinders;
- if (cylinders) {
- for (index = 0, cache = cylinders.length; index < cache; index++) {
- var parsedCylinder = cylinders[index];
- BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
- }
- }
- // Toruses
- var toruses = geometries.toruses;
- if (toruses) {
- for (index = 0, cache = toruses.length; index < cache; index++) {
- var parsedTorus = toruses[index];
- BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
- }
- }
- // Grounds
- var grounds = geometries.grounds;
- if (grounds) {
- for (index = 0, cache = grounds.length; index < cache; index++) {
- var parsedGround = grounds[index];
- BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
- }
- }
- // Planes
- var planes = geometries.planes;
- if (planes) {
- for (index = 0, cache = planes.length; index < cache; index++) {
- var parsedPlane = planes[index];
- BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
- }
- }
- // TorusKnots
- var torusKnots = geometries.torusKnots;
- if (torusKnots) {
- for (index = 0, cache = torusKnots.length; index < cache; index++) {
- var parsedTorusKnot = torusKnots[index];
- BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
- }
- }
- // VertexData
- var vertexData = geometries.vertexData;
- if (vertexData) {
- for (index = 0, cache = vertexData.length; index < cache; index++) {
- var parsedVertexData = vertexData[index];
- BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
- }
- }
- }
- // Meshes
- for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
- var parsedMesh = parsedData.meshes[index];
- BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
- }
- // Cameras
- for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
- var parsedCamera = parsedData.cameras[index];
- BABYLON.Camera.Parse(parsedCamera, scene);
- }
- if (parsedData.activeCameraID) {
- scene.setActiveCameraByID(parsedData.activeCameraID);
- }
- // Browsing all the graph to connect the dots
- for (index = 0, cache = scene.cameras.length; index < cache; index++) {
- var camera = scene.cameras[index];
- if (camera._waitingParentId) {
- camera.parent = scene.getLastEntryByID(camera._waitingParentId);
- camera._waitingParentId = undefined;
- }
- }
- for (index = 0, cache = scene.lights.length; index < cache; index++) {
- var light = scene.lights[index];
- if (light._waitingParentId) {
- light.parent = scene.getLastEntryByID(light._waitingParentId);
- light._waitingParentId = undefined;
- }
- }
- // Sounds
- var loadedSounds = [];
- var loadedSound;
- if (BABYLON.AudioEngine && parsedData.sounds) {
- for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
- var parsedSound = parsedData.sounds[index];
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (!parsedSound.url)
- parsedSound.url = parsedSound.name;
- if (!loadedSounds[parsedSound.url]) {
- loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
- loadedSounds[parsedSound.url] = loadedSound;
- }
- else {
- BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
- }
- }
- else {
- var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
- }
- }
- }
- loadedSounds = [];
- // Connect parents & children and parse actions
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- var mesh = scene.meshes[index];
- if (mesh._waitingParentId) {
- mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
- mesh._waitingParentId = undefined;
- }
- if (mesh._waitingActions) {
- BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
- mesh._waitingActions = undefined;
- }
- }
- // freeze world matrix application
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- var currentMesh = scene.meshes[index];
- if (currentMesh._waitingFreezeWorldMatrix) {
- currentMesh.freezeWorldMatrix();
- currentMesh._waitingFreezeWorldMatrix = undefined;
- }
- else {
- currentMesh.computeWorldMatrix(true);
- }
- }
- // Particles Systems
- if (parsedData.particleSystems) {
- for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
- var parsedParticleSystem = parsedData.particleSystems[index];
- BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
- }
- }
- // Lens flares
- if (parsedData.lensFlareSystems) {
- for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
- var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
- BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
- }
- }
- // Shadows
- if (parsedData.shadowGenerators) {
- for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
- var parsedShadowGenerator = parsedData.shadowGenerators[index];
- BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
- }
- }
- // Actions (scene)
- if (parsedData.actions) {
- BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
- }
- // Finish
- return true;
- }
- });
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SpriteManager = (function () {
- function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- this.name = name;
- this.cellSize = cellSize;
- this.sprites = new Array();
- this.renderingGroupId = 0;
- this.layerMask = 0x0FFFFFFF;
- this.fogEnabled = true;
- this.isPickable = false;
- this._vertexDeclaration = [4, 4, 4, 4];
- this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
- this._capacity = capacity;
- this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
- this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._epsilon = epsilon === undefined ? 0.01 : epsilon;
- this._scene = scene;
- this._scene.spriteManagers.push(this);
- // VBO
- this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
- var indices = [];
- var index = 0;
- for (var count = 0; count < capacity; count++) {
- indices.push(index);
- indices.push(index + 1);
- indices.push(index + 2);
- indices.push(index);
- indices.push(index + 2);
- indices.push(index + 3);
- index += 4;
- }
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- this._vertices = new Float32Array(capacity * this._vertexStrideSize);
- // Effects
- this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
- this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
- }
- SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
- var arrayOffset = index * 16;
- if (offsetX === 0)
- offsetX = this._epsilon;
- else if (offsetX === 1)
- offsetX = 1 - this._epsilon;
- if (offsetY === 0)
- offsetY = this._epsilon;
- else if (offsetY === 1)
- offsetY = 1 - this._epsilon;
- this._vertices[arrayOffset] = sprite.position.x;
- this._vertices[arrayOffset + 1] = sprite.position.y;
- this._vertices[arrayOffset + 2] = sprite.position.z;
- this._vertices[arrayOffset + 3] = sprite.angle;
- this._vertices[arrayOffset + 4] = sprite.width;
- this._vertices[arrayOffset + 5] = sprite.height;
- this._vertices[arrayOffset + 6] = offsetX;
- this._vertices[arrayOffset + 7] = offsetY;
- this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
- this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
- var offset = (sprite.cellIndex / rowSize) >> 0;
- this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
- this._vertices[arrayOffset + 11] = offset;
- // Color
- this._vertices[arrayOffset + 12] = sprite.color.r;
- this._vertices[arrayOffset + 13] = sprite.color.g;
- this._vertices[arrayOffset + 14] = sprite.color.b;
- this._vertices[arrayOffset + 15] = sprite.color.a;
- };
- SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
- var count = Math.min(this._capacity, this.sprites.length);
- var min = BABYLON.Vector3.Zero();
- var max = BABYLON.Vector3.Zero();
- var distance = Number.MAX_VALUE;
- var currentSprite;
- var cameraSpacePosition = BABYLON.Vector3.Zero();
- var cameraView = camera.getViewMatrix();
- for (var index = 0; index < count; index++) {
- var sprite = this.sprites[index];
- if (!sprite) {
- continue;
- }
- if (predicate) {
- if (!predicate(sprite)) {
- continue;
- }
- }
- else if (!sprite.isPickable) {
- continue;
- }
- BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
- min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
- max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
- if (ray.intersectsBoxMinMax(min, max)) {
- var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
- if (distance > currentDistance) {
- distance = currentDistance;
- currentSprite = sprite;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- if (currentSprite) {
- var result = new BABYLON.PickingInfo();
- result.hit = true;
- result.pickedSprite = currentSprite;
- result.distance = distance;
- return result;
- }
- return null;
- };
- SpriteManager.prototype.render = function () {
- // Check
- if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
- return;
- var engine = this._scene.getEngine();
- var baseSize = this._spriteTexture.getBaseSize();
- // Sprites
- var deltaTime = engine.getDeltaTime();
- var max = Math.min(this._capacity, this.sprites.length);
- var rowSize = baseSize.width / this.cellSize;
- var offset = 0;
- for (var index = 0; index < max; index++) {
- var sprite = this.sprites[index];
- if (!sprite) {
- continue;
- }
- sprite._animate(deltaTime);
- this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
- this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
- this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
- this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
- }
- engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
- // Render
- var effect = this._effectBase;
- if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- effect = this._effectFog;
- }
- engine.enableEffect(effect);
- var viewMatrix = this._scene.getViewMatrix();
- effect.setTexture("diffuseSampler", this._spriteTexture);
- effect.setMatrix("view", viewMatrix);
- effect.setMatrix("projection", this._scene.getProjectionMatrix());
- effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
- // Fog
- if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
- effect.setColor3("vFogColor", this._scene.fogColor);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.setDepthFunctionToLessOrEqual();
- effect.setBool("alphaTest", true);
- engine.setColorWrite(false);
- engine.draw(true, 0, max * 6);
- engine.setColorWrite(true);
- effect.setBool("alphaTest", false);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- engine.draw(true, 0, max * 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- };
- SpriteManager.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this._spriteTexture) {
- this._spriteTexture.dispose();
- this._spriteTexture = null;
- }
- // Remove from scene
- var index = this._scene.spriteManagers.indexOf(this);
- this._scene.spriteManagers.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- return SpriteManager;
- })();
- BABYLON.SpriteManager = SpriteManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Sprite = (function () {
- function Sprite(name, manager) {
- this.name = name;
- this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.width = 1.0;
- this.height = 1.0;
- this.angle = 0;
- this.cellIndex = 0;
- this.invertU = 0;
- this.invertV = 0;
- this.animations = new Array();
- this.isPickable = false;
- this._animationStarted = false;
- this._loopAnimation = false;
- this._fromIndex = 0;
- this._toIndex = 0;
- this._delay = 0;
- this._direction = 1;
- this._frameCount = 0;
- this._time = 0;
- this._manager = manager;
- this._manager.sprites.push(this);
- this.position = BABYLON.Vector3.Zero();
- }
- Object.defineProperty(Sprite.prototype, "size", {
- get: function () {
- return this.width;
- },
- set: function (value) {
- this.width = value;
- this.height = value;
- },
- enumerable: true,
- configurable: true
- });
- Sprite.prototype.playAnimation = function (from, to, loop, delay) {
- this._fromIndex = from;
- this._toIndex = to;
- this._loopAnimation = loop;
- this._delay = delay;
- this._animationStarted = true;
- this._direction = from < to ? 1 : -1;
- this.cellIndex = from;
- this._time = 0;
- };
- Sprite.prototype.stopAnimation = function () {
- this._animationStarted = false;
- };
- Sprite.prototype._animate = function (deltaTime) {
- if (!this._animationStarted)
- return;
- this._time += deltaTime;
- if (this._time > this._delay) {
- this._time = this._time % this._delay;
- this.cellIndex += this._direction;
- if (this.cellIndex == this._toIndex) {
- if (this._loopAnimation) {
- this.cellIndex = this._fromIndex;
- }
- else {
- this._animationStarted = false;
- if (this.disposeWhenFinishedAnimating) {
- this.dispose();
- }
- }
- }
- }
- };
- Sprite.prototype.dispose = function () {
- for (var i = 0; i < this._manager.sprites.length; i++) {
- if (this._manager.sprites[i] == this) {
- this._manager.sprites.splice(i, 1);
- }
- }
- };
- return Sprite;
- })();
- BABYLON.Sprite = Sprite;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Layer = (function () {
- function Layer(name, imgUrl, scene, isBackground, color) {
- this.name = name;
- this.scale = new BABYLON.Vector2(1, 1);
- this.offset = new BABYLON.Vector2(0, 0);
- this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
- this.isBackground = isBackground === undefined ? true : isBackground;
- this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
- this._scene = scene;
- this._scene.layers.push(this);
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- // Effects
- this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
- }
- Layer.prototype.render = function () {
- // Check
- if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
- return;
- var engine = this._scene.getEngine();
- // Render
- engine.enableEffect(this._effect);
- engine.setState(false);
- // Texture
- this._effect.setTexture("textureSampler", this.texture);
- this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
- // Color
- this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
- // Scale / offset
- this._effect.setVector2("offset", this.offset);
- this._effect.setVector2("scale", this.scale);
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
- // Draw order
- engine.setAlphaMode(this.alphaBlendingMode);
- engine.draw(true, 0, 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- };
- Layer.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this.texture) {
- this.texture.dispose();
- this.texture = null;
- }
- // Remove from scene
- var index = this._scene.layers.indexOf(this);
- this._scene.layers.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- return Layer;
- })();
- BABYLON.Layer = Layer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Particle = (function () {
- function Particle() {
- this.position = BABYLON.Vector3.Zero();
- this.direction = BABYLON.Vector3.Zero();
- this.color = new BABYLON.Color4(0, 0, 0, 0);
- this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
- this.lifeTime = 1.0;
- this.age = 0;
- this.size = 0;
- this.angle = 0;
- this.angularSpeed = 0;
- }
- Particle.prototype.copyTo = function (other) {
- other.position.copyFrom(this.position);
- other.direction.copyFrom(this.direction);
- other.color.copyFrom(this.color);
- other.colorStep.copyFrom(this.colorStep);
- other.lifeTime = this.lifeTime;
- other.age = this.age;
- other.size = this.size;
- other.angle = this.angle;
- other.angularSpeed = this.angularSpeed;
- };
- return Particle;
- })();
- BABYLON.Particle = Particle;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var randomNumber = function (min, max) {
- if (min === max) {
- return (min);
- }
- var random = Math.random();
- return ((random * (max - min)) + min);
- };
- var ParticleSystem = (function () {
- function ParticleSystem(name, capacity, scene, customEffect) {
- var _this = this;
- this.name = name;
- // Members
- this.animations = [];
- this.renderingGroupId = 0;
- this.emitter = null;
- this.emitRate = 10;
- this.manualEmitCount = -1;
- this.updateSpeed = 0.01;
- this.targetStopDuration = 0;
- this.disposeOnStop = false;
- this.minEmitPower = 1;
- this.maxEmitPower = 1;
- this.minLifeTime = 1;
- this.maxLifeTime = 1;
- this.minSize = 1;
- this.maxSize = 1;
- this.minAngularSpeed = 0;
- this.maxAngularSpeed = 0;
- this.layerMask = 0x0FFFFFFF;
- this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
- this.forceDepthWrite = false;
- this.gravity = BABYLON.Vector3.Zero();
- this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
- this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
- this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
- this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
- this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
- this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.particles = new Array();
- this._vertexDeclaration = [3, 4, 4];
- this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
- this._stockParticles = new Array();
- this._newPartsExcess = 0;
- this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
- this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
- this._scaledDirection = BABYLON.Vector3.Zero();
- this._scaledGravity = BABYLON.Vector3.Zero();
- this._currentRenderId = -1;
- this._started = false;
- this._stopped = false;
- this._actualFrame = 0;
- this.id = name;
- this._capacity = capacity;
- this._scene = scene;
- this._customEffect = customEffect;
- scene.particleSystems.push(this);
- // VBO
- this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
- var indices = [];
- var index = 0;
- for (var count = 0; count < capacity; count++) {
- indices.push(index);
- indices.push(index + 1);
- indices.push(index + 2);
- indices.push(index);
- indices.push(index + 2);
- indices.push(index + 3);
- index += 4;
- }
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- this._vertices = new Float32Array(capacity * this._vertexStrideSize);
- // Default behaviors
- this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
- var randX = randomNumber(_this.direction1.x, _this.direction2.x);
- var randY = randomNumber(_this.direction1.y, _this.direction2.y);
- var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
- };
- this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
- var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
- var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
- var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
- };
- this.updateFunction = function (particles) {
- for (var index = 0; index < particles.length; index++) {
- var particle = particles[index];
- particle.age += _this._scaledUpdateSpeed;
- if (particle.age >= particle.lifeTime) {
- _this.recycleParticle(particle);
- index--;
- continue;
- }
- else {
- particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
- particle.color.addInPlace(_this._scaledColorStep);
- if (particle.color.a < 0)
- particle.color.a = 0;
- particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
- particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
- particle.position.addInPlace(_this._scaledDirection);
- _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
- particle.direction.addInPlace(_this._scaledGravity);
- }
- }
- };
- }
- ParticleSystem.prototype.recycleParticle = function (particle) {
- var lastParticle = this.particles.pop();
- if (lastParticle !== particle) {
- lastParticle.copyTo(particle);
- this._stockParticles.push(lastParticle);
- }
- };
- ParticleSystem.prototype.getCapacity = function () {
- return this._capacity;
- };
- ParticleSystem.prototype.isAlive = function () {
- return this._alive;
- };
- ParticleSystem.prototype.isStarted = function () {
- return this._started;
- };
- ParticleSystem.prototype.start = function () {
- this._started = true;
- this._stopped = false;
- this._actualFrame = 0;
- };
- ParticleSystem.prototype.stop = function () {
- this._stopped = true;
- };
- ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
- var offset = index * 11;
- this._vertices[offset] = particle.position.x;
- this._vertices[offset + 1] = particle.position.y;
- this._vertices[offset + 2] = particle.position.z;
- this._vertices[offset + 3] = particle.color.r;
- this._vertices[offset + 4] = particle.color.g;
- this._vertices[offset + 5] = particle.color.b;
- this._vertices[offset + 6] = particle.color.a;
- this._vertices[offset + 7] = particle.angle;
- this._vertices[offset + 8] = particle.size;
- this._vertices[offset + 9] = offsetX;
- this._vertices[offset + 10] = offsetY;
- };
- ParticleSystem.prototype._update = function (newParticles) {
- // Update current
- this._alive = this.particles.length > 0;
- this.updateFunction(this.particles);
- // Add new ones
- var worldMatrix;
- if (this.emitter.position) {
- worldMatrix = this.emitter.getWorldMatrix();
- }
- else {
- worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
- }
- var particle;
- for (var index = 0; index < newParticles; index++) {
- if (this.particles.length === this._capacity) {
- break;
- }
- if (this._stockParticles.length !== 0) {
- particle = this._stockParticles.pop();
- particle.age = 0;
- }
- else {
- particle = new BABYLON.Particle();
- }
- this.particles.push(particle);
- var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
- this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
- particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
- particle.size = randomNumber(this.minSize, this.maxSize);
- particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
- this.startPositionFunction(worldMatrix, particle.position, particle);
- var step = randomNumber(0, 1.0);
- BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
- this.colorDead.subtractToRef(particle.color, this._colorDiff);
- this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
- }
- };
- ParticleSystem.prototype._getEffect = function () {
- if (this._customEffect) {
- return this._customEffect;
- }
- ;
- var defines = [];
- if (this._scene.clipPlane) {
- defines.push("#define CLIPPLANE");
- }
- // Effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
- }
- return this._effect;
- };
- ParticleSystem.prototype.animate = function () {
- if (!this._started)
- return;
- var effect = this._getEffect();
- // Check
- if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
- return;
- if (this._currentRenderId === this._scene.getRenderId()) {
- return;
- }
- this._currentRenderId = this._scene.getRenderId();
- this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
- // determine the number of particles we need to create
- var newParticles;
- if (this.manualEmitCount > -1) {
- newParticles = this.manualEmitCount;
- this._newPartsExcess = 0;
- this.manualEmitCount = 0;
- }
- else {
- newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
- this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
- }
- if (this._newPartsExcess > 1.0) {
- newParticles += this._newPartsExcess >> 0;
- this._newPartsExcess -= this._newPartsExcess >> 0;
- }
- this._alive = false;
- if (!this._stopped) {
- this._actualFrame += this._scaledUpdateSpeed;
- if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
- this.stop();
- }
- else {
- newParticles = 0;
- }
- this._update(newParticles);
- // Stopped?
- if (this._stopped) {
- if (!this._alive) {
- this._started = false;
- if (this.disposeOnStop) {
- this._scene._toBeDisposed.push(this);
- }
- }
- }
- // Update VBO
- var offset = 0;
- for (var index = 0; index < this.particles.length; index++) {
- var particle = this.particles[index];
- this._appendParticleVertex(offset++, particle, 0, 0);
- this._appendParticleVertex(offset++, particle, 1, 0);
- this._appendParticleVertex(offset++, particle, 1, 1);
- this._appendParticleVertex(offset++, particle, 0, 1);
- }
- var engine = this._scene.getEngine();
- engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
- };
- ParticleSystem.prototype.render = function () {
- var effect = this._getEffect();
- // Check
- if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
- return 0;
- var engine = this._scene.getEngine();
- // Render
- engine.enableEffect(effect);
- engine.setState(false);
- var viewMatrix = this._scene.getViewMatrix();
- effect.setTexture("diffuseSampler", this.particleTexture);
- effect.setMatrix("view", viewMatrix);
- effect.setMatrix("projection", this._scene.getProjectionMatrix());
- effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
- if (this._scene.clipPlane) {
- var clipPlane = this._scene.clipPlane;
- var invView = viewMatrix.clone();
- invView.invert();
- effect.setMatrix("invView", invView);
- effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
- }
- else {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- }
- if (this.forceDepthWrite) {
- engine.setDepthWrite(true);
- }
- engine.draw(true, 0, this.particles.length * 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- return this.particles.length;
- };
- ParticleSystem.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this.particleTexture) {
- this.particleTexture.dispose();
- this.particleTexture = null;
- }
- // Remove from scene
- var index = this._scene.particleSystems.indexOf(this);
- this._scene.particleSystems.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- // Clone
- ParticleSystem.prototype.clone = function (name, newEmitter) {
- var result = new ParticleSystem(name, this._capacity, this._scene);
- BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
- if (newEmitter === undefined) {
- newEmitter = this.emitter;
- }
- result.emitter = newEmitter;
- if (this.particleTexture) {
- result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
- }
- result.start();
- return result;
- };
- ParticleSystem.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- // Emitter
- if (this.emitter.position) {
- serializationObject.emitterId = this.emitter.id;
- }
- else {
- serializationObject.emitter = this.emitter.asArray();
- ;
- }
- serializationObject.capacity = this.getCapacity();
- if (this.particleTexture) {
- serializationObject.textureName = this.particleTexture.name;
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- // Particle system
- serializationObject.minAngularSpeed = this.minAngularSpeed;
- serializationObject.maxAngularSpeed = this.maxAngularSpeed;
- serializationObject.minSize = this.minSize;
- serializationObject.maxSize = this.maxSize;
- serializationObject.minEmitPower = this.minEmitPower;
- serializationObject.maxEmitPower = this.maxEmitPower;
- serializationObject.minLifeTime = this.minLifeTime;
- serializationObject.maxLifeTime = this.maxLifeTime;
- serializationObject.emitRate = this.emitRate;
- serializationObject.minEmitBox = this.minEmitBox.asArray();
- serializationObject.maxEmitBox = this.maxEmitBox.asArray();
- serializationObject.gravity = this.gravity.asArray();
- serializationObject.direction1 = this.direction1.asArray();
- serializationObject.direction2 = this.direction2.asArray();
- serializationObject.color1 = this.color1.asArray();
- serializationObject.color2 = this.color2.asArray();
- serializationObject.colorDead = this.colorDead.asArray();
- serializationObject.updateSpeed = this.updateSpeed;
- serializationObject.targetStopDuration = this.targetStopDuration;
- serializationObject.textureMask = this.textureMask.asArray();
- serializationObject.blendMode = this.blendMode;
- return serializationObject;
- };
- ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
- var name = parsedParticleSystem.name;
- var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
- // Texture
- if (parsedParticleSystem.textureName) {
- particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
- particleSystem.particleTexture.name = parsedParticleSystem.textureName;
- }
- // Emitter
- if (parsedParticleSystem.emitterId) {
- particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
- }
- else {
- particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
- }
- // Animations
- if (parsedParticleSystem.animations) {
- for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
- var parsedAnimation = parsedParticleSystem.animations[animationIndex];
- particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- // Particle system
- particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
- particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
- particleSystem.minSize = parsedParticleSystem.minSize;
- particleSystem.maxSize = parsedParticleSystem.maxSize;
- particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
- particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
- particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
- particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
- particleSystem.emitRate = parsedParticleSystem.emitRate;
- particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
- particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
- particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
- particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
- particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
- particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
- particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
- particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
- particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
- particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
- particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
- particleSystem.blendMode = parsedParticleSystem.blendMode;
- particleSystem.start();
- return particleSystem;
- };
- // Statics
- ParticleSystem.BLENDMODE_ONEONE = 0;
- ParticleSystem.BLENDMODE_STANDARD = 1;
- return ParticleSystem;
- })();
- BABYLON.ParticleSystem = ParticleSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnimationRange = (function () {
- function AnimationRange(name, from, to) {
- this.name = name;
- this.from = from;
- this.to = to;
- }
- return AnimationRange;
- })();
- BABYLON.AnimationRange = AnimationRange;
- /**
- * Composed of a frame, and an action function
- */
- var AnimationEvent = (function () {
- function AnimationEvent(frame, action, onlyOnce) {
- this.frame = frame;
- this.action = action;
- this.onlyOnce = onlyOnce;
- this.isDone = false;
- }
- return AnimationEvent;
- })();
- BABYLON.AnimationEvent = AnimationEvent;
- var Animation = (function () {
- function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
- this.name = name;
- this.targetProperty = targetProperty;
- this.framePerSecond = framePerSecond;
- this.dataType = dataType;
- this.loopMode = loopMode;
- this._offsetsCache = {};
- this._highLimitsCache = {};
- this._stopped = false;
- // The set of event that will be linked to this animation
- this._events = new Array();
- this.allowMatricesInterpolation = false;
- this._ranges = {};
- this.targetPropertyPath = targetProperty.split(".");
- this.dataType = dataType;
- this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
- }
- Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
- var dataType = undefined;
- if (!isNaN(parseFloat(from)) && isFinite(from)) {
- dataType = Animation.ANIMATIONTYPE_FLOAT;
- }
- else if (from instanceof BABYLON.Quaternion) {
- dataType = Animation.ANIMATIONTYPE_QUATERNION;
- }
- else if (from instanceof BABYLON.Vector3) {
- dataType = Animation.ANIMATIONTYPE_VECTOR3;
- }
- else if (from instanceof BABYLON.Vector2) {
- dataType = Animation.ANIMATIONTYPE_VECTOR2;
- }
- else if (from instanceof BABYLON.Color3) {
- dataType = Animation.ANIMATIONTYPE_COLOR3;
- }
- if (dataType == undefined) {
- return null;
- }
- var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
- var keys = [];
- keys.push({ frame: 0, value: from });
- keys.push({ frame: totalFrame, value: to });
- animation.setKeys(keys);
- if (easingFunction !== undefined) {
- animation.setEasingFunction(easingFunction);
- }
- return animation;
- };
- Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
- return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
- };
- Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
- node.animations.push(animation);
- return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
- };
- // Methods
- /**
- * Add an event to this animation.
- */
- Animation.prototype.addEvent = function (event) {
- this._events.push(event);
- };
- /**
- * Remove all events found at the given frame
- * @param frame
- */
- Animation.prototype.removeEvents = function (frame) {
- for (var index = 0; index < this._events.length; index++) {
- if (this._events[index].frame === frame) {
- this._events.splice(index, 1);
- index--;
- }
- }
- };
- Animation.prototype.createRange = function (name, from, to) {
- // check name not already in use; could happen for bones after serialized
- if (!this._ranges[name]) {
- this._ranges[name] = new AnimationRange(name, from, to);
- }
- };
- Animation.prototype.deleteRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- if (this._ranges[name]) {
- if (deleteFrames) {
- var from = this._ranges[name].from;
- var to = this._ranges[name].to;
- // this loop MUST go high to low for multiple splices to work
- for (var key = this._keys.length - 1; key >= 0; key--) {
- if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
- this._keys.splice(key, 1);
- }
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- }
- };
- Animation.prototype.getRange = function (name) {
- return this._ranges[name];
- };
- Animation.prototype.reset = function () {
- this._offsetsCache = {};
- this._highLimitsCache = {};
- this.currentFrame = 0;
- };
- Animation.prototype.isStopped = function () {
- return this._stopped;
- };
- Animation.prototype.getKeys = function () {
- return this._keys;
- };
- Animation.prototype.getHighestFrame = function () {
- var ret = 0;
- for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
- if (ret < this._keys[key].frame) {
- ret = this._keys[key].frame;
- }
- }
- return ret;
- };
- Animation.prototype.getEasingFunction = function () {
- return this._easingFunction;
- };
- Animation.prototype.setEasingFunction = function (easingFunction) {
- this._easingFunction = easingFunction;
- };
- Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
- return startValue + (endValue - startValue) * gradient;
- };
- Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
- };
- Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Color3.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.clone = function () {
- var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
- if (this._keys) {
- clone.setKeys(this._keys);
- }
- return clone;
- };
- Animation.prototype.setKeys = function (values) {
- this._keys = values.slice(0);
- this._offsetsCache = {};
- this._highLimitsCache = {};
- };
- Animation.prototype._getKeyValue = function (value) {
- if (typeof value === "function") {
- return value();
- }
- return value;
- };
- Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
- if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
- return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
- }
- this.currentFrame = currentFrame;
- // Try to get a hash to find the right key
- var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
- if (this._keys[startKey].frame >= currentFrame) {
- while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
- startKey--;
- }
- }
- for (var key = startKey; key < this._keys.length; key++) {
- if (this._keys[key + 1].frame >= currentFrame) {
- var startValue = this._getKeyValue(this._keys[key].value);
- var endValue = this._getKeyValue(this._keys[key + 1].value);
- // gradient : percent of currentFrame between the frame inf and the frame sup
- var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
- // check for easingFunction and correction of gradient
- if (this._easingFunction != null) {
- gradient = this._easingFunction.ease(gradient);
- }
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.floatInterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
- }
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- var quaternion = null;
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
- break;
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- break;
- }
- return quaternion;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.vector3InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.vector2InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.color3InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Matrix
- case Animation.ANIMATIONTYPE_MATRIX:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- if (this.allowMatricesInterpolation) {
- return this.matrixInterpolateFunction(startValue, endValue, gradient);
- }
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return startValue;
- }
- default:
- break;
- }
- break;
- }
- }
- return this._getKeyValue(this._keys[this._keys.length - 1].value);
- };
- Animation.prototype.setValue = function (currentValue) {
- // Set value
- if (this.targetPropertyPath.length > 1) {
- var property = this._target[this.targetPropertyPath[0]];
- for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
- property = property[this.targetPropertyPath[index]];
- }
- property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
- }
- else {
- this._target[this.targetPropertyPath[0]] = currentValue;
- }
- if (this._target.markAsDirty) {
- this._target.markAsDirty(this.targetProperty);
- }
- };
- Animation.prototype.goToFrame = function (frame) {
- if (frame < this._keys[0].frame) {
- frame = this._keys[0].frame;
- }
- else if (frame > this._keys[this._keys.length - 1].frame) {
- frame = this._keys[this._keys.length - 1].frame;
- }
- var currentValue = this._interpolate(frame, 0, this.loopMode);
- this.setValue(currentValue);
- };
- Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
- if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
- this._stopped = true;
- return false;
- }
- var returnValue = true;
- // Adding a start key at frame 0 if missing
- if (this._keys[0].frame !== 0) {
- var newKey = { frame: 0, value: this._keys[0].value };
- this._keys.splice(0, 0, newKey);
- }
- // Check limits
- if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
- from = this._keys[0].frame;
- }
- if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
- to = this._keys[this._keys.length - 1].frame;
- }
- // Compute ratio
- var range = to - from;
- var offsetValue;
- // ratio represents the frame delta between from and to
- var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
- var highLimitValue = 0;
- if (ratio > range && !loop) {
- returnValue = false;
- highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
- }
- else {
- // Get max value if required
- if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
- var keyOffset = to.toString() + from.toString();
- if (!this._offsetsCache[keyOffset]) {
- var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
- var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- this._offsetsCache[keyOffset] = toValue - fromValue;
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- default:
- break;
- }
- this._highLimitsCache[keyOffset] = toValue;
- }
- highLimitValue = this._highLimitsCache[keyOffset];
- offsetValue = this._offsetsCache[keyOffset];
- }
- }
- if (offsetValue === undefined) {
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- offsetValue = 0;
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
- break;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- offsetValue = BABYLON.Vector3.Zero();
- break;
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- offsetValue = BABYLON.Vector2.Zero();
- break;
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- offsetValue = BABYLON.Color3.Black();
- }
- }
- // Compute value
- var repeatCount = (ratio / range) >> 0;
- var currentFrame = returnValue ? from + ratio % range : to;
- var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
- // Set value
- this.setValue(currentValue);
- // Check events
- for (var index = 0; index < this._events.length; index++) {
- if (currentFrame >= this._events[index].frame) {
- var event = this._events[index];
- if (!event.isDone) {
- // If event should be done only once, remove it.
- if (event.onlyOnce) {
- this._events.splice(index, 1);
- index--;
- }
- event.isDone = true;
- event.action();
- } // Don't do anything if the event has already be done.
- }
- else if (this._events[index].isDone && !this._events[index].onlyOnce) {
- // reset event, the animation is looping
- this._events[index].isDone = false;
- }
- }
- if (!returnValue) {
- this._stopped = true;
- }
- return returnValue;
- };
- Animation.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.property = this.targetProperty;
- serializationObject.framePerSecond = this.framePerSecond;
- serializationObject.dataType = this.dataType;
- serializationObject.loopBehavior = this.loopMode;
- var dataType = this.dataType;
- serializationObject.keys = [];
- var keys = this.getKeys();
- for (var index = 0; index < keys.length; index++) {
- var animationKey = keys[index];
- var key = {};
- key.frame = animationKey.frame;
- switch (dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- key.values = [animationKey.value];
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- case Animation.ANIMATIONTYPE_MATRIX:
- case Animation.ANIMATIONTYPE_VECTOR3:
- case Animation.ANIMATIONTYPE_COLOR3:
- key.values = animationKey.value.asArray();
- break;
- }
- serializationObject.keys.push(key);
- }
- serializationObject.ranges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationObject.ranges.push(range);
- }
- return serializationObject;
- };
- Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
- get: function () {
- return Animation._ANIMATIONTYPE_FLOAT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
- get: function () {
- return Animation._ANIMATIONTYPE_VECTOR3;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
- get: function () {
- return Animation._ANIMATIONTYPE_VECTOR2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
- get: function () {
- return Animation._ANIMATIONTYPE_QUATERNION;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
- get: function () {
- return Animation._ANIMATIONTYPE_MATRIX;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
- get: function () {
- return Animation._ANIMATIONTYPE_COLOR3;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_RELATIVE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_CYCLE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_CONSTANT;
- },
- enumerable: true,
- configurable: true
- });
- Animation.Parse = function (parsedAnimation) {
- var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
- var dataType = parsedAnimation.dataType;
- var keys = [];
- for (var index = 0; index < parsedAnimation.keys.length; index++) {
- var key = parsedAnimation.keys[index];
- var data;
- switch (dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- data = key.values[0];
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- data = BABYLON.Quaternion.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_MATRIX:
- data = BABYLON.Matrix.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_COLOR3:
- data = BABYLON.Color3.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_VECTOR3:
- default:
- data = BABYLON.Vector3.FromArray(key.values);
- break;
- }
- keys.push({
- frame: key.frame,
- value: data
- });
- }
- animation.setKeys(keys);
- if (parsedAnimation.ranges) {
- for (var index = 0; index < parsedAnimation.ranges.length; index++) {
- data = parsedAnimation.ranges[index];
- animation.createRange(data.name, data.from, data.to);
- }
- }
- return animation;
- };
- Animation.AppendSerializedAnimations = function (source, destination) {
- if (source.animations) {
- destination.animations = [];
- for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
- var animation = source.animations[animationIndex];
- destination.animations.push(animation.serialize());
- }
- }
- };
- // Statics
- Animation._ANIMATIONTYPE_FLOAT = 0;
- Animation._ANIMATIONTYPE_VECTOR3 = 1;
- Animation._ANIMATIONTYPE_QUATERNION = 2;
- Animation._ANIMATIONTYPE_MATRIX = 3;
- Animation._ANIMATIONTYPE_COLOR3 = 4;
- Animation._ANIMATIONTYPE_VECTOR2 = 5;
- Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
- Animation._ANIMATIONLOOPMODE_CYCLE = 1;
- Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
- return Animation;
- })();
- BABYLON.Animation = Animation;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Animatable = (function () {
- function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
- if (fromFrame === void 0) { fromFrame = 0; }
- if (toFrame === void 0) { toFrame = 100; }
- if (loopAnimation === void 0) { loopAnimation = false; }
- if (speedRatio === void 0) { speedRatio = 1.0; }
- this.target = target;
- this.fromFrame = fromFrame;
- this.toFrame = toFrame;
- this.loopAnimation = loopAnimation;
- this.speedRatio = speedRatio;
- this.onAnimationEnd = onAnimationEnd;
- this._animations = new Array();
- this._paused = false;
- this.animationStarted = false;
- if (animations) {
- this.appendAnimations(target, animations);
- }
- this._scene = scene;
- scene._activeAnimatables.push(this);
- }
- // Methods
- Animatable.prototype.getAnimations = function () {
- return this._animations;
- };
- Animatable.prototype.appendAnimations = function (target, animations) {
- for (var index = 0; index < animations.length; index++) {
- var animation = animations[index];
- animation._target = target;
- this._animations.push(animation);
- }
- };
- Animatable.prototype.getAnimationByTargetProperty = function (property) {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- if (animations[index].targetProperty === property) {
- return animations[index];
- }
- }
- return null;
- };
- Animatable.prototype.reset = function () {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].reset();
- }
- this._localDelayOffset = null;
- this._pausedDelay = null;
- };
- Animatable.prototype.goToFrame = function (frame) {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].goToFrame(frame);
- }
- };
- Animatable.prototype.pause = function () {
- if (this._paused) {
- return;
- }
- this._paused = true;
- };
- Animatable.prototype.restart = function () {
- this._paused = false;
- };
- Animatable.prototype.stop = function () {
- var index = this._scene._activeAnimatables.indexOf(this);
- if (index > -1) {
- this._scene._activeAnimatables.splice(index, 1);
- }
- if (this.onAnimationEnd) {
- this.onAnimationEnd();
- }
- };
- Animatable.prototype._animate = function (delay) {
- if (this._paused) {
- this.animationStarted = false;
- if (!this._pausedDelay) {
- this._pausedDelay = delay;
- }
- return true;
- }
- if (!this._localDelayOffset) {
- this._localDelayOffset = delay;
- }
- else if (this._pausedDelay) {
- this._localDelayOffset += delay - this._pausedDelay;
- this._pausedDelay = null;
- }
- // Animating
- var running = false;
- var animations = this._animations;
- var index;
- for (index = 0; index < animations.length; index++) {
- var animation = animations[index];
- var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
- running = running || isRunning;
- }
- this.animationStarted = running;
- if (!running) {
- // Remove from active animatables
- index = this._scene._activeAnimatables.indexOf(this);
- this._scene._activeAnimatables.splice(index, 1);
- }
- if (!running && this.onAnimationEnd) {
- this.onAnimationEnd();
- }
- return running;
- };
- return Animatable;
- })();
- BABYLON.Animatable = Animatable;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var EasingFunction = (function () {
- function EasingFunction() {
- // Properties
- this._easingMode = EasingFunction.EASINGMODE_EASEIN;
- }
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEIN;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEOUT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEINOUT;
- },
- enumerable: true,
- configurable: true
- });
- EasingFunction.prototype.setEasingMode = function (easingMode) {
- var n = Math.min(Math.max(easingMode, 0), 2);
- this._easingMode = n;
- };
- EasingFunction.prototype.getEasingMode = function () {
- return this._easingMode;
- };
- EasingFunction.prototype.easeInCore = function (gradient) {
- throw new Error('You must implement this method');
- };
- EasingFunction.prototype.ease = function (gradient) {
- switch (this._easingMode) {
- case EasingFunction.EASINGMODE_EASEIN:
- return this.easeInCore(gradient);
- case EasingFunction.EASINGMODE_EASEOUT:
- return (1 - this.easeInCore(1 - gradient));
- }
- if (gradient >= 0.5) {
- return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
- }
- return (this.easeInCore(gradient * 2) * 0.5);
- };
- //Statics
- EasingFunction._EASINGMODE_EASEIN = 0;
- EasingFunction._EASINGMODE_EASEOUT = 1;
- EasingFunction._EASINGMODE_EASEINOUT = 2;
- return EasingFunction;
- })();
- BABYLON.EasingFunction = EasingFunction;
- var CircleEase = (function (_super) {
- __extends(CircleEase, _super);
- function CircleEase() {
- _super.apply(this, arguments);
- }
- CircleEase.prototype.easeInCore = function (gradient) {
- gradient = Math.max(0, Math.min(1, gradient));
- return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
- };
- return CircleEase;
- })(EasingFunction);
- BABYLON.CircleEase = CircleEase;
- var BackEase = (function (_super) {
- __extends(BackEase, _super);
- function BackEase(amplitude) {
- if (amplitude === void 0) { amplitude = 1; }
- _super.call(this);
- this.amplitude = amplitude;
- }
- BackEase.prototype.easeInCore = function (gradient) {
- var num = Math.max(0, this.amplitude);
- return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
- };
- return BackEase;
- })(EasingFunction);
- BABYLON.BackEase = BackEase;
- var BounceEase = (function (_super) {
- __extends(BounceEase, _super);
- function BounceEase(bounces, bounciness) {
- if (bounces === void 0) { bounces = 3; }
- if (bounciness === void 0) { bounciness = 2; }
- _super.call(this);
- this.bounces = bounces;
- this.bounciness = bounciness;
- }
- BounceEase.prototype.easeInCore = function (gradient) {
- var y = Math.max(0.0, this.bounces);
- var bounciness = this.bounciness;
- if (bounciness <= 1.0) {
- bounciness = 1.001;
- }
- var num9 = Math.pow(bounciness, y);
- var num5 = 1.0 - bounciness;
- var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
- var num15 = gradient * num4;
- var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
- var num3 = Math.floor(num65);
- var num13 = num3 + 1.0;
- var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
- var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
- var num7 = (num8 + num12) * 0.5;
- var num6 = gradient - num7;
- var num2 = num7 - num8;
- return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
- };
- return BounceEase;
- })(EasingFunction);
- BABYLON.BounceEase = BounceEase;
- var CubicEase = (function (_super) {
- __extends(CubicEase, _super);
- function CubicEase() {
- _super.apply(this, arguments);
- }
- CubicEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient);
- };
- return CubicEase;
- })(EasingFunction);
- BABYLON.CubicEase = CubicEase;
- var ElasticEase = (function (_super) {
- __extends(ElasticEase, _super);
- function ElasticEase(oscillations, springiness) {
- if (oscillations === void 0) { oscillations = 3; }
- if (springiness === void 0) { springiness = 3; }
- _super.call(this);
- this.oscillations = oscillations;
- this.springiness = springiness;
- }
- ElasticEase.prototype.easeInCore = function (gradient) {
- var num2;
- var num3 = Math.max(0.0, this.oscillations);
- var num = Math.max(0.0, this.springiness);
- if (num == 0) {
- num2 = gradient;
- }
- else {
- num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
- }
- return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
- };
- return ElasticEase;
- })(EasingFunction);
- BABYLON.ElasticEase = ElasticEase;
- var ExponentialEase = (function (_super) {
- __extends(ExponentialEase, _super);
- function ExponentialEase(exponent) {
- if (exponent === void 0) { exponent = 2; }
- _super.call(this);
- this.exponent = exponent;
- }
- ExponentialEase.prototype.easeInCore = function (gradient) {
- if (this.exponent <= 0) {
- return gradient;
- }
- return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
- };
- return ExponentialEase;
- })(EasingFunction);
- BABYLON.ExponentialEase = ExponentialEase;
- var PowerEase = (function (_super) {
- __extends(PowerEase, _super);
- function PowerEase(power) {
- if (power === void 0) { power = 2; }
- _super.call(this);
- this.power = power;
- }
- PowerEase.prototype.easeInCore = function (gradient) {
- var y = Math.max(0.0, this.power);
- return Math.pow(gradient, y);
- };
- return PowerEase;
- })(EasingFunction);
- BABYLON.PowerEase = PowerEase;
- var QuadraticEase = (function (_super) {
- __extends(QuadraticEase, _super);
- function QuadraticEase() {
- _super.apply(this, arguments);
- }
- QuadraticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient);
- };
- return QuadraticEase;
- })(EasingFunction);
- BABYLON.QuadraticEase = QuadraticEase;
- var QuarticEase = (function (_super) {
- __extends(QuarticEase, _super);
- function QuarticEase() {
- _super.apply(this, arguments);
- }
- QuarticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient * gradient);
- };
- return QuarticEase;
- })(EasingFunction);
- BABYLON.QuarticEase = QuarticEase;
- var QuinticEase = (function (_super) {
- __extends(QuinticEase, _super);
- function QuinticEase() {
- _super.apply(this, arguments);
- }
- QuinticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient * gradient * gradient);
- };
- return QuinticEase;
- })(EasingFunction);
- BABYLON.QuinticEase = QuinticEase;
- var SineEase = (function (_super) {
- __extends(SineEase, _super);
- function SineEase() {
- _super.apply(this, arguments);
- }
- SineEase.prototype.easeInCore = function (gradient) {
- return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
- };
- return SineEase;
- })(EasingFunction);
- BABYLON.SineEase = SineEase;
- var BezierCurveEase = (function (_super) {
- __extends(BezierCurveEase, _super);
- function BezierCurveEase(x1, y1, x2, y2) {
- if (x1 === void 0) { x1 = 0; }
- if (y1 === void 0) { y1 = 0; }
- if (x2 === void 0) { x2 = 1; }
- if (y2 === void 0) { y2 = 1; }
- _super.call(this);
- this.x1 = x1;
- this.y1 = y1;
- this.x2 = x2;
- this.y2 = y2;
- }
- BezierCurveEase.prototype.easeInCore = function (gradient) {
- return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
- };
- return BezierCurveEase;
- })(EasingFunction);
- BABYLON.BezierCurveEase = BezierCurveEase;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Bone = (function (_super) {
- __extends(Bone, _super);
- function Bone(name, skeleton, parentBone, matrix, restPose) {
- _super.call(this, name, skeleton.getScene());
- this.name = name;
- this.children = new Array();
- this.animations = new Array();
- this._worldTransform = new BABYLON.Matrix();
- this._absoluteTransform = new BABYLON.Matrix();
- this._invertedAbsoluteTransform = new BABYLON.Matrix();
- this._skeleton = skeleton;
- this._matrix = matrix;
- this._baseMatrix = matrix;
- this._restPose = restPose ? restPose : matrix.clone();
- skeleton.bones.push(this);
- if (parentBone) {
- this._parent = parentBone;
- parentBone.children.push(this);
- }
- else {
- this._parent = null;
- }
- this._updateDifferenceMatrix();
- }
- // Members
- Bone.prototype.getParent = function () {
- return this._parent;
- };
- Bone.prototype.getLocalMatrix = function () {
- return this._matrix;
- };
- Bone.prototype.getBaseMatrix = function () {
- return this._baseMatrix;
- };
- Bone.prototype.getRestPose = function () {
- return this._restPose;
- };
- Bone.prototype.returnToRest = function () {
- this.updateMatrix(this._restPose.clone());
- };
- Bone.prototype.getWorldMatrix = function () {
- return this._worldTransform;
- };
- Bone.prototype.getInvertedAbsoluteTransform = function () {
- return this._invertedAbsoluteTransform;
- };
- Bone.prototype.getAbsoluteTransform = function () {
- return this._absoluteTransform;
- };
- // Methods
- Bone.prototype.updateMatrix = function (matrix) {
- this._baseMatrix = matrix.clone();
- this._matrix = matrix.clone();
- this._skeleton._markAsDirty();
- this._updateDifferenceMatrix();
- };
- Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
- if (!rootMatrix) {
- rootMatrix = this._baseMatrix;
- }
- if (this._parent) {
- rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
- }
- else {
- this._absoluteTransform.copyFrom(rootMatrix);
- }
- this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
- for (var index = 0; index < this.children.length; index++) {
- this.children[index]._updateDifferenceMatrix();
- }
- };
- Bone.prototype.markAsDirty = function () {
- this._currentRenderId++;
- this._skeleton._markAsDirty();
- };
- Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
- if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
- // all animation may be coming from a library skeleton, so may need to create animation
- if (this.animations.length === 0) {
- this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
- }
- // get animation info / verify there is such a range from the source bone
- var sourceRange = source.animations[0].getRange(rangeName);
- if (!sourceRange) {
- return false;
- }
- var from = sourceRange.from;
- var to = sourceRange.to;
- var sourceKeys = source.animations[0].getKeys();
- // rescaling prep
- var sourceBoneLength = source.length;
- var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
- var ratio = scalingReqd ? this.length / sourceBoneLength : null;
- var destKeys = this.animations[0].getKeys();
- // loop vars declaration / initialization
- var orig;
- var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
- var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
- var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
- var mat;
- for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
- orig = sourceKeys[key];
- if (orig.frame >= from && orig.frame <= to) {
- if (scalingReqd) {
- orig.value.decompose(origScale, origRotation, origTranslation);
- origTranslation.scaleInPlace(ratio);
- mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
- }
- else {
- mat = orig.value;
- }
- destKeys.push({ frame: orig.frame + frameOffset, value: mat });
- }
- }
- this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
- return true;
- };
- return Bone;
- })(BABYLON.Node);
- BABYLON.Bone = Bone;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Skeleton = (function () {
- function Skeleton(name, id, scene) {
- this.name = name;
- this.id = id;
- this.bones = new Array();
- this.needInitialSkinMatrix = false;
- this._isDirty = true;
- this._meshesWithPoseMatrix = new Array();
- this._identity = BABYLON.Matrix.Identity();
- this._ranges = {};
- this.bones = [];
- this._scene = scene;
- scene.skeletons.push(this);
- this.prepare();
- //make sure it will recalculate the matrix next time prepare is called.
- this._isDirty = true;
- }
- // Members
- Skeleton.prototype.getTransformMatrices = function (mesh) {
- if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
- return mesh._bonesTransformMatrices;
- }
- return this._transformMatrices;
- };
- Skeleton.prototype.getScene = function () {
- return this._scene;
- };
- // Methods
- Skeleton.prototype.createAnimationRange = function (name, from, to) {
- // check name not already in use
- if (!this._ranges[name]) {
- this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- this.bones[i].animations[0].createRange(name, from, to);
- }
- }
- }
- };
- Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- this.bones[i].animations[0].deleteRange(name, deleteFrames);
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- };
- Skeleton.prototype.getAnimationRange = function (name) {
- return this._ranges[name];
- };
- /**
- * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
- */
- Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
- if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
- if (this._ranges[name] || !source.getAnimationRange(name)) {
- return false;
- }
- var ret = true;
- var frameOffset = this._getHighestAnimationFrame() + 1;
- // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
- var boneDict = {};
- var sourceBones = source.bones;
- for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
- boneDict[sourceBones[i].name] = sourceBones[i];
- }
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- var boneName = this.bones[i].name;
- var sourceBone = boneDict[boneName];
- if (sourceBone) {
- ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
- }
- else {
- BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
- ret = false;
- }
- }
- // do not call createAnimationRange(), since it also is done to bones, which was already done
- var range = source.getAnimationRange(name);
- this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
- return ret;
- };
- Skeleton.prototype.returnToRest = function () {
- for (var index = 0; index < this.bones.length; index++) {
- this.bones[index].returnToRest();
- }
- };
- Skeleton.prototype._getHighestAnimationFrame = function () {
- var ret = 0;
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- var highest = this.bones[i].animations[0].getHighestFrame();
- if (ret < highest) {
- ret = highest;
- }
- }
- }
- return ret;
- };
- Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
- var range = this.getAnimationRange(name);
- if (!range) {
- return null;
- }
- this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- };
- Skeleton.prototype._markAsDirty = function () {
- this._isDirty = true;
- };
- Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
- this._meshesWithPoseMatrix.push(mesh);
- };
- Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
- var index = this._meshesWithPoseMatrix.indexOf(mesh);
- if (index > -1) {
- this._meshesWithPoseMatrix.splice(index, 1);
- }
- };
- Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
- for (var index = 0; index < this.bones.length; index++) {
- var bone = this.bones[index];
- var parentBone = bone.getParent();
- if (parentBone) {
- bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
- }
- else {
- if (initialSkinMatrix) {
- bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
- }
- else {
- bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
- }
- }
- bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
- }
- this._identity.copyToArray(targetMatrix, this.bones.length * 16);
- };
- Skeleton.prototype.prepare = function () {
- if (!this._isDirty) {
- return;
- }
- if (this.needInitialSkinMatrix) {
- for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
- var mesh = this._meshesWithPoseMatrix[index];
- if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
- mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
- }
- var poseMatrix = mesh.getPoseMatrix();
- // Prepare bones
- for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
- var bone = this.bones[boneIndex];
- if (!bone.getParent()) {
- var matrix = bone.getBaseMatrix();
- matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
- bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
- }
- }
- this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
- }
- }
- else {
- if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
- this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
- }
- this._computeTransformMatrices(this._transformMatrices, null);
- }
- this._isDirty = false;
- this._scene._activeBones += this.bones.length;
- };
- Skeleton.prototype.getAnimatables = function () {
- if (!this._animatables || this._animatables.length !== this.bones.length) {
- this._animatables = [];
- for (var index = 0; index < this.bones.length; index++) {
- this._animatables.push(this.bones[index]);
- }
- }
- return this._animatables;
- };
- Skeleton.prototype.clone = function (name, id) {
- var result = new Skeleton(name, id || name, this._scene);
- for (var index = 0; index < this.bones.length; index++) {
- var source = this.bones[index];
- var parentBone = null;
- if (source.getParent()) {
- var parentIndex = this.bones.indexOf(source.getParent());
- parentBone = result.bones[parentIndex];
- }
- var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
- BABYLON.Tools.DeepCopy(source.animations, bone.animations);
- }
- return result;
- };
- Skeleton.prototype.dispose = function () {
- this._meshesWithPoseMatrix = [];
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeSkeleton(this);
- };
- Skeleton.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.bones = [];
- serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
- for (var index = 0; index < this.bones.length; index++) {
- var bone = this.bones[index];
- var serializedBone = {
- parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
- name: bone.name,
- matrix: bone.getLocalMatrix().toArray(),
- rest: bone.getRestPose().toArray()
- };
- serializationObject.bones.push(serializedBone);
- if (bone.length) {
- serializedBone.length = bone.length;
- }
- if (bone.animations && bone.animations.length > 0) {
- serializedBone.animation = bone.animations[0].serialize();
- }
- serializationObject.ranges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationObject.ranges.push(range);
- }
- }
- return serializationObject;
- };
- Skeleton.Parse = function (parsedSkeleton, scene) {
- var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
- skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
- for (var index = 0; index < parsedSkeleton.bones.length; index++) {
- var parsedBone = parsedSkeleton.bones[index];
- var parentBone = null;
- if (parsedBone.parentBoneIndex > -1) {
- parentBone = skeleton.bones[parsedBone.parentBoneIndex];
- }
- var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
- var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
- if (parsedBone.length) {
- bone.length = parsedBone.length;
- }
- if (parsedBone.animation) {
- bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
- }
- }
- // placed after bones, so createAnimationRange can cascade down
- if (parsedSkeleton.ranges) {
- for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
- var data = parsedSkeleton.ranges[index];
- skeleton.createAnimationRange(data.name, data.from, data.to);
- }
- }
- return skeleton;
- };
- return Skeleton;
- })();
- BABYLON.Skeleton = Skeleton;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcess = (function () {
- function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
- if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- this.name = name;
- this.width = -1;
- this.height = -1;
- this._reusable = false;
- this._textures = new BABYLON.SmartArray(2);
- this._currentRenderTextureInd = 0;
- if (camera != null) {
- this._camera = camera;
- this._scene = camera.getScene();
- camera.attachPostProcess(this);
- this._engine = this._scene.getEngine();
- }
- else {
- this._engine = engine;
- }
- this._renderRatio = ratio;
- this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
- this._reusable = reusable || false;
- this._textureType = textureType;
- this._samplers = samplers || [];
- this._samplers.push("textureSampler");
- this._fragmentUrl = fragmentUrl;
- this._parameters = parameters || [];
- this.updateEffect(defines);
- }
- PostProcess.prototype.updateEffect = function (defines) {
- this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
- };
- PostProcess.prototype.isReusable = function () {
- return this._reusable;
- };
- PostProcess.prototype.activate = function (camera, sourceTexture) {
- camera = camera || this._camera;
- var scene = camera.getScene();
- var maxSize = camera.getEngine().getCaps().maxTextureSize;
- var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
- var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
- desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
- desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
- if (this.width !== desiredWidth || this.height !== desiredHeight) {
- if (this._textures.length > 0) {
- for (var i = 0; i < this._textures.length; i++) {
- this._engine._releaseTexture(this._textures.data[i]);
- }
- this._textures.reset();
- }
- this.width = desiredWidth;
- this.height = desiredHeight;
- this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
- if (this._reusable) {
- this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
- }
- if (this.onSizeChanged) {
- this.onSizeChanged();
- }
- }
- this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
- if (this.onActivate) {
- this.onActivate(camera);
- }
- // Clear
- if (this.clearColor) {
- this._engine.clear(this.clearColor, true, true);
- }
- else {
- this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
- }
- if (this._reusable) {
- this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
- }
- };
- Object.defineProperty(PostProcess.prototype, "isSupported", {
- get: function () {
- return this._effect.isSupported;
- },
- enumerable: true,
- configurable: true
- });
- PostProcess.prototype.apply = function () {
- // Check
- if (!this._effect.isReady())
- return null;
- // States
- this._engine.enableEffect(this._effect);
- this._engine.setState(false);
- this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- this._engine.setDepthBuffer(false);
- this._engine.setDepthWrite(false);
- // Texture
- this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
- // Parameters
- if (this.onApply) {
- this.onApply(this._effect);
- }
- return this._effect;
- };
- PostProcess.prototype.dispose = function (camera) {
- camera = camera || this._camera;
- if (this._textures.length > 0) {
- for (var i = 0; i < this._textures.length; i++) {
- this._engine._releaseTexture(this._textures.data[i]);
- }
- this._textures.reset();
- }
- if (!camera) {
- return;
- }
- camera.detachPostProcess(this);
- var index = camera._postProcesses.indexOf(this);
- if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
- this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
- }
- };
- return PostProcess;
- })();
- BABYLON.PostProcess = PostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessManager = (function () {
- function PostProcessManager(scene) {
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._scene = scene;
- }
- PostProcessManager.prototype._prepareBuffers = function () {
- if (this._vertexBuffer) {
- return;
- }
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
- };
- // Methods
- PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
- var postProcesses = this._scene.activeCamera._postProcesses;
- var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
- if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
- return false;
- }
- postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
- return true;
- };
- PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
- var engine = this._scene.getEngine();
- for (var index = 0; index < postProcesses.length; index++) {
- if (index < postProcesses.length - 1) {
- postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
- }
- else {
- if (targetTexture) {
- engine.bindFramebuffer(targetTexture);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- var pp = postProcesses[index];
- var effect = pp.apply();
- if (effect) {
- if (pp.onBeforeRender) {
- pp.onBeforeRender(effect);
- }
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.draw(true, 0, 6);
- if (pp.onAfterRender) {
- pp.onAfterRender(effect);
- }
- }
- }
- // Restore depth buffer
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- };
- PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
- postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
- var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
- if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
- return;
- }
- var engine = this._scene.getEngine();
- for (var index = 0; index < postProcessesTakenIndices.length; index++) {
- if (index < postProcessesTakenIndices.length - 1) {
- postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
- }
- else {
- if (targetTexture) {
- engine.bindFramebuffer(targetTexture, faceIndex);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- if (doNotPresent) {
- break;
- }
- var pp = postProcesses[postProcessesTakenIndices[index]];
- var effect = pp.apply();
- if (effect) {
- if (pp.onBeforeRender) {
- pp.onBeforeRender(effect);
- }
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.draw(true, 0, 6);
- if (pp.onAfterRender) {
- pp.onAfterRender(effect);
- }
- }
- }
- // Restore depth buffer
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- };
- PostProcessManager.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- };
- return PostProcessManager;
- })();
- BABYLON.PostProcessManager = PostProcessManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PassPostProcess = (function (_super) {
- __extends(PassPostProcess, _super);
- function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
- }
- return PassPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.PassPostProcess = PassPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PhysicsEngine = (function () {
- function PhysicsEngine(plugin) {
- this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
- }
- PhysicsEngine.prototype._initialize = function (gravity) {
- this._currentPlugin.initialize();
- this._setGravity(gravity);
- };
- PhysicsEngine.prototype._runOneStep = function (delta) {
- if (delta > 0.1) {
- delta = 0.1;
- }
- else if (delta <= 0) {
- delta = 1.0 / 60.0;
- }
- this._currentPlugin.runOneStep(delta);
- };
- PhysicsEngine.prototype._setGravity = function (gravity) {
- this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
- this._currentPlugin.setGravity(this.gravity);
- };
- PhysicsEngine.prototype._getGravity = function () {
- return this._currentPlugin.getGravity();
- };
- PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
- return this._currentPlugin.registerMesh(mesh, impostor, options);
- };
- PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
- return this._currentPlugin.registerMeshesAsCompound(parts, options);
- };
- PhysicsEngine.prototype._unregisterMesh = function (mesh) {
- this._currentPlugin.unregisterMesh(mesh);
- };
- PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
- this._currentPlugin.applyImpulse(mesh, force, contactPoint);
- };
- PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
- return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
- };
- PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
- this._currentPlugin.updateBodyPosition(mesh);
- };
- PhysicsEngine.prototype.dispose = function () {
- this._currentPlugin.dispose();
- };
- PhysicsEngine.prototype.isSupported = function () {
- return this._currentPlugin.isSupported();
- };
- PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
- return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
- };
- PhysicsEngine.prototype.getPhysicsPluginName = function () {
- return this._currentPlugin.name;
- };
- PhysicsEngine.prototype.getWorldObject = function () {
- return this._currentPlugin.getWorldObject();
- };
- // Statics
- PhysicsEngine.NoImpostor = 0;
- PhysicsEngine.SphereImpostor = 1;
- PhysicsEngine.BoxImpostor = 2;
- PhysicsEngine.PlaneImpostor = 3;
- PhysicsEngine.MeshImpostor = 4;
- PhysicsEngine.CapsuleImpostor = 5;
- PhysicsEngine.ConeImpostor = 6;
- PhysicsEngine.CylinderImpostor = 7;
- PhysicsEngine.ConvexHullImpostor = 8;
- PhysicsEngine.HeightmapImpostor = 9;
- PhysicsEngine.Epsilon = 0.001;
- return PhysicsEngine;
- })();
- BABYLON.PhysicsEngine = PhysicsEngine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VertexData = (function () {
- function VertexData() {
- }
- VertexData.prototype.set = function (data, kind) {
- switch (kind) {
- case BABYLON.VertexBuffer.PositionKind:
- this.positions = data;
- break;
- case BABYLON.VertexBuffer.NormalKind:
- this.normals = data;
- break;
- case BABYLON.VertexBuffer.UVKind:
- this.uvs = data;
- break;
- case BABYLON.VertexBuffer.UV2Kind:
- this.uvs2 = data;
- break;
- case BABYLON.VertexBuffer.UV3Kind:
- this.uvs3 = data;
- break;
- case BABYLON.VertexBuffer.UV4Kind:
- this.uvs4 = data;
- break;
- case BABYLON.VertexBuffer.UV5Kind:
- this.uvs5 = data;
- break;
- case BABYLON.VertexBuffer.UV6Kind:
- this.uvs6 = data;
- break;
- case BABYLON.VertexBuffer.ColorKind:
- this.colors = data;
- break;
- case BABYLON.VertexBuffer.MatricesIndicesKind:
- this.matricesIndices = data;
- break;
- case BABYLON.VertexBuffer.MatricesWeightsKind:
- this.matricesWeights = data;
- break;
- case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
- this.matricesIndicesExtra = data;
- break;
- case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
- this.matricesWeightsExtra = data;
- break;
- }
- };
- VertexData.prototype.applyToMesh = function (mesh, updatable) {
- this._applyTo(mesh, updatable);
- };
- VertexData.prototype.applyToGeometry = function (geometry, updatable) {
- this._applyTo(geometry, updatable);
- };
- VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
- this._update(mesh);
- };
- VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
- this._update(geometry);
- };
- VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
- if (this.positions) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
- }
- if (this.normals) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
- }
- if (this.uvs) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
- }
- if (this.uvs2) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
- }
- if (this.uvs3) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
- }
- if (this.uvs4) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
- }
- if (this.uvs5) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
- }
- if (this.uvs6) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
- }
- if (this.colors) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
- }
- if (this.matricesIndices) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
- }
- if (this.matricesWeights) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
- }
- if (this.matricesIndicesExtra) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
- }
- if (this.matricesWeightsExtra) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
- }
- if (this.indices) {
- meshOrGeometry.setIndices(this.indices);
- }
- };
- VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
- if (this.positions) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
- }
- if (this.normals) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
- }
- if (this.uvs) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
- }
- if (this.uvs2) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
- }
- if (this.uvs3) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
- }
- if (this.uvs4) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
- }
- if (this.uvs5) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
- }
- if (this.uvs6) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
- }
- if (this.colors) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
- }
- if (this.matricesIndices) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
- }
- if (this.matricesWeights) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
- }
- if (this.matricesIndicesExtra) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
- }
- if (this.matricesWeightsExtra) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
- }
- if (this.indices) {
- meshOrGeometry.setIndices(this.indices);
- }
- };
- VertexData.prototype.transform = function (matrix) {
- var transformed = BABYLON.Vector3.Zero();
- var index;
- if (this.positions) {
- var position = BABYLON.Vector3.Zero();
- for (index = 0; index < this.positions.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
- BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
- this.positions[index] = transformed.x;
- this.positions[index + 1] = transformed.y;
- this.positions[index + 2] = transformed.z;
- }
- }
- if (this.normals) {
- var normal = BABYLON.Vector3.Zero();
- for (index = 0; index < this.normals.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
- BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
- this.normals[index] = transformed.x;
- this.normals[index + 1] = transformed.y;
- this.normals[index + 2] = transformed.z;
- }
- }
- };
- VertexData.prototype.merge = function (other) {
- if (other.indices) {
- if (!this.indices) {
- this.indices = [];
- }
- var offset = this.positions ? this.positions.length / 3 : 0;
- for (var index = 0; index < other.indices.length; index++) {
- //TODO check type - if Int32Array!
- this.indices.push(other.indices[index] + offset);
- }
- }
- this.positions = this._mergeElement(this.positions, other.positions);
- this.normals = this._mergeElement(this.normals, other.normals);
- this.uvs = this._mergeElement(this.uvs, other.uvs);
- this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
- this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
- this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
- this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
- this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
- this.colors = this._mergeElement(this.colors, other.colors);
- this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
- this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
- this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
- this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
- };
- VertexData.prototype._mergeElement = function (source, other) {
- if (!other)
- return source;
- if (!source)
- return other;
- var len = other.length + source.length;
- var isSrcTypedArray = source instanceof Float32Array;
- var isOthTypedArray = other instanceof Float32Array;
- // use non-loop method when the source is Float32Array
- if (isSrcTypedArray) {
- var ret32 = new Float32Array(len);
- ret32.set(source);
- ret32.set(other, source.length);
- return ret32;
- }
- else if (!isOthTypedArray) {
- return source.concat(other);
- }
- else {
- var ret = source.slice(0); // copy source to a separate array
- for (var i = 0, len = other.length; i < len; i++) {
- ret.push(other[i]);
- }
- return ret;
- }
- };
- VertexData.prototype.serialize = function () {
- var serializationObject = this.serialize();
- if (this.positions) {
- serializationObject.positions = this.positions;
- }
- if (this.normals) {
- serializationObject.normals = this.normals;
- }
- if (this.uvs) {
- serializationObject.uvs = this.uvs;
- }
- if (this.uvs2) {
- serializationObject.uvs2 = this.uvs2;
- }
- if (this.uvs3) {
- serializationObject.uvs3 = this.uvs3;
- }
- if (this.uvs4) {
- serializationObject.uvs4 = this.uvs4;
- }
- if (this.uvs5) {
- serializationObject.uvs5 = this.uvs5;
- }
- if (this.uvs6) {
- serializationObject.uvs6 = this.uvs6;
- }
- if (this.colors) {
- serializationObject.colors = this.colors;
- }
- if (this.matricesIndices) {
- serializationObject.matricesIndices = this.matricesIndices;
- serializationObject.matricesIndices._isExpanded = true;
- }
- if (this.matricesWeights) {
- serializationObject.matricesWeights = this.matricesWeights;
- }
- if (this.matricesIndicesExtra) {
- serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
- serializationObject.matricesIndicesExtra._isExpanded = true;
- }
- if (this.matricesWeightsExtra) {
- serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
- }
- serializationObject.indices = this.indices;
- return serializationObject;
- };
- // Statics
- VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
- return VertexData._ExtractFrom(mesh, copyWhenShared);
- };
- VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
- return VertexData._ExtractFrom(geometry, copyWhenShared);
- };
- VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
- var result = new VertexData();
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
- result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
- result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
- }
- result.indices = meshOrGeometry.getIndices(copyWhenShared);
- return result;
- };
- VertexData.CreateRibbon = function (options) {
- var pathArray = options.pathArray;
- var closeArray = options.closeArray || false;
- var closePath = options.closePath || false;
- var defaultOffset = Math.floor(pathArray[0].length / 2);
- var offset = options.offset || defaultOffset;
- offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
- var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
- var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
- var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
- var minlg; // minimal length among all paths from pathArray
- var lg = []; // array of path lengths : nb of vertex per path
- var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
- var p; // path iterator
- var i; // point iterator
- var j; // point iterator
- // if single path in pathArray
- if (pathArray.length < 2) {
- var ar1 = [];
- var ar2 = [];
- for (i = 0; i < pathArray[0].length - offset; i++) {
- ar1.push(pathArray[0][i]);
- ar2.push(pathArray[0][i + offset]);
- }
- pathArray = [ar1, ar2];
- }
- // positions and horizontal distances (u)
- var idc = 0;
- var closePathCorr = (closePath) ? 1 : 0;
- var path;
- var l;
- minlg = pathArray[0].length;
- var vectlg;
- var dist;
- for (p = 0; p < pathArray.length; p++) {
- uTotalDistance[p] = 0;
- us[p] = [0];
- path = pathArray[p];
- l = path.length;
- minlg = (minlg < l) ? minlg : l;
- j = 0;
- while (j < l) {
- positions.push(path[j].x, path[j].y, path[j].z);
- if (j > 0) {
- vectlg = path[j].subtract(path[j - 1]).length();
- dist = vectlg + uTotalDistance[p];
- us[p].push(dist);
- uTotalDistance[p] = dist;
- }
- j++;
- }
- if (closePath) {
- j--;
- positions.push(path[0].x, path[0].y, path[0].z);
- vectlg = path[j].subtract(path[0]).length();
- dist = vectlg + uTotalDistance[p];
- us[p].push(dist);
- uTotalDistance[p] = dist;
- }
- lg[p] = l + closePathCorr;
- idx[p] = idc;
- idc += (l + closePathCorr);
- }
- // vertical distances (v)
- var path1;
- var path2;
- var vertex1;
- var vertex2;
- for (i = 0; i < minlg + closePathCorr; i++) {
- vTotalDistance[i] = 0;
- vs[i] = [0];
- for (p = 0; p < pathArray.length - 1; p++) {
- path1 = pathArray[p];
- path2 = pathArray[p + 1];
- if (i === minlg) {
- vertex1 = path1[0];
- vertex2 = path2[0];
- }
- else {
- vertex1 = path1[i];
- vertex2 = path2[i];
- }
- vectlg = vertex2.subtract(vertex1).length();
- dist = vectlg + vTotalDistance[i];
- vs[i].push(dist);
- vTotalDistance[i] = dist;
- }
- if (closeArray) {
- path1 = pathArray[p];
- path2 = pathArray[0];
- if (i === minlg) {
- vertex2 = path2[0];
- }
- vectlg = vertex2.subtract(vertex1).length();
- dist = vectlg + vTotalDistance[i];
- vTotalDistance[i] = dist;
- }
- }
- // uvs
- var u;
- var v;
- for (p = 0; p < pathArray.length; p++) {
- for (i = 0; i < minlg + closePathCorr; i++) {
- u = us[p][i] / uTotalDistance[p];
- v = vs[i][p] / vTotalDistance[i];
- uvs.push(u, v);
- }
- }
- // indices
- p = 0; // path index
- var pi = 0; // positions array index
- var l1 = lg[p] - 1; // path1 length
- var l2 = lg[p + 1] - 1; // path2 length
- var min = (l1 < l2) ? l1 : l2; // current path stop index
- var shft = idx[1] - idx[0]; // shift
- var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
- while (pi <= min && p < path1nb) {
- // 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
- indices.push(pi, pi + shft, pi + 1);
- indices.push(pi + shft + 1, pi + 1, pi + shft);
- pi += 1;
- if (pi === min) {
- p++;
- if (p === lg.length - 1) {
- shft = idx[0] - idx[p];
- l1 = lg[p] - 1;
- l2 = lg[0] - 1;
- }
- else {
- shft = idx[p + 1] - idx[p];
- l1 = lg[p] - 1;
- l2 = lg[p + 1] - 1;
- }
- pi = idx[p];
- min = (l1 < l2) ? l1 + pi : l2 + pi;
- }
- }
- // normals
- VertexData.ComputeNormals(positions, indices, normals);
- if (closePath) {
- var indexFirst = 0;
- var indexLast = 0;
- for (p = 0; p < pathArray.length; p++) {
- indexFirst = idx[p] * 3;
- if (p + 1 < pathArray.length) {
- indexLast = (idx[p + 1] - 1) * 3;
- }
- else {
- indexLast = normals.length - 3;
- }
- normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
- normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
- normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
- normals[indexLast] = normals[indexFirst];
- normals[indexLast + 1] = normals[indexFirst + 1];
- normals[indexLast + 2] = normals[indexFirst + 2];
- }
- }
- // sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (closePath) {
- vertexData._idx = idx;
- }
- return vertexData;
- };
- VertexData.CreateBox = function (options) {
- var normalsSource = [
- new BABYLON.Vector3(0, 0, 1),
- new BABYLON.Vector3(0, 0, -1),
- new BABYLON.Vector3(1, 0, 0),
- new BABYLON.Vector3(-1, 0, 0),
- new BABYLON.Vector3(0, 1, 0),
- new BABYLON.Vector3(0, -1, 0)
- ];
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var width = options.width || options.size || 1;
- var height = options.height || options.size || 1;
- var depth = options.depth || options.size || 1;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var faceUV = options.faceUV || new Array(6);
- var faceColors = options.faceColors;
- var colors = [];
- // default face colors and UV if undefined
- for (var f = 0; f < 6; f++) {
- if (faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- }
- var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
- // Create each face in turn.
- for (var index = 0; index < normalsSource.length; index++) {
- var normal = normalsSource[index];
- // Get two vectors perpendicular to the face normal and to each other.
- var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
- var side2 = BABYLON.Vector3.Cross(normal, side1);
- // Six indices (two triangles) per face.
- var verticesLength = positions.length / 3;
- indices.push(verticesLength);
- indices.push(verticesLength + 1);
- indices.push(verticesLength + 2);
- indices.push(verticesLength);
- indices.push(verticesLength + 2);
- indices.push(verticesLength + 3);
- // Four vertices per face.
- var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].z, faceUV[index].w);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].x, faceUV[index].w);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.add(side1).add(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].x, faceUV[index].y);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].z, faceUV[index].y);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- }
- // sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors) {
- var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
- vertexData.colors = totalColors;
- }
- return vertexData;
- };
- VertexData.CreateSphere = function (options) {
- var segments = options.segments || 32;
- var diameterX = options.diameterX || options.diameter || 1;
- var diameterY = options.diameterY || options.diameter || 1;
- var diameterZ = options.diameterZ || options.diameter || 1;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
- var totalZRotationSteps = 2 + segments;
- var totalYRotationSteps = 2 * totalZRotationSteps;
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
- var normalizedZ = zRotationStep / totalZRotationSteps;
- var angleZ = normalizedZ * Math.PI * slice;
- for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
- var normalizedY = yRotationStep / totalYRotationSteps;
- var angleY = normalizedY * Math.PI * 2 * arc;
- var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
- var rotationY = BABYLON.Matrix.RotationY(angleY);
- var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
- var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
- var vertex = complete.multiply(radius);
- var normal = complete.divide(radius).normalize();
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(normalizedY, normalizedZ);
- }
- if (zRotationStep > 0) {
- var verticesCount = positions.length / 3;
- for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
- indices.push((firstIndex));
- indices.push((firstIndex + 1));
- indices.push(firstIndex + totalYRotationSteps + 1);
- indices.push((firstIndex + totalYRotationSteps + 1));
- indices.push((firstIndex + 1));
- indices.push((firstIndex + totalYRotationSteps + 2));
- }
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // Cylinder and cone
- VertexData.CreateCylinder = function (options) {
- var height = options.height || 2;
- var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
- var diameterBottom = options.diameterBottom || options.diameter || 1;
- var tessellation = options.tessellation || 24;
- var subdivisions = options.subdivisions || 1;
- var hasRings = options.hasRings;
- var enclose = options.enclose;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var faceUV = options.faceUV || new Array(3);
- var faceColors = options.faceColors;
- // default face colors and UV if undefined
- var quadNb = (arc !== 1 && enclose) ? 2 : 0;
- var ringNb = (hasRings) ? subdivisions : 1;
- var surfaceNb = 2 + (1 + quadNb) * ringNb;
- var f;
- for (f = 0; f < surfaceNb; f++) {
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- }
- for (f = 0; f < surfaceNb; f++) {
- if (faceUV && faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- }
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var colors = [];
- var angle_step = Math.PI * 2 * arc / tessellation;
- var angle;
- var h;
- var radius;
- var tan = (diameterBottom - diameterTop) / 2 / height;
- var ringVertex = BABYLON.Vector3.Zero();
- var ringNormal = BABYLON.Vector3.Zero();
- var ringFirstVertex = BABYLON.Vector3.Zero();
- var ringFirstNormal = BABYLON.Vector3.Zero();
- var quadNormal = BABYLON.Vector3.Zero();
- var Y = BABYLON.Axis.Y;
- // positions, normals, uvs
- var i;
- var j;
- var r;
- var ringIdx = 1;
- var s = 1; // surface index
- var cs = 0;
- var v = 0;
- for (i = 0; i <= subdivisions; i++) {
- h = i / subdivisions;
- radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
- ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
- for (r = 0; r < ringIdx; r++) {
- if (hasRings) {
- s += r;
- }
- if (enclose) {
- s += 2 * r;
- }
- for (j = 0; j <= tessellation; j++) {
- angle = j * angle_step;
- // position
- ringVertex.x = Math.cos(-angle) * radius;
- ringVertex.y = -height / 2 + h * height;
- ringVertex.z = Math.sin(-angle) * radius;
- // normal
- if (diameterTop === 0 && i === subdivisions) {
- // if no top cap, reuse former normals
- ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
- ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
- ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
- }
- else {
- ringNormal.x = ringVertex.x;
- ringNormal.z = ringVertex.z;
- ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
- ringNormal.normalize();
- }
- // keep first ring vertex values for enclose
- if (j === 0) {
- ringFirstVertex.copyFrom(ringVertex);
- ringFirstNormal.copyFrom(ringNormal);
- }
- positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
- normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
- }
- else {
- v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
- }
- uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
- if (faceColors) {
- colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
- }
- }
- // if enclose, add four vertices and their dedicated normals
- if (arc !== 1 && enclose) {
- positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
- positions.push(0, ringVertex.y, 0);
- positions.push(0, ringVertex.y, 0);
- positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
- BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
- quadNormal.normalize();
- normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
- BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
- quadNormal.normalize();
- normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
- }
- else {
- v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
- }
- uvs.push(faceUV[s + 1].x, v);
- uvs.push(faceUV[s + 1].z, v);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
- }
- else {
- v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
- }
- uvs.push(faceUV[s + 2].x, v);
- uvs.push(faceUV[s + 2].z, v);
- if (faceColors) {
- colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
- colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
- colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
- colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
- }
- }
- if (cs !== s) {
- cs = s;
- }
- }
- }
- // indices
- var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
- var s;
- i = 0;
- for (s = 0; s < subdivisions; s++) {
- for (j = 0; j < tessellation; j++) {
- var i0 = i * (e + 1) + j;
- var i1 = (i + 1) * (e + 1) + j;
- var i2 = i * (e + 1) + (j + 1);
- var i3 = (i + 1) * (e + 1) + (j + 1);
- indices.push(i0, i1, i2);
- indices.push(i3, i2, i1);
- }
- if (arc !== 1 && enclose) {
- indices.push(i0 + 2, i1 + 2, i2 + 2);
- indices.push(i3 + 2, i2 + 2, i1 + 2);
- indices.push(i0 + 4, i1 + 4, i2 + 4);
- indices.push(i3 + 4, i2 + 4, i1 + 4);
- }
- i = (hasRings) ? (i + 2) : (i + 1);
- }
- // Caps
- var createCylinderCap = function (isTop) {
- var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
- if (radius === 0) {
- return;
- }
- // Cap positions, normals & uvs
- var angle;
- var circleVector;
- var i;
- var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
- var c;
- if (faceColors) {
- c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
- }
- // cap center
- var vbase = positions.length / 3;
- var offset = isTop ? height / 2 : -height / 2;
- var center = new BABYLON.Vector3(0, offset, 0);
- positions.push(center.x, center.y, center.z);
- normals.push(0, isTop ? 1 : -1, 0);
- uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
- if (faceColors) {
- colors.push(c.r, c.g, c.b, c.a);
- }
- var textureScale = new BABYLON.Vector2(0.5, 0.5);
- for (i = 0; i <= tessellation; i++) {
- angle = Math.PI * 2 * i * arc / tessellation;
- var cos = Math.cos(-angle);
- var sin = Math.sin(-angle);
- circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
- var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
- positions.push(circleVector.x, circleVector.y, circleVector.z);
- normals.push(0, isTop ? 1 : -1, 0);
- uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
- if (faceColors) {
- colors.push(c.r, c.g, c.b, c.a);
- }
- }
- // Cap indices
- for (i = 0; i < tessellation; i++) {
- if (!isTop) {
- indices.push(vbase);
- indices.push(vbase + (i + 1));
- indices.push(vbase + (i + 2));
- }
- else {
- indices.push(vbase);
- indices.push(vbase + (i + 2));
- indices.push(vbase + (i + 1));
- }
- }
- };
- // add caps to geometry
- createCylinderCap(false);
- createCylinderCap(true);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors) {
- vertexData.colors = colors;
- }
- return vertexData;
- };
- VertexData.CreateTorus = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var diameter = options.diameter || 1;
- var thickness = options.thickness || 0.5;
- var tessellation = options.tessellation || 16;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var stride = tessellation + 1;
- for (var i = 0; i <= tessellation; i++) {
- var u = i / tessellation;
- var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
- var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
- for (var j = 0; j <= tessellation; j++) {
- var v = 1 - j / tessellation;
- var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
- var dx = Math.cos(innerAngle);
- var dy = Math.sin(innerAngle);
- // Create a vertex.
- var normal = new BABYLON.Vector3(dx, dy, 0);
- var position = normal.scale(thickness / 2);
- var textureCoordinate = new BABYLON.Vector2(u, v);
- position = BABYLON.Vector3.TransformCoordinates(position, transform);
- normal = BABYLON.Vector3.TransformNormal(normal, transform);
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(textureCoordinate.x, textureCoordinate.y);
- // And create indices for two triangles.
- var nextI = (i + 1) % stride;
- var nextJ = (j + 1) % stride;
- indices.push(i * stride + j);
- indices.push(i * stride + nextJ);
- indices.push(nextI * stride + j);
- indices.push(i * stride + nextJ);
- indices.push(nextI * stride + nextJ);
- indices.push(nextI * stride + j);
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateLines = function (options) {
- var indices = [];
- var positions = [];
- var points = options.points;
- for (var index = 0; index < points.length; index++) {
- positions.push(points[index].x, points[index].y, points[index].z);
- if (index > 0) {
- indices.push(index - 1);
- indices.push(index);
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- return vertexData;
- };
- VertexData.CreateDashedLines = function (options) {
- var dashSize = options.dashSize || 3;
- var gapSize = options.gapSize || 1;
- var dashNb = options.dashNb || 200;
- var points = options.points;
- var positions = new Array();
- var indices = new Array();
- var curvect = BABYLON.Vector3.Zero();
- var lg = 0;
- var nb = 0;
- var shft = 0;
- var dashshft = 0;
- var curshft = 0;
- var idx = 0;
- var i = 0;
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- lg += curvect.length();
- }
- shft = lg / dashNb;
- dashshft = dashSize * shft / (dashSize + gapSize);
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- nb = Math.floor(curvect.length() / shft);
- curvect.normalize();
- for (var j = 0; j < nb; j++) {
- curshft = shft * j;
- positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
- positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
- indices.push(idx, idx + 1);
- idx += 2;
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.positions = positions;
- vertexData.indices = indices;
- return vertexData;
- };
- VertexData.CreateGround = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col;
- var width = options.width || 1;
- var height = options.height || 1;
- var subdivisions = options.subdivisions || 1;
- for (row = 0; row <= subdivisions; row++) {
- for (col = 0; col <= subdivisions; col++) {
- var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
- var normal = new BABYLON.Vector3(0, 1.0, 0);
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(col / subdivisions, 1.0 - row / subdivisions);
- }
- }
- for (row = 0; row < subdivisions; row++) {
- for (col = 0; col < subdivisions; col++) {
- indices.push(col + 1 + (row + 1) * (subdivisions + 1));
- indices.push(col + 1 + row * (subdivisions + 1));
- indices.push(col + row * (subdivisions + 1));
- indices.push(col + (row + 1) * (subdivisions + 1));
- indices.push(col + 1 + (row + 1) * (subdivisions + 1));
- indices.push(col + row * (subdivisions + 1));
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateTiledGround = function (options) {
- var xmin = options.xmin;
- var zmin = options.zmin;
- var xmax = options.xmax;
- var zmax = options.zmax;
- var subdivisions = options.subdivisions || { w: 1, h: 1 };
- var precision = options.precision || { w: 1, h: 1 };
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col, tileRow, tileCol;
- subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
- subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
- precision.w = (precision.w < 1) ? 1 : precision.w;
- precision.h = (precision.h < 1) ? 1 : precision.h;
- var tileSize = {
- 'w': (xmax - xmin) / subdivisions.w,
- 'h': (zmax - zmin) / subdivisions.h
- };
- function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
- // Indices
- var base = positions.length / 3;
- var rowLength = precision.w + 1;
- for (row = 0; row < precision.h; row++) {
- for (col = 0; col < precision.w; col++) {
- var square = [
- base + col + row * rowLength,
- base + (col + 1) + row * rowLength,
- base + (col + 1) + (row + 1) * rowLength,
- base + col + (row + 1) * rowLength
- ];
- indices.push(square[1]);
- indices.push(square[2]);
- indices.push(square[3]);
- indices.push(square[0]);
- indices.push(square[1]);
- indices.push(square[3]);
- }
- }
- // Position, normals and uvs
- var position = BABYLON.Vector3.Zero();
- var normal = new BABYLON.Vector3(0, 1.0, 0);
- for (row = 0; row <= precision.h; row++) {
- position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
- for (col = 0; col <= precision.w; col++) {
- position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
- position.y = 0;
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(col / precision.w, row / precision.h);
- }
- }
- }
- for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
- for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
- applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateGroundFromHeightMap = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col;
- // Vertices
- for (row = 0; row <= options.subdivisions; row++) {
- for (col = 0; col <= options.subdivisions; col++) {
- 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));
- // Compute height
- var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
- var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
- var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
- var r = options.buffer[pos] / 255.0;
- var g = options.buffer[pos + 1] / 255.0;
- var b = options.buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
- // Add vertex
- positions.push(position.x, position.y, position.z);
- normals.push(0, 0, 0);
- uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
- }
- }
- // Indices
- for (row = 0; row < options.subdivisions; row++) {
- for (col = 0; col < options.subdivisions; col++) {
- indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
- indices.push(col + 1 + row * (options.subdivisions + 1));
- indices.push(col + row * (options.subdivisions + 1));
- indices.push(col + (row + 1) * (options.subdivisions + 1));
- indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
- indices.push(col + row * (options.subdivisions + 1));
- }
- }
- // Normals
- VertexData.ComputeNormals(positions, indices, normals);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreatePlane = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var width = options.width || options.size || 1;
- var height = options.height || options.size || 1;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // Vertices
- var halfWidth = width / 2.0;
- var halfHeight = height / 2.0;
- positions.push(-halfWidth, -halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(0.0, 0.0);
- positions.push(halfWidth, -halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(1.0, 0.0);
- positions.push(halfWidth, halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(1.0, 1.0);
- positions.push(-halfWidth, halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(0.0, 1.0);
- // Indices
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateDisc = function (options) {
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var radius = options.radius || 0.5;
- var tessellation = options.tessellation || 64;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // positions and uvs
- positions.push(0, 0, 0); // disc center first
- uvs.push(0.5, 0.5);
- var theta = Math.PI * 2 * arc;
- var step = theta / tessellation;
- for (var a = 0; a < theta; a += step) {
- var x = Math.cos(a);
- var y = Math.sin(a);
- var u = (x + 1) / 2;
- var v = (1 - y) / 2;
- positions.push(radius * x, radius * y, 0);
- uvs.push(u, v);
- }
- if (arc === 1) {
- positions.push(positions[3], positions[4], positions[5]); // close the circle
- uvs.push(uvs[2], uvs[3]);
- }
- //indices
- var vertexNb = positions.length / 3;
- for (var i = 1; i < vertexNb - 1; i++) {
- indices.push(i + 1, 0, i);
- }
- // result
- VertexData.ComputeNormals(positions, indices, normals);
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateIcoSphere = function (options) {
- var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var radius = options.radius || 1;
- var flat = (options.flat === undefined) ? true : options.flat;
- var subdivisions = options.subdivisions || 4;
- var radiusX = options.radiusX || radius;
- var radiusY = options.radiusY || radius;
- var radiusZ = options.radiusZ || radius;
- var t = (1 + Math.sqrt(5)) / 2;
- // 12 vertex x,y,z
- var ico_vertices = [
- -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
- 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
- t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
- ];
- // index of 3 vertex makes a face of icopshere
- var ico_indices = [
- 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
- 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
- 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
- 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
- ];
- // vertex for uv have aliased position, not for UV
- var vertices_unalias_id = [
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
- // vertex alias
- 0,
- 2,
- 3,
- 3,
- 3,
- 4,
- 7,
- 8,
- 9,
- 9,
- 10,
- 11 // 23: B + 12
- ];
- // uv as integer step (not pixels !)
- var ico_vertexuv = [
- 5, 1, 3, 1, 6, 4, 0, 0,
- 5, 3, 4, 2, 2, 2, 4, 0,
- 2, 0, 1, 1, 6, 0, 6, 2,
- // vertex alias (for same vertex on different faces)
- 0, 4,
- 3, 3,
- 4, 4,
- 3, 1,
- 4, 2,
- 4, 4,
- 0, 2,
- 1, 1,
- 2, 2,
- 3, 3,
- 1, 3,
- 2, 4 // 23: B + 12
- ];
- // Vertices[0, 1, ...9, A, B] : position on UV plane
- // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
- // First island of uv mapping
- // v = 4h 3+ 2
- // v = 3h 9+ 4
- // v = 2h 9+ 5 B
- // v = 1h 9 1 0
- // v = 0h 3 8 7 A
- // u = 0 1 2 3 4 5 6 *a
- // Second island of uv mapping
- // v = 4h 0+ B+ 4+
- // v = 3h A+ 2+
- // v = 2h 7+ 6 3+
- // v = 1h 8+ 3+
- // v = 0h
- // u = 0 1 2 3 4 5 6 *a
- // Face layout on texture UV mapping
- // ============
- // \ 4 /\ 16 / ======
- // \ / \ / /\ 11 /
- // \/ 7 \/ / \ /
- // ======= / 10 \/
- // /\ 17 /\ =======
- // / \ / \ \ 15 /\
- // / 8 \/ 12 \ \ / \
- // ============ \/ 6 \
- // \ 18 /\ ============
- // \ / \ \ 5 /\ 0 /
- // \/ 13 \ \ / \ /
- // ======= \/ 1 \/
- // =============
- // /\ 19 /\ 2 /\
- // / \ / \ / \
- // / 14 \/ 9 \/ 3 \
- // ===================
- // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
- var ustep = 138 / 1024;
- var vstep = 239 / 1024;
- var uoffset = 60 / 1024;
- var voffset = 26 / 1024;
- // Second island should have margin, not to touch the first island
- // avoid any borderline artefact in pixel rounding
- var island_u_offset = -40 / 1024;
- var island_v_offset = +20 / 1024;
- // face is either island 0 or 1 :
- // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
- var island = [
- 0, 0, 0, 0, 1,
- 0, 0, 1, 1, 0,
- 0, 0, 1, 1, 0,
- 0, 1, 1, 1, 0 // 15 - 19
- ];
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var current_indice = 0;
- // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
- var face_vertex_pos = new Array(3);
- var face_vertex_uv = new Array(3);
- var v012;
- for (v012 = 0; v012 < 3; v012++) {
- face_vertex_pos[v012] = BABYLON.Vector3.Zero();
- face_vertex_uv[v012] = BABYLON.Vector2.Zero();
- }
- // create all with normals
- for (var face = 0; face < 20; face++) {
- // 3 vertex per face
- for (v012 = 0; v012 < 3; v012++) {
- // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
- var v_id = ico_indices[3 * face + v012];
- // vertex have 3D position (x,y,z)
- 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]);
- // Normalize to get normal, then scale to radius
- face_vertex_pos[v012].normalize().scaleInPlace(radius);
- // uv Coordinates from vertex ID
- 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);
- }
- // Subdivide the face (interpolate pos, norm, uv)
- // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
- // - norm is linear interpolation of vertex corner normal
- // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
- // - uv is linear interpolation
- //
- // Topology is as below for sub-divide by 2
- // vertex shown as v0,v1,v2
- // interp index is i1 to progress in range [v0,v1[
- // interp index is i2 to progress in range [v0,v2[
- // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
- // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
- //
- //
- // i2 v2
- // ^ ^
- // / / \
- // / / \
- // / / \
- // / / (0,1) \
- // / #---------\
- // / / \ (0,0)'/ \
- // / / \ / \
- // / / \ / \
- // / / (0,0) \ / (1,0) \
- // / #---------#---------\
- // v0 v1
- //
- // --------------------> i1
- //
- // interp of (i1,i2):
- // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
- // along i1 : lerp(x0,x1, i1/(S-i2))
- //
- // centroid of triangle is needed to get help normal computation
- // (c1,c2) are used for centroid location
- var interp_vertex = function (i1, i2, c1, c2) {
- // vertex is interpolated from
- // - face_vertex_pos[0..2]
- // - face_vertex_uv[0..2]
- var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
- var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
- var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
- pos_interp.normalize();
- var vertex_normal;
- if (flat) {
- // in flat mode, recalculate normal as face centroid normal
- var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
- var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
- vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
- }
- else {
- // in smooth mode, recalculate normal from each single vertex position
- vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
- }
- // Vertex normal need correction due to X,Y,Z radius scaling
- vertex_normal.x /= radiusX;
- vertex_normal.y /= radiusY;
- vertex_normal.z /= radiusZ;
- vertex_normal.normalize();
- var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
- var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
- var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
- positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
- normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
- uvs.push(uv_interp.x, uv_interp.y);
- // push each vertex has member of a face
- // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
- indices.push(current_indice);
- current_indice++;
- };
- for (var i2 = 0; i2 < subdivisions; i2++) {
- for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
- // face : (i1,i2) for /\ :
- // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
- interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
- interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
- interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
- if (i1 + i2 + 1 < subdivisions) {
- // face : (i1,i2)' for \/ :
- // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
- interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
- interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
- interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
- }
- }
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
- VertexData.CreatePolyhedron = function (options) {
- // provided polyhedron types :
- // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
- // 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)
- var polyhedra = [];
- 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]] };
- 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]] };
- polyhedra[2] = {
- 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]],
- 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]]
- };
- polyhedra[3] = {
- 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]],
- 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]]
- };
- polyhedra[4] = {
- 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]],
- 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]]
- };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- polyhedra[14] = {
- 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]],
- 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]]
- };
- var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
- var size = options.size;
- var sizeX = options.sizeX || size || 1;
- var sizeY = options.sizeY || size || 1;
- var sizeZ = options.sizeZ || size || 1;
- var data = options.custom || polyhedra[type];
- var nbfaces = data.face.length;
- var faceUV = options.faceUV || new Array(nbfaces);
- var faceColors = options.faceColors;
- var flat = (options.flat === undefined) ? true : options.flat;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var colors = [];
- var index = 0;
- var faceIdx = 0; // face cursor in the array "indexes"
- var indexes = [];
- var i = 0;
- var f = 0;
- var u, v, ang, x, y, tmp;
- // default face colors and UV if undefined
- if (flat) {
- for (f = 0; f < nbfaces; f++) {
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- if (faceUV && faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- }
- }
- if (!flat) {
- for (i = 0; i < data.vertex.length; i++) {
- positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
- uvs.push(0, 0);
- }
- for (f = 0; f < nbfaces; f++) {
- for (i = 0; i < data.face[f].length - 2; i++) {
- indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
- }
- }
- }
- else {
- for (f = 0; f < nbfaces; f++) {
- var fl = data.face[f].length; // number of vertices of the current face
- ang = 2 * Math.PI / fl;
- x = 0.5 * Math.tan(ang / 2);
- y = 0.5;
- // positions, uvs, colors
- for (i = 0; i < fl; i++) {
- // positions
- 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);
- indexes.push(index);
- index++;
- // uvs
- u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
- v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
- uvs.push(u, v);
- tmp = x * Math.cos(ang) - y * Math.sin(ang);
- y = x * Math.sin(ang) + y * Math.cos(ang);
- x = tmp;
- // colors
- if (faceColors) {
- colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
- }
- }
- // indices from indexes
- for (i = 0; i < fl - 2; i++) {
- indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
- }
- faceIdx += fl;
- }
- }
- VertexData.ComputeNormals(positions, indices, normals);
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.positions = positions;
- vertexData.indices = indices;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors && flat) {
- vertexData.colors = colors;
- }
- return vertexData;
- };
- // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
- VertexData.CreateTorusKnot = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var radius = options.radius || 2;
- var tube = options.tube || 0.5;
- var radialSegments = options.radialSegments || 32;
- var tubularSegments = options.tubularSegments || 32;
- var p = options.p || 2;
- var q = options.q || 3;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // Helper
- var getPos = function (angle) {
- var cu = Math.cos(angle);
- var su = Math.sin(angle);
- var quOverP = q / p * angle;
- var cs = Math.cos(quOverP);
- var tx = radius * (2 + cs) * 0.5 * cu;
- var ty = radius * (2 + cs) * su * 0.5;
- var tz = radius * Math.sin(quOverP) * 0.5;
- return new BABYLON.Vector3(tx, ty, tz);
- };
- // Vertices
- var i;
- var j;
- for (i = 0; i <= radialSegments; i++) {
- var modI = i % radialSegments;
- var u = modI / radialSegments * 2 * p * Math.PI;
- var p1 = getPos(u);
- var p2 = getPos(u + 0.01);
- var tang = p2.subtract(p1);
- var n = p2.add(p1);
- var bitan = BABYLON.Vector3.Cross(tang, n);
- n = BABYLON.Vector3.Cross(bitan, tang);
- bitan.normalize();
- n.normalize();
- for (j = 0; j < tubularSegments; j++) {
- var modJ = j % tubularSegments;
- var v = modJ / tubularSegments * 2 * Math.PI;
- var cx = -tube * Math.cos(v);
- var cy = tube * Math.sin(v);
- positions.push(p1.x + cx * n.x + cy * bitan.x);
- positions.push(p1.y + cx * n.y + cy * bitan.y);
- positions.push(p1.z + cx * n.z + cy * bitan.z);
- uvs.push(i / radialSegments);
- uvs.push(j / tubularSegments);
- }
- }
- for (i = 0; i < radialSegments; i++) {
- for (j = 0; j < tubularSegments; j++) {
- var jNext = (j + 1) % tubularSegments;
- var a = i * tubularSegments + j;
- var b = (i + 1) * tubularSegments + j;
- var c = (i + 1) * tubularSegments + jNext;
- var d = i * tubularSegments + jNext;
- indices.push(d);
- indices.push(b);
- indices.push(a);
- indices.push(d);
- indices.push(c);
- indices.push(b);
- }
- }
- // Normals
- VertexData.ComputeNormals(positions, indices, normals);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // Tools
- /**
- * @param {any} - positions (number[] or Float32Array)
- * @param {any} - indices (number[] or Uint16Array)
- * @param {any} - normals (number[] or Float32Array)
- */
- VertexData.ComputeNormals = function (positions, indices, normals) {
- var index = 0;
- var p1p2x = 0.0;
- var p1p2y = 0.0;
- var p1p2z = 0.0;
- var p3p2x = 0.0;
- var p3p2y = 0.0;
- var p3p2z = 0.0;
- var faceNormalx = 0.0;
- var faceNormaly = 0.0;
- var faceNormalz = 0.0;
- var length = 0.0;
- var i1 = 0;
- var i2 = 0;
- var i3 = 0;
- for (index = 0; index < positions.length; index++) {
- normals[index] = 0.0;
- }
- // indice triplet = 1 face
- var nbFaces = indices.length / 3;
- for (index = 0; index < nbFaces; index++) {
- i1 = indices[index * 3]; // get the indexes of each vertex of the face
- i2 = indices[index * 3 + 1];
- i3 = indices[index * 3 + 2];
- p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
- p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
- p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
- p3p2x = positions[i3 * 3] - positions[i2 * 3];
- p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
- p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
- faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
- faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
- faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
- length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
- length = (length === 0) ? 1.0 : length;
- faceNormalx /= length; // normalize this normal
- faceNormaly /= length;
- faceNormalz /= length;
- normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
- normals[i1 * 3 + 1] += faceNormaly;
- normals[i1 * 3 + 2] += faceNormalz;
- normals[i2 * 3] += faceNormalx;
- normals[i2 * 3 + 1] += faceNormaly;
- normals[i2 * 3 + 2] += faceNormalz;
- normals[i3 * 3] += faceNormalx;
- normals[i3 * 3 + 1] += faceNormaly;
- normals[i3 * 3 + 2] += faceNormalz;
- }
- // last normalization of each normal
- for (index = 0; index < normals.length / 3; index++) {
- faceNormalx = normals[index * 3];
- faceNormaly = normals[index * 3 + 1];
- faceNormalz = normals[index * 3 + 2];
- length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
- length = (length === 0) ? 1.0 : length;
- faceNormalx /= length;
- faceNormaly /= length;
- faceNormalz /= length;
- normals[index * 3] = faceNormalx;
- normals[index * 3 + 1] = faceNormaly;
- normals[index * 3 + 2] = faceNormalz;
- }
- };
- VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
- var li = indices.length;
- var ln = normals.length;
- var i;
- var n;
- sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- switch (sideOrientation) {
- case BABYLON.Mesh.FRONTSIDE:
- // nothing changed
- break;
- case BABYLON.Mesh.BACKSIDE:
- var tmp;
- // indices
- for (i = 0; i < li; i += 3) {
- tmp = indices[i];
- indices[i] = indices[i + 2];
- indices[i + 2] = tmp;
- }
- // normals
- for (n = 0; n < ln; n++) {
- normals[n] = -normals[n];
- }
- break;
- case BABYLON.Mesh.DOUBLESIDE:
- // positions
- var lp = positions.length;
- var l = lp / 3;
- for (var p = 0; p < lp; p++) {
- positions[lp + p] = positions[p];
- }
- // indices
- for (i = 0; i < li; i += 3) {
- indices[i + li] = indices[i + 2] + l;
- indices[i + 1 + li] = indices[i + 1] + l;
- indices[i + 2 + li] = indices[i] + l;
- }
- // normals
- for (n = 0; n < ln; n++) {
- normals[ln + n] = -normals[n];
- }
- // uvs
- var lu = uvs.length;
- for (var u = 0; u < lu; u++) {
- uvs[u + lu] = uvs[u];
- }
- break;
- }
- };
- VertexData.ImportVertexData = function (parsedVertexData, geometry) {
- var vertexData = new VertexData();
- // positions
- var positions = parsedVertexData.positions;
- if (positions) {
- vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
- }
- // normals
- var normals = parsedVertexData.normals;
- if (normals) {
- vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
- }
- // uvs
- var uvs = parsedVertexData.uvs;
- if (uvs) {
- vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
- }
- // uv2s
- var uv2s = parsedVertexData.uv2s;
- if (uv2s) {
- vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
- }
- // uv3s
- var uv3s = parsedVertexData.uv3s;
- if (uv3s) {
- vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
- }
- // uv4s
- var uv4s = parsedVertexData.uv4s;
- if (uv4s) {
- vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
- }
- // uv5s
- var uv5s = parsedVertexData.uv5s;
- if (uv5s) {
- vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
- }
- // uv6s
- var uv6s = parsedVertexData.uv6s;
- if (uv6s) {
- vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
- }
- // colors
- var colors = parsedVertexData.colors;
- if (colors) {
- vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
- }
- // matricesIndices
- var matricesIndices = parsedVertexData.matricesIndices;
- if (matricesIndices) {
- vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- // matricesWeights
- var matricesWeights = parsedVertexData.matricesWeights;
- if (matricesWeights) {
- vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- // indices
- var indices = parsedVertexData.indices;
- if (indices) {
- vertexData.indices = indices;
- }
- geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
- };
- return VertexData;
- })();
- BABYLON.VertexData = VertexData;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Tags = (function () {
- function Tags() {
- }
- Tags.EnableFor = function (obj) {
- obj._tags = obj._tags || {};
- obj.hasTags = function () {
- return Tags.HasTags(obj);
- };
- obj.addTags = function (tagsString) {
- return Tags.AddTagsTo(obj, tagsString);
- };
- obj.removeTags = function (tagsString) {
- return Tags.RemoveTagsFrom(obj, tagsString);
- };
- obj.matchesTagsQuery = function (tagsQuery) {
- return Tags.MatchesQuery(obj, tagsQuery);
- };
- };
- Tags.DisableFor = function (obj) {
- delete obj._tags;
- delete obj.hasTags;
- delete obj.addTags;
- delete obj.removeTags;
- delete obj.matchesTagsQuery;
- };
- Tags.HasTags = function (obj) {
- if (!obj._tags) {
- return false;
- }
- return !BABYLON.Tools.IsEmpty(obj._tags);
- };
- Tags.GetTags = function (obj, asString) {
- if (asString === void 0) { asString = true; }
- if (!obj._tags) {
- return null;
- }
- if (asString) {
- var tagsArray = [];
- for (var tag in obj._tags) {
- if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
- tagsArray.push(tag);
- }
- }
- return tagsArray.join(" ");
- }
- else {
- return obj._tags;
- }
- };
- // the tags 'true' and 'false' are reserved and cannot be used as tags
- // a tag cannot start with '||', '&&', and '!'
- // it cannot contain whitespaces
- Tags.AddTagsTo = function (obj, tagsString) {
- if (!tagsString) {
- return;
- }
- if (typeof tagsString !== "string") {
- return;
- }
- var tags = tagsString.split(" ");
- for (var t in tags) {
- Tags._AddTagTo(obj, tags[t]);
- }
- };
- Tags._AddTagTo = function (obj, tag) {
- tag = tag.trim();
- if (tag === "" || tag === "true" || tag === "false") {
- return;
- }
- if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
- return;
- }
- Tags.EnableFor(obj);
- obj._tags[tag] = true;
- };
- Tags.RemoveTagsFrom = function (obj, tagsString) {
- if (!Tags.HasTags(obj)) {
- return;
- }
- var tags = tagsString.split(" ");
- for (var t in tags) {
- Tags._RemoveTagFrom(obj, tags[t]);
- }
- };
- Tags._RemoveTagFrom = function (obj, tag) {
- delete obj._tags[tag];
- };
- Tags.MatchesQuery = function (obj, tagsQuery) {
- if (tagsQuery === undefined) {
- return true;
- }
- if (tagsQuery === "") {
- return Tags.HasTags(obj);
- }
- return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
- };
- return Tags;
- })();
- BABYLON.Tags = Tags;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var AndOrNotEvaluator = (function () {
- function AndOrNotEvaluator() {
- }
- AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
- if (!query.match(/\([^\(\)]*\)/g)) {
- query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
- }
- else {
- query = query.replace(/\([^\(\)]*\)/g, function (r) {
- // remove parenthesis
- r = r.slice(1, r.length - 1);
- return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
- });
- }
- if (query === "true") {
- return true;
- }
- if (query === "false") {
- return false;
- }
- return AndOrNotEvaluator.Eval(query, evaluateCallback);
- };
- AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
- evaluateCallback = evaluateCallback || (function (r) {
- return r === "true" ? true : false;
- });
- var result;
- var or = parenthesisContent.split("||");
- for (var i in or) {
- var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
- var and = ori.split("&&");
- if (and.length > 1) {
- for (var j = 0; j < and.length; ++j) {
- var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
- if (andj !== "true" && andj !== "false") {
- if (andj[0] === "!") {
- result = !evaluateCallback(andj.substring(1));
- }
- else {
- result = evaluateCallback(andj);
- }
- }
- else {
- result = andj === "true" ? true : false;
- }
- if (!result) {
- ori = "false";
- break;
- }
- }
- }
- if (result || ori === "true") {
- result = true;
- break;
- }
- // result equals false (or undefined)
- if (ori !== "true" && ori !== "false") {
- if (ori[0] === "!") {
- result = !evaluateCallback(ori.substring(1));
- }
- else {
- result = evaluateCallback(ori);
- }
- }
- else {
- result = ori === "true" ? true : false;
- }
- }
- // the whole parenthesis scope is replaced by 'true' or 'false'
- return result ? "true" : "false";
- };
- AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
- booleanString = booleanString.replace(/^[\s!]+/, function (r) {
- // remove whitespaces
- r = r.replace(/[\s]/g, function () { return ""; });
- return r.length % 2 ? "!" : "";
- });
- booleanString = booleanString.trim();
- if (booleanString === "!true") {
- booleanString = "false";
- }
- else if (booleanString === "!false") {
- booleanString = "true";
- }
- return booleanString;
- };
- return AndOrNotEvaluator;
- })();
- Internals.AndOrNotEvaluator = AndOrNotEvaluator;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPass = (function () {
- function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
- this._enabled = true;
- this._refCount = 0;
- this._name = name;
- this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
- this.setRenderList(renderList);
- this._renderTexture.onBeforeRender = beforeRender;
- this._renderTexture.onAfterRender = afterRender;
- this._scene = scene;
- this._renderList = renderList;
- }
- // private
- PostProcessRenderPass.prototype._incRefCount = function () {
- if (this._refCount === 0) {
- this._scene.customRenderTargets.push(this._renderTexture);
- }
- return ++this._refCount;
- };
- PostProcessRenderPass.prototype._decRefCount = function () {
- this._refCount--;
- if (this._refCount <= 0) {
- this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
- }
- return this._refCount;
- };
- PostProcessRenderPass.prototype._update = function () {
- this.setRenderList(this._renderList);
- };
- // public
- PostProcessRenderPass.prototype.setRenderList = function (renderList) {
- this._renderTexture.renderList = renderList;
- };
- PostProcessRenderPass.prototype.getRenderTexture = function () {
- return this._renderTexture;
- };
- return PostProcessRenderPass;
- })();
- BABYLON.PostProcessRenderPass = PostProcessRenderPass;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderEffect = (function () {
- function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
- this._engine = engine;
- this._name = name;
- this._singleInstance = singleInstance || true;
- this._getPostProcess = getPostProcess;
- this._cameras = [];
- this._indicesForCamera = [];
- this._postProcesses = {};
- this._renderPasses = {};
- this._renderEffectAsPasses = {};
- }
- Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
- get: function () {
- for (var index in this._postProcesses) {
- if (!this._postProcesses[index].isSupported) {
- return false;
- }
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- PostProcessRenderEffect.prototype._update = function () {
- for (var renderPassName in this._renderPasses) {
- this._renderPasses[renderPassName]._update();
- }
- };
- PostProcessRenderEffect.prototype.addPass = function (renderPass) {
- this._renderPasses[renderPass._name] = renderPass;
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.removePass = function (renderPass) {
- delete this._renderPasses[renderPass._name];
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
- this._renderEffectAsPasses[renderEffect._name] = renderEffect;
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.getPass = function (passName) {
- for (var renderPassName in this._renderPasses) {
- if (renderPassName === passName) {
- return this._renderPasses[passName];
- }
- }
- };
- PostProcessRenderEffect.prototype.emptyPasses = function () {
- this._renderPasses = {};
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
- var cameraKey;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- if (this._singleInstance) {
- cameraKey = 0;
- }
- else {
- cameraKey = cameraName;
- }
- this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
- var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
- if (!this._indicesForCamera[cameraName]) {
- this._indicesForCamera[cameraName] = [];
- }
- this._indicesForCamera[cameraName].push(index);
- if (this._cameras.indexOf(camera) === -1) {
- this._cameras[cameraName] = camera;
- }
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._incRefCount();
- }
- }
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
- var index = this._cameras.indexOf(cameraName);
- this._indicesForCamera.splice(index, 1);
- this._cameras.splice(index, 1);
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._decRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype._enable = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
- if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
- cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
- }
- }
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._incRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype._disable = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.Name;
- camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._decRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
- if (this._singleInstance) {
- return this._postProcesses[0];
- }
- else {
- return this._postProcesses[camera.name];
- }
- };
- PostProcessRenderEffect.prototype._linkParameters = function () {
- var _this = this;
- for (var index in this._postProcesses) {
- if (this.applyParameters) {
- this.applyParameters(this._postProcesses[index]);
- }
- this._postProcesses[index].onBeforeRender = function (effect) {
- _this._linkTextures(effect);
- };
- }
- };
- PostProcessRenderEffect.prototype._linkTextures = function (effect) {
- for (var renderPassName in this._renderPasses) {
- effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
- }
- for (var renderEffectName in this._renderEffectAsPasses) {
- effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
- }
- };
- return PostProcessRenderEffect;
- })();
- BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPipeline = (function () {
- function PostProcessRenderPipeline(engine, name) {
- this._engine = engine;
- this._name = name;
- this._renderEffects = {};
- this._renderEffectsForIsolatedPass = {};
- this._cameras = [];
- }
- Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
- get: function () {
- for (var renderEffectName in this._renderEffects) {
- if (!this._renderEffects[renderEffectName].isSupported) {
- return false;
- }
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
- this._renderEffects[renderEffect._name] = renderEffect;
- };
- PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
- var renderEffects = this._renderEffects[renderEffectName];
- if (!renderEffects) {
- return;
- }
- renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
- };
- PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
- var renderEffects = this._renderEffects[renderEffectName];
- if (!renderEffects) {
- return;
- }
- renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
- };
- PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- var indicesToDelete = [];
- var i;
- for (i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- if (this._cameras.indexOf(camera) === -1) {
- this._cameras[cameraName] = camera;
- }
- else if (unique) {
- indicesToDelete.push(i);
- }
- }
- for (i = 0; i < indicesToDelete.length; i++) {
- cameras.splice(indicesToDelete[i], 1);
- }
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._attachCameras(_cam);
- }
- };
- PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._detachCameras(_cam);
- }
- for (var i = 0; i < _cam.length; i++) {
- this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
- }
- };
- PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
- var _this = this;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- var pass = null;
- var renderEffectName;
- for (renderEffectName in this._renderEffects) {
- pass = this._renderEffects[renderEffectName].getPass(passName);
- if (pass != null) {
- break;
- }
- }
- if (pass === null) {
- return;
- }
- for (renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._disable(_cam);
- }
- pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
- this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
- this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
- this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
- }
- };
- PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
- var _this = this;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
- this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
- }
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._enable(_cam);
- }
- };
- PostProcessRenderPipeline.prototype._update = function () {
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._update();
- }
- for (var i = 0; i < this._cameras.length; i++) {
- var cameraName = this._cameras[i].name;
- if (this._renderEffectsForIsolatedPass[cameraName]) {
- this._renderEffectsForIsolatedPass[cameraName]._update();
- }
- }
- };
- PostProcessRenderPipeline.prototype.dispose = function () {
- // Must be implemented by children
- };
- PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
- PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
- return PostProcessRenderPipeline;
- })();
- BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPipelineManager = (function () {
- function PostProcessRenderPipelineManager() {
- this._renderPipelines = {};
- }
- PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
- this._renderPipelines[renderPipeline._name] = renderPipeline;
- };
- PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._attachCameras(cameras, unique);
- };
- PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._detachCameras(cameras);
- };
- PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._enableEffect(renderEffectName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._disableEffect(renderEffectName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._enableDisplayOnlyPass(passName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._disableDisplayOnlyPass(cameras);
- };
- PostProcessRenderPipelineManager.prototype.update = function () {
- for (var renderPipelineName in this._renderPipelines) {
- var pipeline = this._renderPipelines[renderPipelineName];
- if (!pipeline.isSupported) {
- pipeline.dispose();
- delete this._renderPipelines[renderPipelineName];
- }
- else {
- pipeline._update();
- }
- }
- };
- return PostProcessRenderPipelineManager;
- })();
- BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingBoxRenderer = (function () {
- function BoundingBoxRenderer(scene) {
- this.frontColor = new BABYLON.Color3(1, 1, 1);
- this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
- this.showBackLines = true;
- this.renderList = new BABYLON.SmartArray(32);
- this._scene = scene;
- }
- BoundingBoxRenderer.prototype._prepareRessources = function () {
- if (this._colorShader) {
- return;
- }
- this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
- attributes: ["position"],
- uniforms: ["worldViewProjection", "color"]
- });
- var engine = this._scene.getEngine();
- var boxdata = BABYLON.VertexData.CreateBox(1.0);
- this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
- this._ib = 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]);
- };
- BoundingBoxRenderer.prototype.reset = function () {
- this.renderList.reset();
- };
- BoundingBoxRenderer.prototype.render = function () {
- if (this.renderList.length === 0) {
- return;
- }
- this._prepareRessources();
- if (!this._colorShader.isReady()) {
- return;
- }
- var engine = this._scene.getEngine();
- engine.setDepthWrite(false);
- this._colorShader._preBind();
- for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
- var boundingBox = this.renderList.data[boundingBoxIndex];
- var min = boundingBox.minimum;
- var max = boundingBox.maximum;
- var diff = max.subtract(min);
- var median = min.add(diff.scale(0.5));
- var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
- .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
- .multiply(boundingBox.getWorldMatrix());
- // VBOs
- engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
- if (this.showBackLines) {
- // Back
- engine.setDepthFunctionToGreaterOrEqual();
- this._scene.resetCachedMaterial();
- this._colorShader.setColor4("color", this.backColor.toColor4());
- this._colorShader.bind(worldMatrix);
- // Draw order
- engine.draw(false, 0, 24);
- }
- // Front
- engine.setDepthFunctionToLess();
- this._scene.resetCachedMaterial();
- this._colorShader.setColor4("color", this.frontColor.toColor4());
- this._colorShader.bind(worldMatrix);
- // Draw order
- engine.draw(false, 0, 24);
- }
- this._colorShader.unbind();
- engine.setDepthFunctionToLessOrEqual();
- engine.setDepthWrite(true);
- };
- BoundingBoxRenderer.prototype.dispose = function () {
- if (!this._colorShader) {
- return;
- }
- this._colorShader.dispose();
- this._vb.dispose();
- this._scene.getEngine()._releaseBuffer(this._ib);
- };
- return BoundingBoxRenderer;
- })();
- BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Condition = (function () {
- function Condition(actionManager) {
- this._actionManager = actionManager;
- }
- Condition.prototype.isValid = function () {
- return true;
- };
- Condition.prototype._getProperty = function (propertyPath) {
- return this._actionManager._getProperty(propertyPath);
- };
- Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
- return this._actionManager._getEffectiveTarget(target, propertyPath);
- };
- return Condition;
- })();
- BABYLON.Condition = Condition;
- var ValueCondition = (function (_super) {
- __extends(ValueCondition, _super);
- function ValueCondition(actionManager, target, propertyPath, value, operator) {
- if (operator === void 0) { operator = ValueCondition.IsEqual; }
- _super.call(this, actionManager);
- this.propertyPath = propertyPath;
- this.value = value;
- this.operator = operator;
- this._target = this._getEffectiveTarget(target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- }
- Object.defineProperty(ValueCondition, "IsEqual", {
- get: function () {
- return ValueCondition._IsEqual;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsDifferent", {
- get: function () {
- return ValueCondition._IsDifferent;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsGreater", {
- get: function () {
- return ValueCondition._IsGreater;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsLesser", {
- get: function () {
- return ValueCondition._IsLesser;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- ValueCondition.prototype.isValid = function () {
- switch (this.operator) {
- case ValueCondition.IsGreater:
- return this._target[this._property] > this.value;
- case ValueCondition.IsLesser:
- return this._target[this._property] < this.value;
- case ValueCondition.IsEqual:
- case ValueCondition.IsDifferent:
- var check;
- if (this.value.equals) {
- check = this.value.equals(this._target[this._property]);
- }
- else {
- check = this.value === this._target[this._property];
- }
- return this.operator === ValueCondition.IsEqual ? check : !check;
- }
- return false;
- };
- // Statics
- ValueCondition._IsEqual = 0;
- ValueCondition._IsDifferent = 1;
- ValueCondition._IsGreater = 2;
- ValueCondition._IsLesser = 3;
- return ValueCondition;
- })(Condition);
- BABYLON.ValueCondition = ValueCondition;
- var PredicateCondition = (function (_super) {
- __extends(PredicateCondition, _super);
- function PredicateCondition(actionManager, predicate) {
- _super.call(this, actionManager);
- this.predicate = predicate;
- }
- PredicateCondition.prototype.isValid = function () {
- return this.predicate();
- };
- return PredicateCondition;
- })(Condition);
- BABYLON.PredicateCondition = PredicateCondition;
- var StateCondition = (function (_super) {
- __extends(StateCondition, _super);
- function StateCondition(actionManager, target, value) {
- _super.call(this, actionManager);
- this.value = value;
- this._target = target;
- }
- // Methods
- StateCondition.prototype.isValid = function () {
- return this._target.state === this.value;
- };
- return StateCondition;
- })(Condition);
- BABYLON.StateCondition = StateCondition;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Action = (function () {
- function Action(triggerOptions, condition) {
- this.triggerOptions = triggerOptions;
- if (triggerOptions.parameter) {
- this.trigger = triggerOptions.trigger;
- this._triggerParameter = triggerOptions.parameter;
- }
- else {
- this.trigger = triggerOptions;
- }
- this._nextActiveAction = this;
- this._condition = condition;
- }
- // Methods
- Action.prototype._prepare = function () {
- };
- Action.prototype.getTriggerParameter = function () {
- return this._triggerParameter;
- };
- Action.prototype._executeCurrent = function (evt) {
- if (this._nextActiveAction._condition) {
- var condition = this._nextActiveAction._condition;
- var currentRenderId = this._actionManager.getScene().getRenderId();
- // We cache the current evaluation for the current frame
- if (condition._evaluationId === currentRenderId) {
- if (!condition._currentResult) {
- return;
- }
- }
- else {
- condition._evaluationId = currentRenderId;
- if (!condition.isValid()) {
- condition._currentResult = false;
- return;
- }
- condition._currentResult = true;
- }
- }
- this._nextActiveAction.execute(evt);
- this.skipToNextActiveAction();
- };
- Action.prototype.execute = function (evt) {
- };
- Action.prototype.skipToNextActiveAction = function () {
- if (this._nextActiveAction._child) {
- if (!this._nextActiveAction._child._actionManager) {
- this._nextActiveAction._child._actionManager = this._actionManager;
- }
- this._nextActiveAction = this._nextActiveAction._child;
- }
- else {
- this._nextActiveAction = this;
- }
- };
- Action.prototype.then = function (action) {
- this._child = action;
- action._actionManager = this._actionManager;
- action._prepare();
- return action;
- };
- Action.prototype._getProperty = function (propertyPath) {
- return this._actionManager._getProperty(propertyPath);
- };
- Action.prototype._getEffectiveTarget = function (target, propertyPath) {
- return this._actionManager._getEffectiveTarget(target, propertyPath);
- };
- return Action;
- })();
- BABYLON.Action = Action;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * ActionEvent is the event beint sent when an action is triggered.
- */
- var ActionEvent = (function () {
- /**
- * @constructor
- * @param source The mesh or sprite that triggered the action.
- * @param pointerX The X mouse cursor position at the time of the event
- * @param pointerY The Y mouse cursor position at the time of the event
- * @param meshUnderPointer The mesh that is currently pointed at (can be null)
- * @param sourceEvent the original (browser) event that triggered the ActionEvent
- */
- function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
- this.source = source;
- this.pointerX = pointerX;
- this.pointerY = pointerY;
- this.meshUnderPointer = meshUnderPointer;
- this.sourceEvent = sourceEvent;
- this.additionalData = additionalData;
- }
- /**
- * Helper function to auto-create an ActionEvent from a source mesh.
- * @param source The source mesh that triggered the event
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNew = function (source, evt, additionalData) {
- var scene = source.getScene();
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
- };
- /**
- * Helper function to auto-create an ActionEvent from a source mesh.
- * @param source The source sprite that triggered the event
- * @param scene Scene associated with the sprite
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
- };
- /**
- * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
- * @param scene the scene where the event occurred
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNewFromScene = function (scene, evt) {
- return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
- };
- return ActionEvent;
- })();
- BABYLON.ActionEvent = ActionEvent;
- /**
- * Action Manager manages all events to be triggered on a given mesh or the global scene.
- * A single scene can have many Action Managers to handle predefined actions on specific meshes.
- */
- var ActionManager = (function () {
- function ActionManager(scene) {
- // Members
- this.actions = new Array();
- this._scene = scene;
- scene._actionManagers.push(this);
- }
- Object.defineProperty(ActionManager, "NothingTrigger", {
- get: function () {
- return ActionManager._NothingTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickTrigger", {
- get: function () {
- return ActionManager._OnPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
- get: function () {
- return ActionManager._OnLeftPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnRightPickTrigger", {
- get: function () {
- return ActionManager._OnRightPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
- get: function () {
- return ActionManager._OnCenterPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickDownTrigger", {
- get: function () {
- return ActionManager._OnPickDownTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickUpTrigger", {
- get: function () {
- return ActionManager._OnPickUpTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickOutTrigger", {
- /// This trigger will only be raised if you also declared a OnPickDown
- get: function () {
- return ActionManager._OnPickOutTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnLongPressTrigger", {
- get: function () {
- return ActionManager._OnLongPressTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
- get: function () {
- return ActionManager._OnPointerOverTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
- get: function () {
- return ActionManager._OnPointerOutTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
- get: function () {
- return ActionManager._OnEveryFrameTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
- get: function () {
- return ActionManager._OnIntersectionEnterTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
- get: function () {
- return ActionManager._OnIntersectionExitTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
- get: function () {
- return ActionManager._OnKeyDownTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
- get: function () {
- return ActionManager._OnKeyUpTrigger;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- ActionManager.prototype.dispose = function () {
- var index = this._scene._actionManagers.indexOf(this);
- if (index > -1) {
- this._scene._actionManagers.splice(index, 1);
- }
- };
- ActionManager.prototype.getScene = function () {
- return this._scene;
- };
- /**
- * Does this action manager handles actions of any of the given triggers
- * @param {number[]} triggers - the triggers to be tested
- * @return {boolean} whether one (or more) of the triggers is handeled
- */
- ActionManager.prototype.hasSpecificTriggers = function (triggers) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (triggers.indexOf(action.trigger) > -1) {
- return true;
- }
- }
- return false;
- };
- /**
- * Does this action manager handles actions of a given trigger
- * @param {number} trigger - the trigger to be tested
- * @return {boolean} whether the trigger is handeled
- */
- ActionManager.prototype.hasSpecificTrigger = function (trigger) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger === trigger) {
- return true;
- }
- }
- return false;
- };
- Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
- /**
- * Does this action manager has pointer triggers
- * @return {boolean} whether or not it has pointer triggers
- */
- get: function () {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
- return true;
- }
- }
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
- /**
- * Does this action manager has pick triggers
- * @return {boolean} whether or not it has pick triggers
- */
- get: function () {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
- return true;
- }
- }
- return false;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Registers an action to this action manager
- * @param {BABYLON.Action} action - the action to be registered
- * @return {BABYLON.Action} the action amended (prepared) after registration
- */
- ActionManager.prototype.registerAction = function (action) {
- if (action.trigger === ActionManager.OnEveryFrameTrigger) {
- if (this.getScene().actionManager !== this) {
- BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
- return null;
- }
- }
- this.actions.push(action);
- action._actionManager = this;
- action._prepare();
- return action;
- };
- /**
- * Process a specific trigger
- * @param {number} trigger - the trigger to process
- * @param evt {BABYLON.ActionEvent} the event details to be processed
- */
- ActionManager.prototype.processTrigger = function (trigger, evt) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger === trigger) {
- if (trigger === ActionManager.OnKeyUpTrigger
- || trigger === ActionManager.OnKeyDownTrigger) {
- var parameter = action.getTriggerParameter();
- if (parameter) {
- var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
- var actualkey = String.fromCharCode(unicode).toLowerCase();
- if (actualkey !== parameter.toLowerCase()) {
- continue;
- }
- }
- }
- action._executeCurrent(evt);
- }
- }
- };
- ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
- var properties = propertyPath.split(".");
- for (var index = 0; index < properties.length - 1; index++) {
- target = target[properties[index]];
- }
- return target;
- };
- ActionManager.prototype._getProperty = function (propertyPath) {
- var properties = propertyPath.split(".");
- return properties[properties.length - 1];
- };
- ActionManager.Parse = function (parsedActions, object, scene) {
- var actionManager = new BABYLON.ActionManager(scene);
- if (object === null)
- scene.actionManager = actionManager;
- else
- object.actionManager = actionManager;
- // instanciate a new object
- var instanciate = function (name, params) {
- var newInstance = Object.create(BABYLON[name].prototype);
- newInstance.constructor.apply(newInstance, params);
- return newInstance;
- };
- var parseParameter = function (name, value, target, propertyPath) {
- if (propertyPath === null) {
- // String, boolean or float
- var floatValue = parseFloat(value);
- if (value === "true" || value === "false")
- return value === "true";
- else
- return isNaN(floatValue) ? value : floatValue;
- }
- var effectiveTarget = propertyPath.split(".");
- var values = value.split(",");
- // Get effective Target
- for (var i = 0; i < effectiveTarget.length; i++) {
- target = target[effectiveTarget[i]];
- }
- // Return appropriate value with its type
- if (typeof (target) === "boolean")
- return values[0] === "true";
- if (typeof (target) === "string")
- return values[0];
- // Parameters with multiple values such as Vector3 etc.
- var split = new Array();
- for (var i = 0; i < values.length; i++)
- split.push(parseFloat(values[i]));
- if (target instanceof BABYLON.Vector3)
- return BABYLON.Vector3.FromArray(split);
- if (target instanceof BABYLON.Vector4)
- return BABYLON.Vector4.FromArray(split);
- if (target instanceof BABYLON.Color3)
- return BABYLON.Color3.FromArray(split);
- if (target instanceof BABYLON.Color4)
- return BABYLON.Color4.FromArray(split);
- return parseFloat(values[0]);
- };
- // traverse graph per trigger
- var traverse = function (parsedAction, trigger, condition, action, combineArray) {
- if (combineArray === void 0) { combineArray = null; }
- if (parsedAction.detached)
- return;
- var parameters = new Array();
- var target = null;
- var propertyPath = null;
- var combine = parsedAction.combine && parsedAction.combine.length > 0;
- // Parameters
- if (parsedAction.type === 2)
- parameters.push(actionManager);
- else
- parameters.push(trigger);
- if (combine) {
- var actions = new Array();
- for (var j = 0; j < parsedAction.combine.length; j++) {
- traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
- }
- parameters.push(actions);
- }
- else {
- for (var i = 0; i < parsedAction.properties.length; i++) {
- var value = parsedAction.properties[i].value;
- var name = parsedAction.properties[i].name;
- var targetType = parsedAction.properties[i].targetType;
- if (name === "target")
- if (targetType !== null && targetType === "SceneProperties")
- value = target = scene;
- else
- value = target = scene.getNodeByName(value);
- else if (name === "parent")
- value = scene.getNodeByName(value);
- else if (name === "sound")
- value = scene.getSoundByName(value);
- else if (name !== "propertyPath") {
- if (parsedAction.type === 2 && name === "operator")
- value = BABYLON.ValueCondition[value];
- else
- value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
- }
- else {
- propertyPath = value;
- }
- parameters.push(value);
- }
- }
- if (combineArray === null) {
- parameters.push(condition);
- }
- else {
- parameters.push(null);
- }
- // If interpolate value action
- if (parsedAction.name === "InterpolateValueAction") {
- var param = parameters[parameters.length - 2];
- parameters[parameters.length - 1] = param;
- parameters[parameters.length - 2] = condition;
- }
- // Action or condition(s) and not CombineAction
- var newAction = instanciate(parsedAction.name, parameters);
- if (newAction instanceof BABYLON.Condition && condition !== null) {
- var nothing = new BABYLON.DoNothingAction(trigger, condition);
- if (action)
- action.then(nothing);
- else
- actionManager.registerAction(nothing);
- action = nothing;
- }
- if (combineArray === null) {
- if (newAction instanceof BABYLON.Condition) {
- condition = newAction;
- newAction = action;
- }
- else {
- condition = null;
- if (action)
- action.then(newAction);
- else
- actionManager.registerAction(newAction);
- }
- }
- else {
- combineArray.push(newAction);
- }
- for (var i = 0; i < parsedAction.children.length; i++)
- traverse(parsedAction.children[i], trigger, condition, newAction, null);
- };
- // triggers
- for (var i = 0; i < parsedActions.children.length; i++) {
- var triggerParams;
- var trigger = parsedActions.children[i];
- if (trigger.properties.length > 0) {
- var param = trigger.properties[0].value;
- var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
- triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
- }
- else
- triggerParams = BABYLON.ActionManager[trigger.name];
- for (var j = 0; j < trigger.children.length; j++) {
- if (!trigger.detached)
- traverse(trigger.children[j], triggerParams, null, null);
- }
- }
- };
- // Statics
- ActionManager._NothingTrigger = 0;
- ActionManager._OnPickTrigger = 1;
- ActionManager._OnLeftPickTrigger = 2;
- ActionManager._OnRightPickTrigger = 3;
- ActionManager._OnCenterPickTrigger = 4;
- ActionManager._OnPickDownTrigger = 5;
- ActionManager._OnPickUpTrigger = 6;
- ActionManager._OnLongPressTrigger = 7;
- ActionManager._OnPointerOverTrigger = 8;
- ActionManager._OnPointerOutTrigger = 9;
- ActionManager._OnEveryFrameTrigger = 10;
- ActionManager._OnIntersectionEnterTrigger = 11;
- ActionManager._OnIntersectionExitTrigger = 12;
- ActionManager._OnKeyDownTrigger = 13;
- ActionManager._OnKeyUpTrigger = 14;
- ActionManager._OnPickOutTrigger = 15;
- ActionManager.DragMovementThreshold = 10; // in pixels
- ActionManager.LongPressDelay = 500; // in milliseconds
- return ActionManager;
- })();
- BABYLON.ActionManager = ActionManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var InterpolateValueAction = (function (_super) {
- __extends(InterpolateValueAction, _super);
- function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
- if (duration === void 0) { duration = 1000; }
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this.duration = duration;
- this.stopOtherAnimations = stopOtherAnimations;
- this.onInterpolationDone = onInterpolationDone;
- this._target = target;
- }
- InterpolateValueAction.prototype._prepare = function () {
- this._target = this._getEffectiveTarget(this._target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- InterpolateValueAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- var keys = [
- {
- frame: 0,
- value: this._target[this._property]
- }, {
- frame: 100,
- value: this.value
- }
- ];
- var dataType;
- if (typeof this.value === "number") {
- dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
- }
- else if (this.value instanceof BABYLON.Color3) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
- }
- else if (this.value instanceof BABYLON.Vector3) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
- }
- else if (this.value instanceof BABYLON.Matrix) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
- }
- else if (this.value instanceof BABYLON.Quaternion) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
- }
- else {
- BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
- return;
- }
- var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
- animation.setKeys(keys);
- if (this.stopOtherAnimations) {
- scene.stopAnimation(this._target);
- }
- scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
- };
- return InterpolateValueAction;
- })(BABYLON.Action);
- BABYLON.InterpolateValueAction = InterpolateValueAction;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SwitchBooleanAction = (function (_super) {
- __extends(SwitchBooleanAction, _super);
- function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this._target = target;
- }
- SwitchBooleanAction.prototype._prepare = function () {
- this._target = this._getEffectiveTarget(this._target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- SwitchBooleanAction.prototype.execute = function () {
- this._target[this._property] = !this._target[this._property];
- };
- return SwitchBooleanAction;
- })(BABYLON.Action);
- BABYLON.SwitchBooleanAction = SwitchBooleanAction;
- var SetStateAction = (function (_super) {
- __extends(SetStateAction, _super);
- function SetStateAction(triggerOptions, target, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.value = value;
- this._target = target;
- }
- SetStateAction.prototype.execute = function () {
- this._target.state = this.value;
- };
- return SetStateAction;
- })(BABYLON.Action);
- BABYLON.SetStateAction = SetStateAction;
- var SetValueAction = (function (_super) {
- __extends(SetValueAction, _super);
- function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this._target = target;
- }
- SetValueAction.prototype._prepare = function () {
- this._target = this._getEffectiveTarget(this._target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- SetValueAction.prototype.execute = function () {
- this._target[this._property] = this.value;
- };
- return SetValueAction;
- })(BABYLON.Action);
- BABYLON.SetValueAction = SetValueAction;
- var IncrementValueAction = (function (_super) {
- __extends(IncrementValueAction, _super);
- function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this._target = target;
- }
- IncrementValueAction.prototype._prepare = function () {
- this._target = this._getEffectiveTarget(this._target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- if (typeof this._target[this._property] !== "number") {
- BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
- }
- };
- IncrementValueAction.prototype.execute = function () {
- this._target[this._property] += this.value;
- };
- return IncrementValueAction;
- })(BABYLON.Action);
- BABYLON.IncrementValueAction = IncrementValueAction;
- var PlayAnimationAction = (function (_super) {
- __extends(PlayAnimationAction, _super);
- function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
- _super.call(this, triggerOptions, condition);
- this.from = from;
- this.to = to;
- this.loop = loop;
- this._target = target;
- }
- PlayAnimationAction.prototype._prepare = function () {
- };
- PlayAnimationAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- scene.beginAnimation(this._target, this.from, this.to, this.loop);
- };
- return PlayAnimationAction;
- })(BABYLON.Action);
- BABYLON.PlayAnimationAction = PlayAnimationAction;
- var StopAnimationAction = (function (_super) {
- __extends(StopAnimationAction, _super);
- function StopAnimationAction(triggerOptions, target, condition) {
- _super.call(this, triggerOptions, condition);
- this._target = target;
- }
- StopAnimationAction.prototype._prepare = function () {
- };
- StopAnimationAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- scene.stopAnimation(this._target);
- };
- return StopAnimationAction;
- })(BABYLON.Action);
- BABYLON.StopAnimationAction = StopAnimationAction;
- var DoNothingAction = (function (_super) {
- __extends(DoNothingAction, _super);
- function DoNothingAction(triggerOptions, condition) {
- if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
- _super.call(this, triggerOptions, condition);
- }
- DoNothingAction.prototype.execute = function () {
- };
- return DoNothingAction;
- })(BABYLON.Action);
- BABYLON.DoNothingAction = DoNothingAction;
- var CombineAction = (function (_super) {
- __extends(CombineAction, _super);
- function CombineAction(triggerOptions, children, condition) {
- _super.call(this, triggerOptions, condition);
- this.children = children;
- }
- CombineAction.prototype._prepare = function () {
- for (var index = 0; index < this.children.length; index++) {
- this.children[index]._actionManager = this._actionManager;
- this.children[index]._prepare();
- }
- };
- CombineAction.prototype.execute = function (evt) {
- for (var index = 0; index < this.children.length; index++) {
- this.children[index].execute(evt);
- }
- };
- return CombineAction;
- })(BABYLON.Action);
- BABYLON.CombineAction = CombineAction;
- var ExecuteCodeAction = (function (_super) {
- __extends(ExecuteCodeAction, _super);
- function ExecuteCodeAction(triggerOptions, func, condition) {
- _super.call(this, triggerOptions, condition);
- this.func = func;
- }
- ExecuteCodeAction.prototype.execute = function (evt) {
- this.func(evt);
- };
- return ExecuteCodeAction;
- })(BABYLON.Action);
- BABYLON.ExecuteCodeAction = ExecuteCodeAction;
- var SetParentAction = (function (_super) {
- __extends(SetParentAction, _super);
- function SetParentAction(triggerOptions, target, parent, condition) {
- _super.call(this, triggerOptions, condition);
- this._target = target;
- this._parent = parent;
- }
- SetParentAction.prototype._prepare = function () {
- };
- SetParentAction.prototype.execute = function () {
- if (this._target.parent === this._parent) {
- return;
- }
- var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
- this._target.parent = this._parent;
- };
- return SetParentAction;
- })(BABYLON.Action);
- BABYLON.SetParentAction = SetParentAction;
- var PlaySoundAction = (function (_super) {
- __extends(PlaySoundAction, _super);
- function PlaySoundAction(triggerOptions, sound, condition) {
- _super.call(this, triggerOptions, condition);
- this._sound = sound;
- }
- PlaySoundAction.prototype._prepare = function () {
- };
- PlaySoundAction.prototype.execute = function () {
- if (this._sound !== undefined)
- this._sound.play();
- };
- return PlaySoundAction;
- })(BABYLON.Action);
- BABYLON.PlaySoundAction = PlaySoundAction;
- var StopSoundAction = (function (_super) {
- __extends(StopSoundAction, _super);
- function StopSoundAction(triggerOptions, sound, condition) {
- _super.call(this, triggerOptions, condition);
- this._sound = sound;
- }
- StopSoundAction.prototype._prepare = function () {
- };
- StopSoundAction.prototype.execute = function () {
- if (this._sound !== undefined)
- this._sound.stop();
- };
- return StopSoundAction;
- })(BABYLON.Action);
- BABYLON.StopSoundAction = StopSoundAction;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Geometry = (function () {
- function Geometry(id, scene, vertexData, updatable, mesh) {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this._totalVertices = 0;
- this._isDisposed = false;
- this.id = id;
- this._engine = scene.getEngine();
- this._meshes = [];
- this._scene = scene;
- //Init vertex buffer cache
- this._vertexBuffers = {};
- this._indices = [];
- // vertexData
- if (vertexData) {
- this.setAllVerticesData(vertexData, updatable);
- }
- else {
- this._totalVertices = 0;
- this._indices = [];
- }
- // applyToMesh
- if (mesh) {
- this.applyToMesh(mesh);
- mesh.computeWorldMatrix(true);
- }
- }
- Object.defineProperty(Geometry.prototype, "extend", {
- get: function () {
- return this._extend;
- },
- enumerable: true,
- configurable: true
- });
- Geometry.prototype.getScene = function () {
- return this._scene;
- };
- Geometry.prototype.getEngine = function () {
- return this._engine;
- };
- Geometry.prototype.isReady = function () {
- return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
- };
- Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
- vertexData.applyToGeometry(this, updatable);
- this.notifyUpdate();
- };
- Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (this._vertexBuffers[kind]) {
- this._vertexBuffers[kind].dispose();
- }
- this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- stride = this._vertexBuffers[kind].getStrideSize();
- this._totalVertices = data.length / stride;
- this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- mesh._resetPointsArrayCache();
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh();
- mesh.computeWorldMatrix(true);
- }
- }
- this.notifyUpdate(kind);
- };
- Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return;
- }
- vertexBuffer.updateDirectly(data, offset);
- this.notifyUpdate(kind);
- };
- Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return;
- }
- vertexBuffer.update(data);
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- var stride = vertexBuffer.getStrideSize();
- this._totalVertices = data.length / stride;
- if (updateExtends) {
- this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
- }
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- mesh._resetPointsArrayCache();
- if (updateExtends) {
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- subMesh.refreshBoundingInfo();
- }
- }
- }
- }
- this.notifyUpdate(kind);
- };
- Geometry.prototype.getTotalVertices = function () {
- if (!this.isReady()) {
- return 0;
- }
- return this._totalVertices;
- };
- Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return null;
- }
- var orig = vertexBuffer.getData();
- if (!copyWhenShared || this._meshes.length === 1) {
- return orig;
- }
- else {
- var len = orig.length;
- var copy = [];
- for (var i = 0; i < len; i++) {
- copy.push(orig[i]);
- }
- return copy;
- }
- };
- Geometry.prototype.getVertexBuffer = function (kind) {
- if (!this.isReady()) {
- return null;
- }
- return this._vertexBuffers[kind];
- };
- Geometry.prototype.getVertexBuffers = function () {
- if (!this.isReady()) {
- return null;
- }
- return this._vertexBuffers;
- };
- Geometry.prototype.isVerticesDataPresent = function (kind) {
- if (!this._vertexBuffers) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._vertexBuffers[kind] !== undefined;
- };
- Geometry.prototype.getVerticesDataKinds = function () {
- var result = [];
- var kind;
- if (!this._vertexBuffers && this._delayInfo) {
- for (kind in this._delayInfo) {
- result.push(kind);
- }
- }
- else {
- for (kind in this._vertexBuffers) {
- result.push(kind);
- }
- }
- return result;
- };
- Geometry.prototype.setIndices = function (indices, totalVertices) {
- if (this._indexBuffer) {
- this._engine._releaseBuffer(this._indexBuffer);
- }
- this._indices = indices;
- if (this._meshes.length !== 0 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices);
- }
- if (totalVertices !== undefined) {
- this._totalVertices = totalVertices;
- }
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- meshes[index]._createGlobalSubMesh();
- }
- this.notifyUpdate();
- };
- Geometry.prototype.getTotalIndices = function () {
- if (!this.isReady()) {
- return 0;
- }
- return this._indices.length;
- };
- Geometry.prototype.getIndices = function (copyWhenShared) {
- if (!this.isReady()) {
- return null;
- }
- var orig = this._indices;
- if (!copyWhenShared || this._meshes.length === 1) {
- return orig;
- }
- else {
- var len = orig.length;
- var copy = [];
- for (var i = 0; i < len; i++) {
- copy.push(orig[i]);
- }
- return copy;
- }
- };
- Geometry.prototype.getIndexBuffer = function () {
- if (!this.isReady()) {
- return null;
- }
- return this._indexBuffer;
- };
- Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
- var meshes = this._meshes;
- var index = meshes.indexOf(mesh);
- if (index === -1) {
- return;
- }
- for (var kind in this._vertexBuffers) {
- this._vertexBuffers[kind].dispose();
- }
- if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
- this._indexBuffer = null;
- }
- meshes.splice(index, 1);
- mesh._geometry = null;
- if (meshes.length === 0 && shouldDispose) {
- this.dispose();
- }
- };
- Geometry.prototype.applyToMesh = function (mesh) {
- if (mesh._geometry === this) {
- return;
- }
- var previousGeometry = mesh._geometry;
- if (previousGeometry) {
- previousGeometry.releaseForMesh(mesh);
- }
- var meshes = this._meshes;
- // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
- mesh._geometry = this;
- this._scene.pushGeometry(this);
- meshes.push(mesh);
- if (this.isReady()) {
- this._applyToMesh(mesh);
- }
- else {
- mesh._boundingInfo = this._boundingInfo;
- }
- };
- Geometry.prototype._applyToMesh = function (mesh) {
- var numOfMeshes = this._meshes.length;
- // vertexBuffers
- for (var kind in this._vertexBuffers) {
- if (numOfMeshes === 1) {
- this._vertexBuffers[kind].create();
- }
- this._vertexBuffers[kind]._buffer.references = numOfMeshes;
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- mesh._resetPointsArrayCache();
- if (!this._extend) {
- this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
- }
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh();
- //bounding info was just created again, world matrix should be applied again.
- mesh._updateBoundingInfo();
- }
- }
- // indexBuffer
- if (numOfMeshes === 1 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices);
- }
- if (this._indexBuffer) {
- this._indexBuffer.references = numOfMeshes;
- }
- };
- Geometry.prototype.notifyUpdate = function (kind) {
- if (this.onGeometryUpdated) {
- this.onGeometryUpdated(this, kind);
- }
- };
- Geometry.prototype.load = function (scene, onLoaded) {
- var _this = this;
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return;
- }
- if (this.isReady()) {
- if (onLoaded) {
- onLoaded();
- }
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(this);
- BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
- _this._delayLoadingFunction(JSON.parse(data), _this);
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- _this._delayInfo = [];
- scene._removePendingData(_this);
- var meshes = _this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- _this._applyToMesh(meshes[index]);
- }
- if (onLoaded) {
- onLoaded();
- }
- }, function () { }, scene.database);
- };
- Geometry.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- Geometry.prototype.dispose = function () {
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- var index;
- for (index = 0; index < numOfMeshes; index++) {
- this.releaseForMesh(meshes[index]);
- }
- this._meshes = [];
- for (var kind in this._vertexBuffers) {
- this._vertexBuffers[kind].dispose();
- }
- this._vertexBuffers = [];
- this._totalVertices = 0;
- if (this._indexBuffer) {
- this._engine._releaseBuffer(this._indexBuffer);
- }
- this._indexBuffer = null;
- this._indices = [];
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.delayLoadingFile = null;
- this._delayLoadingFunction = null;
- this._delayInfo = [];
- this._boundingInfo = null;
- this._scene.removeGeometry(this);
- this._isDisposed = true;
- };
- Geometry.prototype.copy = function (id) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = [];
- var indices = this.getIndices();
- for (var index = 0; index < indices.length; index++) {
- vertexData.indices.push(indices[index]);
- }
- var updatable = false;
- var stopChecking = false;
- var kind;
- for (kind in this._vertexBuffers) {
- // using slice() to make a copy of the array and not just reference it
- var data = this.getVerticesData(kind);
- if (data instanceof Float32Array) {
- vertexData.set(new Float32Array(data), kind);
- }
- else {
- vertexData.set(data.slice(0), kind);
- }
- if (!stopChecking) {
- updatable = this.getVertexBuffer(kind).isUpdatable();
- stopChecking = !updatable;
- }
- }
- var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
- geometry.delayLoadState = this.delayLoadState;
- geometry.delayLoadingFile = this.delayLoadingFile;
- geometry._delayLoadingFunction = this._delayLoadingFunction;
- for (kind in this._delayInfo) {
- geometry._delayInfo = geometry._delayInfo || [];
- geometry._delayInfo.push(kind);
- }
- // Bounding info
- geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- return geometry;
- };
- Geometry.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.id = this.id;
- if (BABYLON.Tags.HasTags(this)) {
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- }
- return serializationObject;
- };
- Geometry.prototype.serializeVerticeData = function () {
- var serializationObject = this.serialize();
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- serializationObject.matricesIndices._isExpanded = true;
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- serializationObject.indices = this.getIndices();
- return serializationObject;
- };
- // Statics
- Geometry.ExtractFromMesh = function (mesh, id) {
- var geometry = mesh._geometry;
- if (!geometry) {
- return null;
- }
- return geometry.copy(id);
- };
- // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
- // be aware Math.random() could cause collisions
- Geometry.RandomId = function () {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
- return v.toString(16);
- });
- };
- Geometry.ImportGeometry = function (parsedGeometry, mesh) {
- var scene = mesh.getScene();
- // Geometry
- var geometryId = parsedGeometry.geometryId;
- if (geometryId) {
- var geometry = scene.getGeometryByID(geometryId);
- if (geometry) {
- geometry.applyToMesh(mesh);
- }
- }
- else if (parsedGeometry instanceof ArrayBuffer) {
- var binaryInfo = mesh._binaryInfo;
- if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
- var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
- }
- if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
- var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
- }
- if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
- var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
- }
- if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
- var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
- }
- if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
- var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
- }
- if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
- var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
- }
- if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
- var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
- }
- if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
- var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
- }
- if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
- var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
- }
- if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
- var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
- }
- if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
- var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
- }
- if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
- var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
- mesh.setIndices(indicesData);
- }
- if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
- var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
- mesh.subMeshes = [];
- for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
- var materialIndex = subMeshesData[(i * 5) + 0];
- var verticesStart = subMeshesData[(i * 5) + 1];
- var verticesCount = subMeshesData[(i * 5) + 2];
- var indexStart = subMeshesData[(i * 5) + 3];
- var indexCount = subMeshesData[(i * 5) + 4];
- var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
- }
- }
- }
- else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
- if (parsedGeometry.uvs) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
- }
- if (parsedGeometry.uvs2) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
- }
- if (parsedGeometry.uvs3) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
- }
- if (parsedGeometry.uvs4) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
- }
- if (parsedGeometry.uvs5) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
- }
- if (parsedGeometry.uvs6) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
- }
- if (parsedGeometry.colors) {
- mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
- }
- if (parsedGeometry.matricesIndices) {
- if (!parsedGeometry.matricesIndices._isExpanded) {
- var floatIndices = [];
- for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
- var matricesIndex = parsedGeometry.matricesIndices[i];
- floatIndices.push(matricesIndex & 0x000000FF);
- floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
- floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
- floatIndices.push(matricesIndex >> 24);
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
- }
- }
- if (parsedGeometry.matricesIndicesExtra) {
- if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
- var floatIndices = [];
- for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
- var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
- floatIndices.push(matricesIndex & 0x000000FF);
- floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
- floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
- floatIndices.push(matricesIndex >> 24);
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
- }
- }
- if (parsedGeometry.matricesWeights) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
- }
- if (parsedGeometry.matricesWeightsExtra) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
- }
- mesh.setIndices(parsedGeometry.indices);
- }
- // SubMeshes
- if (parsedGeometry.subMeshes) {
- mesh.subMeshes = [];
- for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
- var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
- var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
- }
- }
- // Flat shading
- if (mesh._shouldGenerateFlatShading) {
- mesh.convertToFlatShadedMesh();
- delete mesh._shouldGenerateFlatShading;
- }
- // Update
- mesh.computeWorldMatrix(true);
- // Octree
- if (scene['_selectionOctree']) {
- scene['_selectionOctree'].addMesh(mesh);
- }
- };
- Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
- if (scene.getGeometryByID(parsedVertexData.id)) {
- return null; // null since geometry could be something else than a box...
- }
- var geometry = new Geometry(parsedVertexData.id, scene);
- BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
- if (parsedVertexData.delayLoadingFile) {
- geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
- geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
- geometry._delayInfo = [];
- if (parsedVertexData.hasUVs) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
- }
- if (parsedVertexData.hasUVs2) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (parsedVertexData.hasUVs3) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
- }
- if (parsedVertexData.hasUVs4) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
- }
- if (parsedVertexData.hasUVs5) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
- }
- if (parsedVertexData.hasUVs6) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
- }
- if (parsedVertexData.hasColors) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
- }
- if (parsedVertexData.hasMatricesIndices) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- if (parsedVertexData.hasMatricesWeights) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
- }
- else {
- BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
- }
- scene.pushGeometry(geometry, true);
- return geometry;
- };
- return Geometry;
- })();
- BABYLON.Geometry = Geometry;
- /////// Primitives //////////////////////////////////////////////
- var Geometry;
- (function (Geometry) {
- var Primitives;
- (function (Primitives) {
- /// Abstract class
- var _Primitive = (function (_super) {
- __extends(_Primitive, _super);
- function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
- this._beingRegenerated = true;
- this._canBeRegenerated = canBeRegenerated;
- _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
- this._beingRegenerated = false;
- }
- _Primitive.prototype.canBeRegenerated = function () {
- return this._canBeRegenerated;
- };
- _Primitive.prototype.regenerate = function () {
- if (!this._canBeRegenerated) {
- return;
- }
- this._beingRegenerated = true;
- this.setAllVerticesData(this._regenerateVertexData(), false);
- this._beingRegenerated = false;
- };
- _Primitive.prototype.asNewGeometry = function (id) {
- return _super.prototype.copy.call(this, id);
- };
- // overrides
- _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setAllVerticesData.call(this, vertexData, false);
- };
- _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setVerticesData.call(this, kind, data, false);
- };
- // to override
- // protected
- _Primitive.prototype._regenerateVertexData = function () {
- throw new Error("Abstract method");
- };
- _Primitive.prototype.copy = function (id) {
- throw new Error("Must be overriden in sub-classes.");
- };
- _Primitive.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.canBeRegenerated = this.canBeRegenerated();
- return serializationObject;
- };
- return _Primitive;
- })(Geometry);
- Primitives._Primitive = _Primitive;
- var Ribbon = (function (_super) {
- __extends(Ribbon, _super);
- function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.pathArray = pathArray;
- this.closeArray = closeArray;
- this.closePath = closePath;
- this.offset = offset;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Ribbon.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
- };
- Ribbon.prototype.copy = function (id) {
- return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
- };
- return Ribbon;
- })(_Primitive);
- Primitives.Ribbon = Ribbon;
- var Box = (function (_super) {
- __extends(Box, _super);
- function Box(id, scene, size, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.size = size;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Box.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
- };
- Box.prototype.copy = function (id) {
- return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
- };
- Box.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- Box.Parse = function (parsedBox, scene) {
- if (scene.getGeometryByID(parsedBox.id)) {
- return null; // null since geometry could be something else than a box...
- }
- var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
- scene.pushGeometry(box, true);
- return box;
- };
- return Box;
- })(_Primitive);
- Primitives.Box = Box;
- var Sphere = (function (_super) {
- __extends(Sphere, _super);
- function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.segments = segments;
- this.diameter = diameter;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Sphere.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
- };
- Sphere.prototype.copy = function (id) {
- return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
- };
- Sphere.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.segments = this.segments;
- serializationObject.diameter = this.diameter;
- return serializationObject;
- };
- Sphere.Parse = function (parsedSphere, scene) {
- if (scene.getGeometryByID(parsedSphere.id)) {
- return null; // null since geometry could be something else than a sphere...
- }
- var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
- scene.pushGeometry(sphere, true);
- return sphere;
- };
- return Sphere;
- })(_Primitive);
- Primitives.Sphere = Sphere;
- var Disc = (function (_super) {
- __extends(Disc, _super);
- function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.radius = radius;
- this.tessellation = tessellation;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Disc.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
- };
- Disc.prototype.copy = function (id) {
- return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- return Disc;
- })(_Primitive);
- Primitives.Disc = Disc;
- var Cylinder = (function (_super) {
- __extends(Cylinder, _super);
- function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
- if (subdivisions === void 0) { subdivisions = 1; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.height = height;
- this.diameterTop = diameterTop;
- this.diameterBottom = diameterBottom;
- this.tessellation = tessellation;
- this.subdivisions = subdivisions;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Cylinder.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
- };
- Cylinder.prototype.copy = function (id) {
- return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
- };
- Cylinder.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.height = this.height;
- serializationObject.diameterTop = this.diameterTop;
- serializationObject.diameterBottom = this.diameterBottom;
- serializationObject.tessellation = this.tessellation;
- return serializationObject;
- };
- Cylinder.Parse = function (parsedCylinder, scene) {
- if (scene.getGeometryByID(parsedCylinder.id)) {
- return null; // null since geometry could be something else than a cylinder...
- }
- var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
- scene.pushGeometry(cylinder, true);
- return cylinder;
- };
- return Cylinder;
- })(_Primitive);
- Primitives.Cylinder = Cylinder;
- var Torus = (function (_super) {
- __extends(Torus, _super);
- function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.diameter = diameter;
- this.thickness = thickness;
- this.tessellation = tessellation;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Torus.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
- };
- Torus.prototype.copy = function (id) {
- return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- Torus.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.diameter = this.diameter;
- serializationObject.thickness = this.thickness;
- serializationObject.tessellation = this.tessellation;
- return serializationObject;
- };
- Torus.Parse = function (parsedTorus, scene) {
- if (scene.getGeometryByID(parsedTorus.id)) {
- return null; // null since geometry could be something else than a torus...
- }
- var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
- scene.pushGeometry(torus, true);
- return torus;
- };
- return Torus;
- })(_Primitive);
- Primitives.Torus = Torus;
- var Ground = (function (_super) {
- __extends(Ground, _super);
- function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
- this.width = width;
- this.height = height;
- this.subdivisions = subdivisions;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Ground.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
- };
- Ground.prototype.copy = function (id) {
- return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
- };
- Ground.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.width = this.width;
- serializationObject.height = this.height;
- serializationObject.subdivisions = this.subdivisions;
- return serializationObject;
- };
- Ground.Parse = function (parsedGround, scene) {
- if (scene.getGeometryByID(parsedGround.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
- scene.pushGeometry(ground, true);
- return ground;
- };
- return Ground;
- })(_Primitive);
- Primitives.Ground = Ground;
- var TiledGround = (function (_super) {
- __extends(TiledGround, _super);
- function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
- this.xmin = xmin;
- this.zmin = zmin;
- this.xmax = xmax;
- this.zmax = zmax;
- this.subdivisions = subdivisions;
- this.precision = precision;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- TiledGround.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
- };
- TiledGround.prototype.copy = function (id) {
- return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
- };
- return TiledGround;
- })(_Primitive);
- Primitives.TiledGround = TiledGround;
- var Plane = (function (_super) {
- __extends(Plane, _super);
- function Plane(id, scene, size, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.size = size;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- Plane.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
- };
- Plane.prototype.copy = function (id) {
- return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
- };
- Plane.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- Plane.Parse = function (parsedPlane, scene) {
- if (scene.getGeometryByID(parsedPlane.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
- scene.pushGeometry(plane, true);
- return plane;
- };
- return Plane;
- })(_Primitive);
- Primitives.Plane = Plane;
- var TorusKnot = (function (_super) {
- __extends(TorusKnot, _super);
- function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- this.radius = radius;
- this.tube = tube;
- this.radialSegments = radialSegments;
- this.tubularSegments = tubularSegments;
- this.p = p;
- this.q = q;
- this.side = side;
- _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
- }
- TorusKnot.prototype._regenerateVertexData = function () {
- 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 });
- };
- TorusKnot.prototype.copy = function (id) {
- return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
- };
- TorusKnot.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.radius = this.radius;
- serializationObject.tube = this.tube;
- serializationObject.radialSegments = this.radialSegments;
- serializationObject.tubularSegments = this.tubularSegments;
- serializationObject.p = this.p;
- serializationObject.q = this.q;
- return serializationObject;
- };
- ;
- TorusKnot.Parse = function (parsedTorusKnot, scene) {
- if (scene.getGeometryByID(parsedTorusKnot.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
- scene.pushGeometry(torusKnot, true);
- return torusKnot;
- };
- return TorusKnot;
- })(_Primitive);
- Primitives.TorusKnot = TorusKnot;
- })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
- })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var GroundMesh = (function (_super) {
- __extends(GroundMesh, _super);
- function GroundMesh(name, scene) {
- _super.call(this, name, scene);
- this.generateOctree = false;
- this._worldInverse = new BABYLON.Matrix();
- }
- Object.defineProperty(GroundMesh.prototype, "subdivisions", {
- get: function () {
- return this._subdivisions;
- },
- enumerable: true,
- configurable: true
- });
- GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
- if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
- this._subdivisions = chunksCount;
- this.subdivide(this._subdivisions);
- this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
- };
- /**
- * Returns a height (y) value in the Worl system :
- * the ground altitude at the coordinates (x, z) expressed in the World system.
- * Returns the ground y position if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
- // express x and y in the ground local system
- x -= this.position.x;
- z -= this.position.z;
- x /= this.scaling.x;
- z /= this.scaling.z;
- if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
- return this.position.y;
- }
- if (!this._heightQuads || this._heightQuads.length == 0) {
- this._computeHeightQuads();
- }
- var facet = this._getFacetAt(x, z);
- var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
- // return y in the World system
- return y * this.scaling.y + this.position.y;
- };
- /**
- * Returns a normalized vector (Vector3) orthogonal to the ground
- * at the ground coordinates (x, z) expressed in the World system.
- * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
- var normal = new BABYLON.Vector3(0, 1, 0);
- this.getNormalAtCoordinatesToRef(x, z, normal);
- return normal;
- };
- /**
- * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
- * at the ground coordinates (x, z) expressed in the World system.
- * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
- // express x and y in the ground local system
- x -= this.position.x;
- z -= this.position.z;
- x /= this.scaling.x;
- z /= this.scaling.z;
- if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
- return;
- }
- if (!this._heightQuads || this._heightQuads.length == 0) {
- this._computeHeightQuads();
- }
- var facet = this._getFacetAt(x, z);
- ref.x = facet.x;
- ref.y = facet.y;
- ref.z = facet.z;
- };
- // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
- GroundMesh.prototype._getFacetAt = function (x, z) {
- // retrieve col and row from x, z coordinates in the ground local system
- var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
- var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
- var quad = this._heightQuads[row * this._subdivisions + col];
- var facet;
- if (z < quad.slope.x * x + quad.slope.y) {
- facet = quad.facet1;
- }
- else {
- facet = quad.facet2;
- }
- return facet;
- };
- // Populates the heightMap array with "facet" elements :
- // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
- // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
- // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
- // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
- GroundMesh.prototype._computeHeightQuads = function () {
- this._heightQuads = new Array();
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var v1 = BABYLON.Vector3.Zero();
- var v2 = BABYLON.Vector3.Zero();
- var v3 = BABYLON.Vector3.Zero();
- var v4 = BABYLON.Vector3.Zero();
- var v1v2 = BABYLON.Vector3.Zero();
- var v1v3 = BABYLON.Vector3.Zero();
- var v1v4 = BABYLON.Vector3.Zero();
- var norm1 = BABYLON.Vector3.Zero();
- var norm2 = BABYLON.Vector3.Zero();
- var i = 0;
- var j = 0;
- var k = 0;
- var cd = 0; // 2D slope coefficient : z = cd * x + h
- var h = 0;
- var d1 = 0; // facet plane equation : ax + by + cz + d = 0
- var d2 = 0;
- for (var row = 0; row < this._subdivisions; row++) {
- for (var col = 0; col < this._subdivisions; col++) {
- i = col * 3;
- j = row * (this._subdivisions + 1) * 3;
- k = (row + 1) * (this._subdivisions + 1) * 3;
- v1.x = positions[j + i];
- v1.y = positions[j + i + 1];
- v1.z = positions[j + i + 2];
- v2.x = positions[j + i + 3];
- v2.y = positions[j + i + 4];
- v2.z = positions[j + i + 5];
- v3.x = positions[k + i];
- v3.y = positions[k + i + 1];
- v3.z = positions[k + i + 2];
- v4.x = positions[k + i + 3];
- v4.y = positions[k + i + 4];
- v4.z = positions[k + i + 5];
- // 2D slope V1V4
- cd = (v4.z - v1.z) / (v4.x - v1.x);
- h = v1.z - cd * v1.x; // v1 belongs to the slope
- var slope = new BABYLON.Vector2(cd, h);
- // facet equations :
- // we compute each facet normal vector
- // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
- // we compute the value d by applying the equation to v1 which belongs to the plane
- // then we store the facet equation in a Vector4
- v2.subtractToRef(v1, v1v2);
- v3.subtractToRef(v1, v1v3);
- v4.subtractToRef(v1, v1v4);
- BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
- BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
- norm1.normalize();
- norm2.normalize();
- d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
- d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
- var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
- var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
- var quad = { slope: slope, facet1: facet1, facet2: facet2 };
- this._heightQuads.push(quad);
- }
- }
- };
- return GroundMesh;
- })(BABYLON.Mesh);
- BABYLON.GroundMesh = GroundMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LinesMesh = (function (_super) {
- __extends(LinesMesh, _super);
- function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
- if (parent === void 0) { parent = null; }
- _super.call(this, name, scene, parent, source, doNotCloneChildren);
- this.color = new BABYLON.Color3(1, 1, 1);
- this.alpha = 1;
- this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
- attributes: ["position"],
- uniforms: ["worldViewProjection", "color"],
- needAlphaBlending: true
- });
- }
- Object.defineProperty(LinesMesh.prototype, "material", {
- get: function () {
- return this._colorShader;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(LinesMesh.prototype, "isPickable", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
- var engine = this.getScene().getEngine();
- var indexToBind = this._geometry.getIndexBuffer();
- // VBOs
- engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
- // Color
- this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
- };
- LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var engine = this.getScene().getEngine();
- // Draw order
- engine.draw(false, subMesh.indexStart, subMesh.indexCount);
- };
- LinesMesh.prototype.intersects = function (ray, fastCheck) {
- return null;
- };
- LinesMesh.prototype.dispose = function (doNotRecurse) {
- this._colorShader.dispose();
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
- };
- return LinesMesh;
- })(BABYLON.Mesh);
- BABYLON.LinesMesh = LinesMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DebugLayer = (function () {
- function DebugLayer(scene) {
- var _this = this;
- this._transformationMatrix = BABYLON.Matrix.Identity();
- this._enabled = false;
- this._labelsEnabled = false;
- this._displayStatistics = true;
- this._displayTree = false;
- this._displayLogs = false;
- this._identityMatrix = BABYLON.Matrix.Identity();
- this.axisRatio = 0.02;
- this.accentColor = "orange";
- this._scene = scene;
- this._syncPositions = function () {
- var engine = _this._scene.getEngine();
- var canvasRect = engine.getRenderingCanvasClientRect();
- if (_this._showUI) {
- _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
- _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
- _this._statsDiv.style.width = "400px";
- _this._statsDiv.style.height = "auto";
- _this._statsSubsetDiv.style.maxHeight = "240px";
- _this._optionsDiv.style.left = "0px";
- _this._optionsDiv.style.top = "10px";
- _this._optionsDiv.style.width = "200px";
- _this._optionsDiv.style.height = "auto";
- _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
- _this._logDiv.style.left = "0px";
- _this._logDiv.style.top = (canvasRect.height - 170) + "px";
- _this._logDiv.style.width = "600px";
- _this._logDiv.style.height = "160px";
- _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
- _this._treeDiv.style.top = "10px";
- _this._treeDiv.style.width = "300px";
- _this._treeDiv.style.height = "auto";
- _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
- }
- _this._globalDiv.style.left = canvasRect.left + "px";
- _this._globalDiv.style.top = canvasRect.top + "px";
- _this._drawingCanvas.style.left = "0px";
- _this._drawingCanvas.style.top = "0px";
- _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
- _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
- var devicePixelRatio = window.devicePixelRatio || 1;
- var context = _this._drawingContext;
- var backingStoreRatio = context.webkitBackingStorePixelRatio ||
- context.mozBackingStorePixelRatio ||
- context.msBackingStorePixelRatio ||
- context.oBackingStorePixelRatio ||
- context.backingStorePixelRatio || 1;
- _this._ratio = devicePixelRatio / backingStoreRatio;
- _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
- _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
- };
- this._onCanvasClick = function (evt) {
- _this._clickPosition = {
- x: evt.clientX * _this._ratio,
- y: evt.clientY * _this._ratio
- };
- };
- this._syncUI = function () {
- if (_this._showUI) {
- if (_this._displayStatistics) {
- _this._displayStats();
- _this._statsDiv.style.display = "";
- }
- else {
- _this._statsDiv.style.display = "none";
- }
- if (_this._displayLogs) {
- _this._logDiv.style.display = "";
- }
- else {
- _this._logDiv.style.display = "none";
- }
- if (_this._displayTree) {
- _this._treeDiv.style.display = "";
- if (_this._needToRefreshMeshesTree) {
- _this._needToRefreshMeshesTree = false;
- _this._refreshMeshesTreeContent();
- }
- }
- else {
- _this._treeDiv.style.display = "none";
- }
- }
- };
- this._syncData = function () {
- if (_this._labelsEnabled || !_this._showUI) {
- _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
- _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
- var engine = _this._scene.getEngine();
- var viewport = _this._camera.viewport;
- var globalViewport = viewport.toGlobal(engine);
- // Meshes
- var meshes = _this._camera.getActiveMeshes();
- var index;
- var projectedPosition;
- for (index = 0; index < meshes.length; index++) {
- var mesh = meshes.data[index];
- var position = mesh.getBoundingInfo().boundingSphere.center;
- projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
- if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
- _this._renderAxis(projectedPosition, mesh, globalViewport);
- }
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
- _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
- }
- }
- // Cameras
- var cameras = _this._scene.cameras;
- for (index = 0; index < cameras.length; index++) {
- var camera = cameras[index];
- if (camera === _this._camera) {
- continue;
- }
- projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
- _this._renderLabel(camera.name, projectedPosition, 12, function () {
- _this._camera.detachControl(engine.getRenderingCanvas());
- _this._camera = camera;
- _this._camera.attachControl(engine.getRenderingCanvas());
- }, function () { return "purple"; });
- }
- }
- // Lights
- var lights = _this._scene.lights;
- for (index = 0; index < lights.length; index++) {
- var light = lights[index];
- if (light.position) {
- projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
- _this._renderLabel(light.name, projectedPosition, -20, function () {
- light.setEnabled(!light.isEnabled());
- }, function () { return light.isEnabled() ? "orange" : "gray"; });
- }
- }
- }
- }
- _this._clickPosition = undefined;
- };
- }
- DebugLayer.prototype._refreshMeshesTreeContent = function () {
- while (this._treeSubsetDiv.hasChildNodes()) {
- this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
- }
- // Add meshes
- var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
- sortedArray.sort(function (a, b) {
- if (a.name === b.name) {
- return 0;
- }
- return (a.name > b.name) ? 1 : -1;
- });
- for (var index = 0; index < sortedArray.length; index++) {
- var mesh = sortedArray[index];
- if (!mesh.isEnabled()) {
- continue;
- }
- this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
- m.isVisible = element.checked;
- }, mesh);
- }
- };
- DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
- this._drawingContext.beginPath();
- this._drawingContext.moveTo(zero.x, zero.y);
- this._drawingContext.lineTo(unit.x, unit.y);
- this._drawingContext.strokeStyle = color;
- this._drawingContext.lineWidth = 4;
- this._drawingContext.stroke();
- this._drawingContext.font = "normal 14px Segoe UI";
- this._drawingContext.fillStyle = color;
- this._drawingContext.fillText(label, unitText.x, unitText.y);
- };
- DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
- var position = mesh.getBoundingInfo().boundingSphere.center;
- var worldMatrix = mesh.getWorldMatrix();
- var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
- var unit = (unprojectedVector.subtract(position)).length();
- var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
- var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
- var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
- var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
- };
- DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
- if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
- this._drawingContext.font = "normal 12px Segoe UI";
- var textMetrics = this._drawingContext.measureText(text);
- var centerX = projectedPosition.x - textMetrics.width / 2;
- var centerY = projectedPosition.y;
- var clientRect = this._drawingCanvas.getBoundingClientRect();
- if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
- onClick();
- }
- this._drawingContext.beginPath();
- this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
- this._drawingContext.fillStyle = getFillStyle();
- this._drawingContext.globalAlpha = 0.5;
- this._drawingContext.fill();
- this._drawingContext.globalAlpha = 1.0;
- this._drawingContext.strokeStyle = '#FFFFFF';
- this._drawingContext.lineWidth = 1;
- this._drawingContext.stroke();
- this._drawingContext.fillStyle = "#FFFFFF";
- this._drawingContext.fillText(text, centerX, centerY - labelOffset);
- this._drawingContext.beginPath();
- this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
- this._drawingContext.fill();
- }
- };
- DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
- if (!this._clickPosition) {
- return false;
- }
- if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
- return false;
- }
- if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
- return false;
- }
- return true;
- };
- DebugLayer.prototype.isVisible = function () {
- return this._enabled;
- };
- DebugLayer.prototype.hide = function () {
- if (!this._enabled) {
- return;
- }
- this._enabled = false;
- var engine = this._scene.getEngine();
- this._scene.unregisterBeforeRender(this._syncData);
- this._scene.unregisterAfterRender(this._syncUI);
- this._rootElement.removeChild(this._globalDiv);
- this._scene.forceShowBoundingBoxes = false;
- this._scene.forceWireframe = false;
- BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
- BABYLON.StandardMaterial.AmbientTextureEnabled = true;
- BABYLON.StandardMaterial.SpecularTextureEnabled = true;
- BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
- BABYLON.StandardMaterial.BumpTextureEnabled = true;
- BABYLON.StandardMaterial.OpacityTextureEnabled = true;
- BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
- BABYLON.StandardMaterial.LightmapTextureEnabled = true;
- BABYLON.StandardMaterial.RefractionTextureEnabled = true;
- this._scene.shadowsEnabled = true;
- this._scene.particlesEnabled = true;
- this._scene.postProcessesEnabled = true;
- this._scene.collisionsEnabled = true;
- this._scene.lightsEnabled = true;
- this._scene.texturesEnabled = true;
- this._scene.lensFlaresEnabled = true;
- this._scene.proceduralTexturesEnabled = true;
- this._scene.renderTargetsEnabled = true;
- this._scene.probesEnabled = true;
- engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
- };
- DebugLayer.prototype.show = function (showUI, camera, rootElement) {
- if (showUI === void 0) { showUI = true; }
- if (camera === void 0) { camera = null; }
- if (rootElement === void 0) { rootElement = null; }
- if (this._enabled) {
- return;
- }
- this._enabled = true;
- if (camera) {
- this._camera = camera;
- }
- else {
- this._camera = this._scene.activeCamera;
- }
- this._showUI = showUI;
- var engine = this._scene.getEngine();
- this._globalDiv = document.createElement("div");
- this._rootElement = rootElement || document.body;
- this._rootElement.appendChild(this._globalDiv);
- this._generateDOMelements();
- engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
- this._syncPositions();
- this._scene.registerBeforeRender(this._syncData);
- this._scene.registerAfterRender(this._syncUI);
- };
- DebugLayer.prototype._clearLabels = function () {
- this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- mesh.renderOverlay = false;
- }
- };
- DebugLayer.prototype._generateheader = function (root, text) {
- var header = document.createElement("div");
- header.innerHTML = text + " ";
- header.style.textAlign = "right";
- header.style.width = "100%";
- header.style.color = "white";
- header.style.backgroundColor = "Black";
- header.style.padding = "5px 5px 4px 0px";
- header.style.marginLeft = "-5px";
- header.style.fontWeight = "bold";
- root.appendChild(header);
- };
- DebugLayer.prototype._generateTexBox = function (root, title, color) {
- var label = document.createElement("label");
- label.innerHTML = title;
- label.style.color = color;
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- var boundingBoxesCheckbox = document.createElement("input");
- boundingBoxesCheckbox.type = "checkbox";
- boundingBoxesCheckbox.checked = initialState;
- boundingBoxesCheckbox.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(boundingBoxesCheckbox);
- var container = document.createElement("span");
- var leftPart = document.createElement("span");
- var rightPart = document.createElement("span");
- rightPart.style.cssFloat = "right";
- leftPart.innerHTML = leftTitle;
- rightPart.innerHTML = rightTitle;
- rightPart.style.fontSize = "12px";
- rightPart.style.maxWidth = "200px";
- container.appendChild(leftPart);
- container.appendChild(rightPart);
- label.appendChild(container);
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- var checkBox = document.createElement("input");
- checkBox.type = "checkbox";
- checkBox.checked = initialState;
- checkBox.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(checkBox);
- label.appendChild(document.createTextNode(title));
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateButton = function (root, title, task, tag) {
- if (tag === void 0) { tag = null; }
- var button = document.createElement("button");
- button.innerHTML = title;
- button.style.height = "24px";
- button.style.width = "150px";
- button.style.marginBottom = "5px";
- button.style.color = "#444444";
- button.style.border = "1px solid white";
- button.className = "debugLayerButton";
- button.addEventListener("click", function (evt) {
- task(evt.target, tag);
- });
- root.appendChild(button);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- var boundingBoxesRadio = document.createElement("input");
- boundingBoxesRadio.type = "radio";
- boundingBoxesRadio.name = name;
- boundingBoxesRadio.checked = initialState;
- boundingBoxesRadio.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(boundingBoxesRadio);
- label.appendChild(document.createTextNode(title));
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateDOMelements = function () {
- var _this = this;
- this._globalDiv.id = "DebugLayer";
- this._globalDiv.style.position = "absolute";
- this._globalDiv.style.fontFamily = "Segoe UI, Arial";
- this._globalDiv.style.fontSize = "14px";
- this._globalDiv.style.color = "white";
- // Drawing canvas
- this._drawingCanvas = document.createElement("canvas");
- this._drawingCanvas.id = "DebugLayerDrawingCanvas";
- this._drawingCanvas.style.position = "absolute";
- this._drawingCanvas.style.pointerEvents = "none";
- this._drawingCanvas.style.backgroundColor = "transparent";
- this._drawingContext = this._drawingCanvas.getContext("2d");
- this._globalDiv.appendChild(this._drawingCanvas);
- if (this._showUI) {
- var background = "rgba(128, 128, 128, 0.4)";
- var border = "rgb(180, 180, 180) solid 1px";
- // Stats
- this._statsDiv = document.createElement("div");
- this._statsDiv.id = "DebugLayerStats";
- this._statsDiv.style.border = border;
- this._statsDiv.style.position = "absolute";
- this._statsDiv.style.background = background;
- this._statsDiv.style.padding = "0px 0px 0px 5px";
- this._generateheader(this._statsDiv, "STATISTICS");
- this._statsSubsetDiv = document.createElement("div");
- this._statsSubsetDiv.style.paddingTop = "5px";
- this._statsSubsetDiv.style.paddingBottom = "5px";
- this._statsSubsetDiv.style.overflowY = "auto";
- this._statsDiv.appendChild(this._statsSubsetDiv);
- // Tree
- this._treeDiv = document.createElement("div");
- this._treeDiv.id = "DebugLayerTree";
- this._treeDiv.style.border = border;
- this._treeDiv.style.position = "absolute";
- this._treeDiv.style.background = background;
- this._treeDiv.style.padding = "0px 0px 0px 5px";
- this._treeDiv.style.display = "none";
- this._generateheader(this._treeDiv, "MESHES TREE");
- this._treeSubsetDiv = document.createElement("div");
- this._treeSubsetDiv.style.paddingTop = "5px";
- this._treeSubsetDiv.style.paddingRight = "5px";
- this._treeSubsetDiv.style.overflowY = "auto";
- this._treeSubsetDiv.style.maxHeight = "300px";
- this._treeDiv.appendChild(this._treeSubsetDiv);
- this._needToRefreshMeshesTree = true;
- // Logs
- this._logDiv = document.createElement("div");
- this._logDiv.style.border = border;
- this._logDiv.id = "DebugLayerLogs";
- this._logDiv.style.position = "absolute";
- this._logDiv.style.background = background;
- this._logDiv.style.padding = "0px 0px 0px 5px";
- this._logDiv.style.display = "none";
- this._generateheader(this._logDiv, "LOGS");
- this._logSubsetDiv = document.createElement("div");
- this._logSubsetDiv.style.height = "127px";
- this._logSubsetDiv.style.paddingTop = "5px";
- this._logSubsetDiv.style.overflowY = "auto";
- this._logSubsetDiv.style.fontSize = "12px";
- this._logSubsetDiv.style.fontFamily = "consolas";
- this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
- this._logDiv.appendChild(this._logSubsetDiv);
- BABYLON.Tools.OnNewCacheEntry = function (entry) {
- _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
- };
- // Options
- this._optionsDiv = document.createElement("div");
- this._optionsDiv.id = "DebugLayerOptions";
- this._optionsDiv.style.border = border;
- this._optionsDiv.style.position = "absolute";
- this._optionsDiv.style.background = background;
- this._optionsDiv.style.padding = "0px 0px 0px 5px";
- this._optionsDiv.style.overflowY = "auto";
- this._generateheader(this._optionsDiv, "OPTIONS");
- this._optionsSubsetDiv = document.createElement("div");
- this._optionsSubsetDiv.style.paddingTop = "5px";
- this._optionsSubsetDiv.style.paddingBottom = "5px";
- this._optionsSubsetDiv.style.overflowY = "auto";
- this._optionsSubsetDiv.style.maxHeight = "200px";
- this._optionsDiv.appendChild(this._optionsSubsetDiv);
- this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
- _this._displayTree = element.checked;
- _this._needToRefreshMeshesTree = true;
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
- _this._labelsEnabled = element.checked;
- if (!_this._labelsEnabled) {
- _this._clearLabels();
- }
- });
- this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
- if (element.checked) {
- BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
- }
- else {
- BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
- }
- });
- ;
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
- this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = false;
- _this._scene.forcePointsCloud = false;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = true;
- _this._scene.forcePointsCloud = false;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = false;
- _this._scene.forcePointsCloud = true;
- }
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
- if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
- this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
- if (element.checked) {
- _this._scene.headphone = true;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
- if (element.checked) {
- _this._scene.headphone = false;
- }
- });
- this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
- _this._scene.audioEnabled = !element.checked;
- });
- }
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
- this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
- this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
- this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
- if (_this._camera) {
- console.log(_this._camera);
- }
- else {
- console.warn("No camera defined, or debug layer created before camera creation!");
- }
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._globalDiv.appendChild(this._statsDiv);
- this._globalDiv.appendChild(this._logDiv);
- this._globalDiv.appendChild(this._optionsDiv);
- this._globalDiv.appendChild(this._treeDiv);
- }
- };
- DebugLayer.prototype._displayStats = function () {
- var scene = this._scene;
- var engine = scene.getEngine();
- var glInfo = engine.getGlInfo();
- this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Count</b><br>"
- + "Total meshes: " + scene.meshes.length + "<br>"
- + "Total vertices: " + scene.getTotalVertices() + "<br>"
- + "Total materials: " + scene.materials.length + "<br>"
- + "Total textures: " + scene.textures.length + "<br>"
- + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
- + "Active indices: " + scene.getActiveIndices() + "<br>"
- + "Active bones: " + scene.getActiveBones() + "<br>"
- + "Active particles: " + scene.getActiveParticles() + "<br>"
- + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
- + "<b>Duration</b><br>"
- + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
- + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
- + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
- + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
- + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
- + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
- + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
- + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
- + "</div>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Extensions</b><br>"
- + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
- + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
- + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
- + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
- + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
- + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
- + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
- + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
- + "</div><br>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Caps.</b><br>"
- + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
- + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
- + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
- + "<b>Info</b><br>"
- + "WebGL feature level: " + engine.webGLVersion + "<br>"
- + glInfo.version + "<br>"
- + "</div><br>"
- + glInfo.renderer + "<br>";
- if (this.customStatsFunction) {
- this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
- }
- };
- return DebugLayer;
- })();
- BABYLON.DebugLayer = DebugLayer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DefaultLoadingScreen = (function () {
- function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
- var _this = this;
- if (_loadingText === void 0) { _loadingText = ""; }
- if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
- this._renderingCanvas = _renderingCanvas;
- this._loadingText = _loadingText;
- this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
- // Resize
- this._resizeLoadingUI = function () {
- var canvasRect = _this._renderingCanvas.getBoundingClientRect();
- _this._loadingDiv.style.position = "absolute";
- _this._loadingDiv.style.left = canvasRect.left + "px";
- _this._loadingDiv.style.top = canvasRect.top + "px";
- _this._loadingDiv.style.width = canvasRect.width + "px";
- _this._loadingDiv.style.height = canvasRect.height + "px";
- };
- }
- DefaultLoadingScreen.prototype.displayLoadingUI = function () {
- var _this = this;
- if (this._loadingDiv) {
- // Do not add a loading screen if there is already one
- return;
- }
- this._loadingDiv = document.createElement("div");
- this._loadingDiv.id = "babylonjsLoadingDiv";
- this._loadingDiv.style.opacity = "0";
- this._loadingDiv.style.transition = "opacity 1.5s ease";
- // Loading text
- this._loadingTextDiv = document.createElement("div");
- this._loadingTextDiv.style.position = "absolute";
- this._loadingTextDiv.style.left = "0";
- this._loadingTextDiv.style.top = "50%";
- this._loadingTextDiv.style.marginTop = "80px";
- this._loadingTextDiv.style.width = "100%";
- this._loadingTextDiv.style.height = "20px";
- this._loadingTextDiv.style.fontFamily = "Arial";
- this._loadingTextDiv.style.fontSize = "14px";
- this._loadingTextDiv.style.color = "white";
- this._loadingTextDiv.style.textAlign = "center";
- this._loadingTextDiv.innerHTML = "Loading";
- this._loadingDiv.appendChild(this._loadingTextDiv);
- //set the predefined text
- this._loadingTextDiv.innerHTML = this._loadingText;
- // Loading img
- var imgBack = new Image();
- imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
- imgBack.style.position = "absolute";
- imgBack.style.left = "50%";
- imgBack.style.top = "50%";
- imgBack.style.marginLeft = "-50px";
- imgBack.style.marginTop = "-50px";
- imgBack.style.transition = "transform 1.0s ease";
- imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
- var deg = 360;
- var onTransitionEnd = function () {
- deg += 360;
- imgBack.style.transform = "rotateZ(" + deg + "deg)";
- imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
- };
- imgBack.addEventListener("transitionend", onTransitionEnd);
- imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
- this._loadingDiv.appendChild(imgBack);
- // front image
- var imgFront = new Image();
- imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
- imgFront.style.position = "absolute";
- imgFront.style.left = "50%";
- imgFront.style.top = "50%";
- imgFront.style.marginLeft = "-50px";
- imgFront.style.marginTop = "-50px";
- this._loadingDiv.appendChild(imgFront);
- this._resizeLoadingUI();
- window.addEventListener("resize", this._resizeLoadingUI);
- this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
- document.body.appendChild(this._loadingDiv);
- setTimeout(function () {
- _this._loadingDiv.style.opacity = "1";
- imgBack.style.transform = "rotateZ(360deg)";
- imgBack.style.webkitTransform = "rotateZ(360deg)";
- }, 0);
- };
- DefaultLoadingScreen.prototype.hideLoadingUI = function () {
- var _this = this;
- if (!this._loadingDiv) {
- return;
- }
- var onTransitionEnd = function () {
- if (!_this._loadingDiv) {
- return;
- }
- document.body.removeChild(_this._loadingDiv);
- window.removeEventListener("resize", _this._resizeLoadingUI);
- _this._loadingDiv = null;
- };
- this._loadingDiv.style.opacity = "0";
- this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
- };
- Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
- set: function (text) {
- this._loadingText = text;
- if (this._loadingTextDiv) {
- this._loadingTextDiv.innerHTML = this._loadingText;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
- get: function () {
- return this._loadingDivBackgroundColor;
- },
- set: function (color) {
- this._loadingDivBackgroundColor = color;
- if (!this._loadingDiv) {
- return;
- }
- this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
- },
- enumerable: true,
- configurable: true
- });
- return DefaultLoadingScreen;
- })();
- BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SIMDVector3 = (function () {
- function SIMDVector3() {
- }
- SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
- var v = SIMD.float32x4.loadXYZ(vector._data, 0);
- var m0 = SIMD.float32x4.load(transformation.m, 0);
- var m1 = SIMD.float32x4.load(transformation.m, 4);
- var m2 = SIMD.float32x4.load(transformation.m, 8);
- var m3 = SIMD.float32x4.load(transformation.m, 12);
- var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
- r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
- SIMD.float32x4.storeXYZ(result._data, 0, r);
- };
- SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
- var v0 = SIMD.float32x4.splat(x);
- var v1 = SIMD.float32x4.splat(y);
- var v2 = SIMD.float32x4.splat(z);
- var m0 = SIMD.float32x4.load(transformation.m, 0);
- var m1 = SIMD.float32x4.load(transformation.m, 4);
- var m2 = SIMD.float32x4.load(transformation.m, 8);
- var m3 = SIMD.float32x4.load(transformation.m, 12);
- var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
- r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
- SIMD.float32x4.storeXYZ(result._data, 0, r);
- };
- return SIMDVector3;
- })();
- BABYLON.SIMDVector3 = SIMDVector3;
- var SIMDMatrix = (function () {
- function SIMDMatrix() {
- }
- SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
- if (offset === void 0) { offset = 0; }
- var tm = this.m;
- var om = other.m;
- var om0 = SIMD.float32x4.load(om, 0);
- var om1 = SIMD.float32x4.load(om, 4);
- var om2 = SIMD.float32x4.load(om, 8);
- var om3 = SIMD.float32x4.load(om, 12);
- var tm0 = SIMD.float32x4.load(tm, 0);
- SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
- var tm1 = SIMD.float32x4.load(tm, 4);
- SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
- var tm2 = SIMD.float32x4.load(tm, 8);
- SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
- var tm3 = SIMD.float32x4.load(tm, 12);
- SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
- };
- SIMDMatrix.prototype.invertToRefSIMD = function (other) {
- var src = this.m;
- var dest = other.m;
- var row0, row1, row2, row3;
- var tmp1;
- var minor0, minor1, minor2, minor3;
- var det;
- // Load the 4 rows
- var src0 = SIMD.float32x4.load(src, 0);
- var src1 = SIMD.float32x4.load(src, 4);
- var src2 = SIMD.float32x4.load(src, 8);
- var src3 = SIMD.float32x4.load(src, 12);
- // Transpose the source matrix. Sort of. Not a true transpose operation
- tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
- row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
- row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
- row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
- tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
- row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
- row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
- row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
- // This is a true transposition, but it will lead to an incorrect result
- //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
- //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
- //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
- //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
- //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
- //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
- //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
- //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
- // ----
- tmp1 = SIMD.float32x4.mul(row2, row3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor0 = SIMD.float32x4.mul(row1, tmp1);
- minor1 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
- minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
- minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(row1, row2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
- minor3 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
- minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
- minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
- minor2 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
- minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
- minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
- minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
- minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
- minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
- minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
- minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
- minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
- // Compute determinant
- det = SIMD.float32x4.mul(row0, minor0);
- det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
- det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
- tmp1 = SIMD.float32x4.reciprocalApproximation(det);
- det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
- det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
- // These shuffles aren't necessary if the faulty transposition is done
- // up at the top of this function.
- //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
- //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
- //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
- //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
- // Compute final values by multiplying with 1/det
- minor0 = SIMD.float32x4.mul(det, minor0);
- minor1 = SIMD.float32x4.mul(det, minor1);
- minor2 = SIMD.float32x4.mul(det, minor2);
- minor3 = SIMD.float32x4.mul(det, minor3);
- SIMD.float32x4.store(dest, 0, minor0);
- SIMD.float32x4.store(dest, 4, minor1);
- SIMD.float32x4.store(dest, 8, minor2);
- SIMD.float32x4.store(dest, 12, minor3);
- return this;
- };
- SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
- var out = result.m;
- var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
- var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
- var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
- // cc.kmVec3Subtract(f, pCenter, pEye);
- var f = SIMD.float32x4.sub(center, eye);
- // cc.kmVec3Normalize(f, f);
- var tmp = SIMD.float32x4.mul(f, f);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Assign(up, pUp);
- // cc.kmVec3Normalize(up, up);
- tmp = SIMD.float32x4.mul(up, up);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Cross(s, f, up);
- var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
- // cc.kmVec3Normalize(s, s);
- tmp = SIMD.float32x4.mul(s, s);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Cross(u, s, f);
- var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
- // cc.kmVec3Normalize(s, s);
- tmp = SIMD.float32x4.mul(s, s);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- var zero = SIMD.float32x4.splat(0.0);
- s = SIMD.float32x4.neg(s);
- var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
- var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
- var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
- var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
- tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
- tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
- var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
- var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
- var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
- var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
- var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
- var b3 = SIMD.float32x4.neg(eye);
- b3 = SIMD.float32x4.withW(b3, 1.0);
- SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
- };
- return SIMDMatrix;
- })();
- BABYLON.SIMDMatrix = SIMDMatrix;
- var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
- var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
- var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
- var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
- var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
- var SIMDHelper = (function () {
- function SIMDHelper() {
- }
- Object.defineProperty(SIMDHelper, "IsEnabled", {
- get: function () {
- return SIMDHelper._isEnabled;
- },
- enumerable: true,
- configurable: true
- });
- SIMDHelper.DisableSIMD = function () {
- // Replace functions
- BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
- BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
- BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
- BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
- SIMDHelper._isEnabled = false;
- };
- SIMDHelper.EnableSIMD = function () {
- if (window.SIMD === undefined) {
- return;
- }
- // Replace functions
- BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
- BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
- BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
- BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
- Object.defineProperty(BABYLON.Vector3.prototype, "x", {
- get: function () { return this._data[0]; },
- set: function (value) {
- if (!this._data) {
- this._data = new Float32Array(3);
- }
- this._data[0] = value;
- }
- });
- Object.defineProperty(BABYLON.Vector3.prototype, "y", {
- get: function () { return this._data[1]; },
- set: function (value) {
- this._data[1] = value;
- }
- });
- Object.defineProperty(BABYLON.Vector3.prototype, "z", {
- get: function () { return this._data[2]; },
- set: function (value) {
- this._data[2] = value;
- }
- });
- SIMDHelper._isEnabled = true;
- };
- SIMDHelper._isEnabled = false;
- return SIMDHelper;
- })();
- BABYLON.SIMDHelper = SIMDHelper;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ShaderMaterial = (function (_super) {
- __extends(ShaderMaterial, _super);
- function ShaderMaterial(name, scene, shaderPath, options) {
- _super.call(this, name, scene);
- this._textures = {};
- this._floats = {};
- this._floatsArrays = {};
- this._colors3 = {};
- this._colors4 = {};
- this._vectors2 = {};
- this._vectors3 = {};
- this._vectors4 = {};
- this._matrices = {};
- this._matrices3x3 = {};
- this._matrices2x2 = {};
- this._cachedWorldViewMatrix = new BABYLON.Matrix();
- this._shaderPath = shaderPath;
- options.needAlphaBlending = options.needAlphaBlending || false;
- options.needAlphaTesting = options.needAlphaTesting || false;
- options.attributes = options.attributes || ["position", "normal", "uv"];
- options.uniforms = options.uniforms || ["worldViewProjection"];
- options.samplers = options.samplers || [];
- options.defines = options.defines || [];
- this._options = options;
- }
- ShaderMaterial.prototype.needAlphaBlending = function () {
- return this._options.needAlphaBlending;
- };
- ShaderMaterial.prototype.needAlphaTesting = function () {
- return this._options.needAlphaTesting;
- };
- ShaderMaterial.prototype._checkUniform = function (uniformName) {
- if (this._options.uniforms.indexOf(uniformName) === -1) {
- this._options.uniforms.push(uniformName);
- }
- };
- ShaderMaterial.prototype.setTexture = function (name, texture) {
- if (this._options.samplers.indexOf(name) === -1) {
- this._options.samplers.push(name);
- }
- this._textures[name] = texture;
- return this;
- };
- ShaderMaterial.prototype.setFloat = function (name, value) {
- this._checkUniform(name);
- this._floats[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setFloats = function (name, value) {
- this._checkUniform(name);
- this._floatsArrays[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setColor3 = function (name, value) {
- this._checkUniform(name);
- this._colors3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setColor4 = function (name, value) {
- this._checkUniform(name);
- this._colors4[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector2 = function (name, value) {
- this._checkUniform(name);
- this._vectors2[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector3 = function (name, value) {
- this._checkUniform(name);
- this._vectors3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector4 = function (name, value) {
- this._checkUniform(name);
- this._vectors4[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix = function (name, value) {
- this._checkUniform(name);
- this._matrices[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
- this._checkUniform(name);
- this._matrices3x3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
- this._checkUniform(name);
- this._matrices2x2[name] = value;
- return this;
- };
- ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (!this.checkReadyOnEveryCall) {
- if (this._renderId === scene.getRenderId()) {
- return true;
- }
- }
- // Instances
- var defines = [];
- var fallbacks = new BABYLON.EffectFallbacks();
- if (useInstances) {
- defines.push("#define INSTANCES");
- }
- for (var index = 0; index < this._options.defines.length; index++) {
- defines.push(this._options.defines[index]);
- }
- // Bones
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- fallbacks.addCPUSkinningFallback(0, mesh);
- }
- // Alpha test
- if (engine.getAlphaTesting()) {
- defines.push("#define ALPHATEST");
- }
- var previousEffect = this._effect;
- var join = defines.join("\n");
- this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
- if (!this._effect.isReady()) {
- return false;
- }
- if (previousEffect !== this._effect) {
- scene.resetCachedMaterial();
- }
- this._renderId = scene.getRenderId();
- return true;
- };
- ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- var scene = this.getScene();
- if (this._options.uniforms.indexOf("world") !== -1) {
- this._effect.setMatrix("world", world);
- }
- if (this._options.uniforms.indexOf("worldView") !== -1) {
- world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
- this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
- }
- if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
- this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
- }
- };
- ShaderMaterial.prototype.bind = function (world, mesh) {
- // Std values
- this.bindOnlyWorldMatrix(world);
- if (this.getScene().getCachedMaterial() !== this) {
- if (this._options.uniforms.indexOf("view") !== -1) {
- this._effect.setMatrix("view", this.getScene().getViewMatrix());
- }
- if (this._options.uniforms.indexOf("projection") !== -1) {
- this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
- }
- if (this._options.uniforms.indexOf("viewProjection") !== -1) {
- this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
- }
- // Bones
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- // Texture
- for (var name in this._textures) {
- this._effect.setTexture(name, this._textures[name]);
- }
- // Float
- for (name in this._floats) {
- this._effect.setFloat(name, this._floats[name]);
- }
- // Float s
- for (name in this._floatsArrays) {
- this._effect.setArray(name, this._floatsArrays[name]);
- }
- // Color3
- for (name in this._colors3) {
- this._effect.setColor3(name, this._colors3[name]);
- }
- // Color4
- for (name in this._colors4) {
- var color = this._colors4[name];
- this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
- }
- // Vector2
- for (name in this._vectors2) {
- this._effect.setVector2(name, this._vectors2[name]);
- }
- // Vector3
- for (name in this._vectors3) {
- this._effect.setVector3(name, this._vectors3[name]);
- }
- // Vector4
- for (name in this._vectors4) {
- this._effect.setVector4(name, this._vectors4[name]);
- }
- // Matrix
- for (name in this._matrices) {
- this._effect.setMatrix(name, this._matrices[name]);
- }
- // Matrix 3x3
- for (name in this._matrices3x3) {
- this._effect.setMatrix3x3(name, this._matrices3x3[name]);
- }
- // Matrix 2x2
- for (name in this._matrices2x2) {
- this._effect.setMatrix2x2(name, this._matrices2x2[name]);
- }
- }
- _super.prototype.bind.call(this, world, mesh);
- };
- ShaderMaterial.prototype.clone = function (name) {
- var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
- return newShaderMaterial;
- };
- ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
- for (var name in this._textures) {
- this._textures[name].dispose();
- }
- this._textures = {};
- _super.prototype.dispose.call(this, forceDisposeEffect);
- };
- ShaderMaterial.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.options = this._options;
- serializationObject.shaderPath = this._shaderPath;
- serializationObject.customType = "BABYLON.ShaderMaterial";
- // Texture
- serializationObject.textures = {};
- for (var name in this._textures) {
- serializationObject.textures[name] = this._textures[name].serialize();
- }
- // Float
- serializationObject.floats = {};
- for (name in this._floats) {
- serializationObject.floats[name] = this._floats[name];
- }
- // Float s
- serializationObject.floatArrays = {};
- for (name in this._floatsArrays) {
- serializationObject.floatArrays[name] = this._floatsArrays[name];
- }
- // Color3
- serializationObject.colors3 = {};
- for (name in this._colors3) {
- serializationObject.colors3[name] = this._colors3[name].asArray();
- }
- // Color4
- serializationObject.colors4 = {};
- for (name in this._colors4) {
- serializationObject.colors4[name] = this._colors4[name].asArray();
- }
- // Vector2
- serializationObject.vectors2 = {};
- for (name in this._vectors2) {
- serializationObject.vectors2[name] = this._vectors2[name].asArray();
- }
- // Vector3
- serializationObject.vectors3 = {};
- for (name in this._vectors3) {
- serializationObject.vectors3[name] = this._vectors3[name].asArray();
- }
- // Vector4
- serializationObject.vectors4 = {};
- for (name in this._vectors4) {
- serializationObject.vectors4[name] = this._vectors4[name].asArray();
- }
- // Matrix
- serializationObject.matrices = {};
- for (name in this._matrices) {
- serializationObject.matrices[name] = this._matrices[name].asArray();
- }
- // Matrix 3x3
- serializationObject.matrices3x3 = {};
- for (name in this._matrices3x3) {
- serializationObject.matrices3x3[name] = this._matrices3x3[name];
- }
- // Matrix 2x2
- serializationObject.matrices2x2 = {};
- for (name in this._matrices2x2) {
- serializationObject.matrices2x2[name] = this._matrices2x2[name];
- }
- return serializationObject;
- };
- ShaderMaterial.Parse = function (source, scene, rootUrl) {
- var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
- // Texture
- for (var name in source.textures) {
- material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
- }
- // Float
- for (name in source.floats) {
- material.setFloat(name, source.floats[name]);
- }
- // Float s
- for (name in source.floatsArrays) {
- material.setFloats(name, source.floatsArrays[name]);
- }
- // Color3
- for (name in source.colors3) {
- material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
- }
- // Color4
- for (name in source.colors4) {
- material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
- }
- // Vector2
- for (name in source.vectors2) {
- material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
- }
- // Vector3
- for (name in source.vectors3) {
- material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
- }
- // Vector4
- for (name in source.vectors4) {
- material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
- }
- // Matrix
- for (name in source.matrices) {
- material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
- }
- // Matrix 3x3
- for (name in source.matrices3x3) {
- material.setMatrix3x3(name, source.matrices3x3[name]);
- }
- // Matrix 2x2
- for (name in source.matrices2x2) {
- material.setMatrix2x2(name, source.matrices2x2[name]);
- }
- return material;
- };
- return ShaderMaterial;
- })(BABYLON.Material);
- BABYLON.ShaderMaterial = ShaderMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
- // All values and structures referenced from:
- // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
- var DDS_MAGIC = 0x20534444;
- var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
- var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
- var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
- var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
- function FourCCToInt32(value) {
- return value.charCodeAt(0) +
- (value.charCodeAt(1) << 8) +
- (value.charCodeAt(2) << 16) +
- (value.charCodeAt(3) << 24);
- }
- function Int32ToFourCC(value) {
- return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
- }
- var FOURCC_DXT1 = FourCCToInt32("DXT1");
- var FOURCC_DXT3 = FourCCToInt32("DXT3");
- var FOURCC_DXT5 = FourCCToInt32("DXT5");
- var headerLengthInt = 31; // The header length in 32 bit ints
- // Offsets into the header array
- var off_magic = 0;
- var off_size = 1;
- var off_flags = 2;
- var off_height = 3;
- var off_width = 4;
- var off_mipmapCount = 7;
- var off_pfFlags = 20;
- var off_pfFourCC = 21;
- var off_RGBbpp = 22;
- var off_RMask = 23;
- var off_GMask = 24;
- var off_BMask = 25;
- var off_AMask = 26;
- var off_caps1 = 27;
- var off_caps2 = 28;
- ;
- var DDSTools = (function () {
- function DDSTools() {
- }
- DDSTools.GetDDSInfo = function (arrayBuffer) {
- var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
- var mipmapCount = 1;
- if (header[off_flags] & DDSD_MIPMAPCOUNT) {
- mipmapCount = Math.max(1, header[off_mipmapCount]);
- }
- return {
- width: header[off_width],
- height: header[off_height],
- mipmapCount: mipmapCount,
- isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
- isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
- isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
- isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
- };
- };
- DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width) * 4;
- byteArray[index + 2] = srcData[srcPos];
- byteArray[index + 1] = srcData[srcPos + 1];
- byteArray[index] = srcData[srcPos + 2];
- byteArray[index + 3] = srcData[srcPos + 3];
- index += 4;
- }
- }
- return byteArray;
- };
- DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width) * 3;
- byteArray[index + 2] = srcData[srcPos];
- byteArray[index + 1] = srcData[srcPos + 1];
- byteArray[index] = srcData[srcPos + 2];
- index += 3;
- }
- }
- return byteArray;
- };
- DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width);
- byteArray[index] = srcData[srcPos];
- index++;
- }
- }
- return byteArray;
- };
- DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
- var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
- if (header[off_magic] != DDS_MAGIC) {
- BABYLON.Tools.Error("Invalid magic number in DDS header");
- return;
- }
- if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
- BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
- return;
- }
- if (info.isFourCC) {
- fourCC = header[off_pfFourCC];
- switch (fourCC) {
- case FOURCC_DXT1:
- blockBytes = 8;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
- break;
- case FOURCC_DXT3:
- blockBytes = 16;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
- break;
- case FOURCC_DXT5:
- blockBytes = 16;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
- break;
- default:
- console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
- return;
- }
- }
- mipmapCount = 1;
- if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
- mipmapCount = Math.max(1, header[off_mipmapCount]);
- }
- var bpp = header[off_RGBbpp];
- for (var face = 0; face < faces; face++) {
- var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
- width = header[off_width];
- height = header[off_height];
- dataOffset = header[off_size] + 4;
- for (i = 0; i < mipmapCount; ++i) {
- if (info.isRGB) {
- if (bpp === 24) {
- dataLength = width * height * 3;
- byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
- }
- else {
- dataLength = width * height * 4;
- byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
- }
- }
- else if (info.isLuminance) {
- var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
- var unpaddedRowSize = width;
- var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
- dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
- byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
- }
- else {
- dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
- byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
- gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
- }
- dataOffset += dataLength;
- width *= 0.5;
- height *= 0.5;
- width = Math.max(1.0, width);
- height = Math.max(1.0, height);
- }
- }
- };
- return DDSTools;
- })();
- Internals.DDSTools = DDSTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CannonJSPlugin = (function () {
- function CannonJSPlugin(_useDeltaForWorldStep) {
- if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
- this._useDeltaForWorldStep = _useDeltaForWorldStep;
- this._registeredMeshes = [];
- this._physicsMaterials = [];
- this._fixedTimeStep = 1 / 60;
- //private _maxSubSteps : number = 15;
- this.name = "CannonJS";
- this.updateBodyPosition = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
- var body = registeredMesh.body;
- var center = mesh.getBoundingInfo().boundingBox.center.clone();
- body.quaternion.copy(mesh.rotationQuaternion);
- if (registeredMesh.deltaRotation) {
- var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
- body.quaternion = body.quaternion.mult(tmpQ);
- }
- if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
- //calculate the correct body position:
- var rotationQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = new BABYLON.Quaternion();
- mesh.computeWorldMatrix(true);
- //get original center with no rotation
- var center = mesh.getBoundingInfo().boundingBox.center.clone();
- var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
- //rotation is back
- mesh.rotationQuaternion = rotationQuaternion;
- //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
- var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
- mesh.setPivotMatrix(p);
- mesh.computeWorldMatrix(true);
- //calculate the translation
- var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
- center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
- //add it inverted to the delta
- registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
- registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
- mesh.setPivotMatrix(oldPivot);
- mesh.computeWorldMatrix(true);
- }
- else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
- center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
- }
- body.position.set(center.x, center.y, center.z);
- return;
- }
- }
- };
- }
- CannonJSPlugin.prototype.initialize = function (iterations) {
- if (iterations === void 0) { iterations = 10; }
- this._world = new CANNON.World();
- this._world.broadphase = new CANNON.NaiveBroadphase();
- this._world.solver.iterations = iterations;
- };
- CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
- return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
- };
- CannonJSPlugin.prototype.runOneStep = function (delta) {
- var _this = this;
- this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
- this._registeredMeshes.forEach(function (registeredMesh) {
- // Body position
- var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
- registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
- registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
- registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
- registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
- if (registeredMesh.deltaRotation) {
- registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
- }
- //is the physics collision callback is set?
- if (registeredMesh.mesh.onPhysicsCollide) {
- if (!registeredMesh.collisionFunction) {
- registeredMesh.collisionFunction = function (e) {
- //find the mesh that collided with the registered mesh
- for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
- if (_this._registeredMeshes[idx].body == e.body) {
- registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
- }
- }
- };
- registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
- }
- }
- else {
- //unregister, in case the function was removed for some reason
- if (registeredMesh.collisionFunction) {
- registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
- }
- }
- });
- };
- CannonJSPlugin.prototype.setGravity = function (gravity) {
- this._gravity = gravity;
- this._world.gravity.set(gravity.x, gravity.y, gravity.z);
- };
- CannonJSPlugin.prototype.getGravity = function () {
- return this._gravity;
- };
- CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
- this.unregisterMesh(mesh);
- if (!mesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
- }
- mesh.computeWorldMatrix(true);
- var shape = this._createShape(mesh, impostor);
- return this._createRigidBodyFromShape(shape, mesh, options);
- };
- CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
- //get the correct bounding box
- var oldQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
- mesh.computeWorldMatrix(true);
- var returnValue;
- switch (impostor) {
- case BABYLON.PhysicsEngine.SphereImpostor:
- var bbox = mesh.getBoundingInfo().boundingBox;
- var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
- var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
- var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
- returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
- break;
- //TMP also for cylinder - TODO Cannon supports cylinder natively.
- case BABYLON.PhysicsEngine.CylinderImpostor:
- BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
- case BABYLON.PhysicsEngine.BoxImpostor:
- bbox = mesh.getBoundingInfo().boundingBox;
- var min = bbox.minimumWorld;
- var max = bbox.maximumWorld;
- var box = max.subtract(min).scale(0.5);
- returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
- break;
- case BABYLON.PhysicsEngine.PlaneImpostor:
- BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
- returnValue = new CANNON.Plane();
- break;
- case BABYLON.PhysicsEngine.MeshImpostor:
- var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var rawFaces = mesh.getIndices();
- BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
- returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
- break;
- case BABYLON.PhysicsEngine.HeightmapImpostor:
- returnValue = this._createHeightmap(mesh);
- break;
- }
- mesh.rotationQuaternion = oldQuaternion;
- return returnValue;
- };
- CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
- var verts = [], faces = [];
- mesh.computeWorldMatrix(true);
- //reuse this variable
- var transformed = BABYLON.Vector3.Zero();
- // Get vertices
- for (var i = 0; i < rawVerts.length; i += 3) {
- BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
- verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
- }
- // Get faces
- for (var j = 0; j < rawFaces.length; j += 3) {
- faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
- }
- var shape = new CANNON.ConvexPolyhedron(verts, faces);
- return shape;
- };
- CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
- var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var matrix = [];
- //For now pointDepth will not be used and will be automatically calculated.
- //Future reference - try and find the best place to add a reference to the pointDepth variable.
- var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
- var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
- var elementSize = dim * 2 / arraySize;
- var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
- for (var i = 0; i < pos.length; i = i + 3) {
- var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
- var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
- var y = pos[i + 1] + minY;
- if (!matrix[x]) {
- matrix[x] = [];
- }
- if (!matrix[x][z]) {
- matrix[x][z] = y;
- }
- matrix[x][z] = Math.max(y, matrix[x][z]);
- }
- for (var x = 0; x <= arraySize; ++x) {
- if (!matrix[x]) {
- var loc = 1;
- while (!matrix[(x + loc) % arraySize]) {
- loc++;
- }
- matrix[x] = matrix[(x + loc) % arraySize].slice();
- }
- for (var z = 0; z <= arraySize; ++z) {
- if (!matrix[x][z]) {
- var loc = 1;
- var newValue;
- while (newValue === undefined) {
- newValue = matrix[x][(z + loc++) % arraySize];
- }
- matrix[x][z] = newValue;
- }
- }
- }
- var shape = new CANNON.Heightfield(matrix, {
- elementSize: elementSize
- });
- //For future reference, needed for body transformation
- shape.minY = minY;
- return shape;
- };
- CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
- var index;
- var mat;
- for (index = 0; index < this._physicsMaterials.length; index++) {
- mat = this._physicsMaterials[index];
- if (mat.friction === friction && mat.restitution === restitution) {
- return mat;
- }
- }
- var currentMat = new CANNON.Material("mat");
- this._physicsMaterials.push(currentMat);
- for (index = 0; index < this._physicsMaterials.length; index++) {
- mat = this._physicsMaterials[index];
- var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
- this._world.addContactMaterial(contactMaterial);
- }
- return currentMat;
- };
- CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
- if (!mesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
- }
- // The delta between the mesh position and the mesh bounding box center
- var bbox = mesh.getBoundingInfo().boundingBox;
- var deltaPosition = mesh.position.subtract(bbox.center);
- var deltaRotation;
- var material = this._addMaterial(options.friction, options.restitution);
- var body = new CANNON.Body({
- mass: options.mass,
- material: material,
- position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
- });
- body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
- //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
- if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
- //-90 DEG in X, precalculated
- var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
- body.quaternion = body.quaternion.mult(tmpQ);
- //Invert! (Precalculated, 90 deg in X)
- deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
- }
- //If it is a heightfield, if should be centered.
- if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
- //calculate the correct body position:
- var rotationQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = new BABYLON.Quaternion();
- mesh.computeWorldMatrix(true);
- //get original center with no rotation
- var center = mesh.getBoundingInfo().boundingBox.center.clone();
- var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
- //rotation is back
- mesh.rotationQuaternion = rotationQuaternion;
- //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
- var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
- mesh.setPivotMatrix(p);
- mesh.computeWorldMatrix(true);
- //calculate the translation
- var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
- body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
- //add it inverted to the delta
- deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
- deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
- mesh.setPivotMatrix(oldPivot);
- mesh.computeWorldMatrix(true);
- }
- else if (shape.type === CANNON.Shape.types.TRIMESH) {
- deltaPosition = BABYLON.Vector3.Zero();
- }
- //add the shape
- body.addShape(shape);
- this._world.add(body);
- this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
- return body;
- };
- CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
- var initialMesh = parts[0].mesh;
- this.unregisterMesh(initialMesh);
- initialMesh.computeWorldMatrix(true);
- var initialShape = this._createShape(initialMesh, parts[0].impostor);
- var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
- for (var index = 1; index < parts.length; index++) {
- var mesh = parts[index].mesh;
- mesh.computeWorldMatrix(true);
- var shape = this._createShape(mesh, parts[index].impostor);
- var localPosition = mesh.position;
- body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
- }
- return body;
- };
- CannonJSPlugin.prototype._unbindBody = function (body) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.body === body) {
- this._world.remove(registeredMesh.body);
- registeredMesh.body = null;
- registeredMesh.delta = null;
- registeredMesh.deltaRotation = null;
- }
- }
- };
- CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh) {
- // Remove body
- if (registeredMesh.body) {
- this._unbindBody(registeredMesh.body);
- }
- this._registeredMeshes.splice(index, 1);
- return;
- }
- }
- };
- CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
- var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
- var impulse = new CANNON.Vec3(force.x, force.y, force.z);
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh) {
- registeredMesh.body.applyImpulse(impulse, worldPoint);
- return;
- }
- }
- };
- CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
- var body1 = null, body2 = null;
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh1) {
- body1 = registeredMesh.body;
- if (body2)
- break;
- }
- else if (registeredMesh.mesh === mesh2) {
- body2 = registeredMesh.body;
- if (body1)
- break;
- }
- }
- if (!body1 || !body2) {
- return false;
- }
- var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
- this._world.addConstraint(constraint);
- return true;
- };
- CannonJSPlugin.prototype.dispose = function () {
- while (this._registeredMeshes.length) {
- this.unregisterMesh(this._registeredMeshes[0].mesh);
- }
- };
- CannonJSPlugin.prototype.isSupported = function () {
- return window.CANNON !== undefined;
- };
- CannonJSPlugin.prototype.getWorldObject = function () {
- return this._world;
- };
- CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh) {
- return registeredMesh.body;
- }
- }
- return null;
- };
- return CannonJSPlugin;
- })();
- BABYLON.CannonJSPlugin = CannonJSPlugin;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OimoJSPlugin = (function () {
- function OimoJSPlugin() {
- this._registeredMeshes = [];
- this.name = "oimo";
- /**
- * Update the body position according to the mesh position
- * @param mesh
- */
- this.updateBodyPosition = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- var body = registeredMesh.body.body;
- var updated = false;
- var newPosition;
- if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
- mesh.computeWorldMatrix(true);
- newPosition = mesh.getBoundingInfo().boundingBox.center;
- updated = true;
- }
- else if (registeredMesh.mesh.parent === mesh) {
- mesh.computeWorldMatrix(true);
- registeredMesh.mesh.computeWorldMatrix(true);
- newPosition = registeredMesh.mesh.getAbsolutePosition();
- updated = true;
- }
- if (updated) {
- body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
- body.setQuaternion(mesh.rotationQuaternion);
- body.sleeping = false;
- //force Oimo to update the body's position
- body.updatePosition(1);
- }
- }
- };
- }
- OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
- return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
- };
- OimoJSPlugin.prototype.initialize = function (iterations) {
- this._world = new OIMO.World(null, null, iterations);
- this._world.clear();
- };
- OimoJSPlugin.prototype.setGravity = function (gravity) {
- this._gravity = this._world.gravity = gravity;
- };
- OimoJSPlugin.prototype.getGravity = function () {
- return this._gravity;
- };
- OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
- this.unregisterMesh(mesh);
- if (!mesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
- }
- mesh.computeWorldMatrix(true);
- var bbox = mesh.getBoundingInfo().boundingBox;
- // The delta between the mesh position and the mesh bounding box center
- var deltaPosition = mesh.position.subtract(bbox.center);
- //calculate rotation to fit Oimo's needs (Euler...)
- var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
- //get the correct bounding box
- var oldQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
- mesh.computeWorldMatrix(true);
- var bodyConfig = {
- name: mesh.uniqueId,
- pos: [bbox.center.x, bbox.center.y, bbox.center.z],
- rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
- move: options.mass != 0,
- config: [options.mass, options.friction, options.restitution],
- world: this._world
- };
- // register mesh
- switch (impostor) {
- case BABYLON.PhysicsEngine.SphereImpostor:
- var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
- var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
- var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
- var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
- bodyConfig.type = 'sphere';
- bodyConfig.size = [size];
- break;
- case BABYLON.PhysicsEngine.PlaneImpostor:
- //Oimo "fakes" a cylinder as a box, so why don't we!
- case BABYLON.PhysicsEngine.CylinderImpostor:
- case BABYLON.PhysicsEngine.BoxImpostor:
- var min = bbox.minimumWorld;
- var max = bbox.maximumWorld;
- var box = max.subtract(min);
- var sizeX = this._checkWithEpsilon(box.x);
- var sizeY = this._checkWithEpsilon(box.y);
- var sizeZ = this._checkWithEpsilon(box.z);
- bodyConfig.type = 'box';
- bodyConfig.size = [sizeX, sizeY, sizeZ];
- break;
- }
- var body = new OIMO.Body(bodyConfig);
- //We have to access the rigid body's properties to set the quaternion.
- //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
- //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
- //TEST
- //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
- //update the internal rotation matrix
- //body.body.syncShapes();
- this._registeredMeshes.push({
- mesh: mesh,
- body: body,
- delta: deltaPosition
- });
- //for the sake of consistency.
- mesh.rotationQuaternion = oldQuaternion;
- return body;
- };
- OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
- var types = [], sizes = [], positions = [], rotations = [];
- var initialMesh = parts[0].mesh;
- for (var index = 0; index < parts.length; index++) {
- var part = parts[index];
- var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
- types.push(bodyParameters.type);
- sizes.push.apply(sizes, bodyParameters.size);
- positions.push.apply(positions, bodyParameters.pos);
- rotations.push.apply(rotations, bodyParameters.rot);
- }
- var body = new OIMO.Body({
- name: initialMesh.uniqueId,
- type: types,
- size: sizes,
- pos: positions,
- rot: rotations,
- move: options.mass != 0,
- config: [options.mass, options.friction, options.restitution],
- world: this._world
- });
- //Reset the body's rotation to be of the initial mesh's.
- var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
- body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
- this._registeredMeshes.push({
- mesh: initialMesh,
- body: body
- });
- return body;
- };
- OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
- var mesh = part.mesh;
- if (!mesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
- }
- // We need the bounding box/sphere info to compute the physics body
- mesh.computeWorldMatrix(true);
- var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
- var bodyParameters = {
- name: mesh.uniqueId,
- pos: [mesh.position.x, mesh.position.y, mesh.position.z],
- //A bug in Oimo (Body class) prevents us from using rot directly.
- rot: [0, 0, 0],
- //For future reference, if the bug will ever be fixed.
- realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
- };
- var oldQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
- mesh.computeWorldMatrix(true);
- switch (part.impostor) {
- case BABYLON.PhysicsEngine.SphereImpostor:
- var bbox = mesh.getBoundingInfo().boundingBox;
- var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
- var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
- var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
- var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
- bodyParameters.type = 'sphere';
- bodyParameters.size = [size, size, size];
- break;
- case BABYLON.PhysicsEngine.PlaneImpostor:
- case BABYLON.PhysicsEngine.CylinderImpostor:
- case BABYLON.PhysicsEngine.BoxImpostor:
- bbox = mesh.getBoundingInfo().boundingBox;
- var min = bbox.minimumWorld;
- var max = bbox.maximumWorld;
- var box = max.subtract(min);
- var sizeX = this._checkWithEpsilon(box.x);
- var sizeY = this._checkWithEpsilon(box.y);
- var sizeZ = this._checkWithEpsilon(box.z);
- bodyParameters.type = 'box';
- bodyParameters.size = [sizeX, sizeY, sizeZ];
- break;
- }
- mesh.rotationQuaternion = oldQuaternion;
- return bodyParameters;
- };
- OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
- if (registeredMesh.body) {
- this._world.removeRigidBody(registeredMesh.body.body);
- this._unbindBody(registeredMesh.body);
- }
- this._registeredMeshes.splice(index, 1);
- return;
- }
- }
- };
- OimoJSPlugin.prototype._unbindBody = function (body) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.body === body) {
- registeredMesh.body = null;
- }
- }
- };
- OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
- // Get object mass to have a behaviour similar to cannon.js
- var mass = registeredMesh.body.body.massInfo.mass;
- // The force is scaled with the mass of object
- registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
- return;
- }
- }
- };
- OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
- var body1 = null, body2 = null;
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh1) {
- body1 = registeredMesh.body.body;
- }
- else if (registeredMesh.mesh === mesh2) {
- body2 = registeredMesh.body.body;
- }
- }
- if (!body1 || !body2) {
- return false;
- }
- if (!options) {
- options = {};
- }
- new OIMO.Link({
- type: options.type,
- body1: body1,
- body2: body2,
- min: options.min,
- max: options.max,
- axe1: options.axe1,
- axe2: options.axe2,
- pos1: [pivot1.x, pivot1.y, pivot1.z],
- pos2: [pivot2.x, pivot2.y, pivot2.z],
- collision: options.collision,
- spring: options.spring,
- world: this._world
- });
- return true;
- };
- OimoJSPlugin.prototype.dispose = function () {
- this._world.clear();
- while (this._registeredMeshes.length) {
- this.unregisterMesh(this._registeredMeshes[0].mesh);
- }
- };
- OimoJSPlugin.prototype.isSupported = function () {
- return OIMO !== undefined;
- };
- OimoJSPlugin.prototype.getWorldObject = function () {
- return this._world;
- };
- OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
- for (var index = 0; index < this._registeredMeshes.length; index++) {
- var registeredMesh = this._registeredMeshes[index];
- if (registeredMesh.mesh === mesh) {
- return registeredMesh.body;
- }
- }
- return null;
- };
- OimoJSPlugin.prototype._getLastShape = function (body) {
- var lastShape = body.shapes;
- while (lastShape.next) {
- lastShape = lastShape.next;
- }
- return lastShape;
- };
- OimoJSPlugin.prototype.runOneStep = function (time) {
- this._world.step();
- // Update the position of all registered meshes
- var i = this._registeredMeshes.length;
- var m;
- while (i--) {
- var body = this._registeredMeshes[i].body.body;
- var mesh = this._registeredMeshes[i].mesh;
- if (!this._registeredMeshes[i].delta) {
- this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
- }
- if (!body.sleeping) {
- //TODO check that
- if (body.shapes.next) {
- var parentShape = this._getLastShape(body);
- mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
- mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
- mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
- }
- else {
- mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
- }
- mesh.rotationQuaternion.copyFrom(body.getQuaternion());
- mesh.computeWorldMatrix();
- }
- //check if the collide callback is set.
- if (mesh.onPhysicsCollide) {
- var meshUniqueName = mesh.uniqueId;
- var contact = this._world.contacts;
- while (contact !== null) {
- //is this body colliding with any other?
- if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
- var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
- //get the mesh and execute the callback
- var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
- if (otherMesh)
- mesh.onPhysicsCollide(otherMesh, contact);
- }
- contact = contact.next;
- }
- }
- }
- };
- return OimoJSPlugin;
- })();
- BABYLON.OimoJSPlugin = OimoJSPlugin;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DisplayPassPostProcess = (function (_super) {
- __extends(DisplayPassPostProcess, _super);
- function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
- }
- return DisplayPassPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SimplificationSettings = (function () {
- function SimplificationSettings(quality, distance, optimizeMesh) {
- this.quality = quality;
- this.distance = distance;
- this.optimizeMesh = optimizeMesh;
- }
- return SimplificationSettings;
- })();
- BABYLON.SimplificationSettings = SimplificationSettings;
- var SimplificationQueue = (function () {
- function SimplificationQueue() {
- this.running = false;
- this._simplificationArray = [];
- }
- SimplificationQueue.prototype.addTask = function (task) {
- this._simplificationArray.push(task);
- };
- SimplificationQueue.prototype.executeNext = function () {
- var task = this._simplificationArray.pop();
- if (task) {
- this.running = true;
- this.runSimplification(task);
- }
- else {
- this.running = false;
- }
- };
- SimplificationQueue.prototype.runSimplification = function (task) {
- var _this = this;
- if (task.parallelProcessing) {
- //parallel simplifier
- task.settings.forEach(function (setting) {
- var simplifier = _this.getSimplifier(task);
- simplifier.simplify(setting, function (newMesh) {
- task.mesh.addLODLevel(setting.distance, newMesh);
- newMesh.isVisible = true;
- //check if it is the last
- if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
- //all done, run the success callback.
- task.successCallback();
- }
- _this.executeNext();
- });
- });
- }
- else {
- //single simplifier.
- var simplifier = this.getSimplifier(task);
- var runDecimation = function (setting, callback) {
- simplifier.simplify(setting, function (newMesh) {
- task.mesh.addLODLevel(setting.distance, newMesh);
- newMesh.isVisible = true;
- //run the next quality level
- callback();
- });
- };
- BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
- runDecimation(task.settings[loop.index], function () {
- loop.executeNext();
- });
- }, function () {
- //execution ended, run the success callback.
- if (task.successCallback) {
- task.successCallback();
- }
- _this.executeNext();
- });
- }
- };
- SimplificationQueue.prototype.getSimplifier = function (task) {
- switch (task.simplificationType) {
- case SimplificationType.QUADRATIC:
- default:
- return new QuadraticErrorSimplification(task.mesh);
- }
- };
- return SimplificationQueue;
- })();
- BABYLON.SimplificationQueue = SimplificationQueue;
- /**
- * The implemented types of simplification.
- * At the moment only Quadratic Error Decimation is implemented.
- */
- (function (SimplificationType) {
- SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
- })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
- var SimplificationType = BABYLON.SimplificationType;
- var DecimationTriangle = (function () {
- function DecimationTriangle(vertices) {
- this.vertices = vertices;
- this.error = new Array(4);
- this.deleted = false;
- this.isDirty = false;
- this.deletePending = false;
- this.borderFactor = 0;
- }
- return DecimationTriangle;
- })();
- BABYLON.DecimationTriangle = DecimationTriangle;
- var DecimationVertex = (function () {
- function DecimationVertex(position, id) {
- this.position = position;
- this.id = id;
- this.isBorder = true;
- this.q = new QuadraticMatrix();
- this.triangleCount = 0;
- this.triangleStart = 0;
- this.originalOffsets = [];
- }
- DecimationVertex.prototype.updatePosition = function (newPosition) {
- this.position.copyFrom(newPosition);
- };
- return DecimationVertex;
- })();
- BABYLON.DecimationVertex = DecimationVertex;
- var QuadraticMatrix = (function () {
- function QuadraticMatrix(data) {
- this.data = new Array(10);
- for (var i = 0; i < 10; ++i) {
- if (data && data[i]) {
- this.data[i] = data[i];
- }
- else {
- this.data[i] = 0;
- }
- }
- }
- QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
- var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
- this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
- this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
- return det;
- };
- QuadraticMatrix.prototype.addInPlace = function (matrix) {
- for (var i = 0; i < 10; ++i) {
- this.data[i] += matrix.data[i];
- }
- };
- QuadraticMatrix.prototype.addArrayInPlace = function (data) {
- for (var i = 0; i < 10; ++i) {
- this.data[i] += data[i];
- }
- };
- QuadraticMatrix.prototype.add = function (matrix) {
- var m = new QuadraticMatrix();
- for (var i = 0; i < 10; ++i) {
- m.data[i] = this.data[i] + matrix.data[i];
- }
- return m;
- };
- QuadraticMatrix.FromData = function (a, b, c, d) {
- return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
- };
- //returning an array to avoid garbage collection
- QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
- return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
- };
- return QuadraticMatrix;
- })();
- BABYLON.QuadraticMatrix = QuadraticMatrix;
- var Reference = (function () {
- function Reference(vertexId, triangleId) {
- this.vertexId = vertexId;
- this.triangleId = triangleId;
- }
- return Reference;
- })();
- BABYLON.Reference = Reference;
- /**
- * An implementation of the Quadratic Error simplification algorithm.
- * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
- * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
- * @author RaananW
- */
- var QuadraticErrorSimplification = (function () {
- function QuadraticErrorSimplification(_mesh) {
- this._mesh = _mesh;
- this.initialized = false;
- this.syncIterations = 5000;
- this.aggressiveness = 7;
- this.decimationIterations = 100;
- this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
- }
- QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
- var _this = this;
- this.initDecimatedMesh();
- //iterating through the submeshes array, one after the other.
- BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
- _this.initWithMesh(loop.index, function () {
- _this.runDecimation(settings, loop.index, function () {
- loop.executeNext();
- });
- }, settings.optimizeMesh);
- }, function () {
- setTimeout(function () {
- successCallback(_this._reconstructedMesh);
- }, 0);
- });
- };
- QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
- var _this = this;
- var gCount = 0;
- triangle.vertices.forEach(function (vertex) {
- var count = 0;
- var vPos = vertex.position;
- var bbox = _this._mesh.getBoundingInfo().boundingBox;
- if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
- ++count;
- if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
- ++count;
- if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
- ++count;
- if (count > 1) {
- ++gCount;
- }
- ;
- });
- if (gCount > 1) {
- console.log(triangle, gCount);
- }
- return gCount > 1;
- };
- QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
- var _this = this;
- var targetCount = ~~(this.triangles.length * settings.quality);
- var deletedTriangles = 0;
- var triangleCount = this.triangles.length;
- var iterationFunction = function (iteration, callback) {
- setTimeout(function () {
- if (iteration % 5 === 0) {
- _this.updateMesh(iteration === 0);
- }
- for (var i = 0; i < _this.triangles.length; ++i) {
- _this.triangles[i].isDirty = false;
- }
- var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
- var trianglesIterator = function (i) {
- var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
- var t = _this.triangles[tIdx];
- if (!t)
- return;
- if (t.error[3] > threshold || t.deleted || t.isDirty) {
- return;
- }
- for (var j = 0; j < 3; ++j) {
- if (t.error[j] < threshold) {
- var deleted0 = [];
- var deleted1 = [];
- var v0 = t.vertices[j];
- var v1 = t.vertices[(j + 1) % 3];
- if (v0.isBorder !== v1.isBorder)
- continue;
- var p = BABYLON.Vector3.Zero();
- var n = BABYLON.Vector3.Zero();
- var uv = BABYLON.Vector2.Zero();
- var color = new BABYLON.Color4(0, 0, 0, 1);
- _this.calculateError(v0, v1, p, n, uv, color);
- var delTr = [];
- if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
- continue;
- if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
- continue;
- if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
- continue;
- var uniqueArray = [];
- delTr.forEach(function (deletedT) {
- if (uniqueArray.indexOf(deletedT) === -1) {
- deletedT.deletePending = true;
- uniqueArray.push(deletedT);
- }
- });
- if (uniqueArray.length % 2 !== 0) {
- continue;
- }
- v0.q = v1.q.add(v0.q);
- v0.updatePosition(p);
- var tStart = _this.references.length;
- deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
- deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
- var tCount = _this.references.length - tStart;
- if (tCount <= v0.triangleCount) {
- if (tCount) {
- for (var c = 0; c < tCount; c++) {
- _this.references[v0.triangleStart + c] = _this.references[tStart + c];
- }
- }
- }
- else {
- v0.triangleStart = tStart;
- }
- v0.triangleCount = tCount;
- break;
- }
- }
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
- }, 0);
- };
- BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
- if (triangleCount - deletedTriangles <= targetCount)
- loop.breakLoop();
- else {
- iterationFunction(loop.index, function () {
- loop.executeNext();
- });
- }
- }, function () {
- setTimeout(function () {
- //reconstruct this part of the mesh
- _this.reconstructMesh(submeshIndex);
- successCallback();
- }, 0);
- });
- };
- QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
- var _this = this;
- this.vertices = [];
- this.triangles = [];
- var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this._mesh.getIndices();
- var submesh = this._mesh.subMeshes[submeshIndex];
- var findInVertices = function (positionToSearch) {
- if (optimizeMesh) {
- for (var ii = 0; ii < _this.vertices.length; ++ii) {
- if (_this.vertices[ii].position.equals(positionToSearch)) {
- return _this.vertices[ii];
- }
- }
- }
- return null;
- };
- var vertexReferences = [];
- var vertexInit = function (i) {
- var offset = i + submesh.verticesStart;
- var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
- var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
- vertex.originalOffsets.push(offset);
- if (vertex.id === _this.vertices.length) {
- _this.vertices.push(vertex);
- }
- vertexReferences.push(vertex.id);
- };
- //var totalVertices = mesh.getTotalVertices();
- var totalVertices = submesh.verticesCount;
- BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
- var indicesInit = function (i) {
- var offset = (submesh.indexStart / 3) + i;
- var pos = (offset * 3);
- var i0 = indices[pos + 0];
- var i1 = indices[pos + 1];
- var i2 = indices[pos + 2];
- var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
- var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
- var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
- var triangle = new DecimationTriangle([v0, v1, v2]);
- triangle.originalOffset = pos;
- _this.triangles.push(triangle);
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
- _this.init(callback);
- });
- });
- };
- QuadraticErrorSimplification.prototype.init = function (callback) {
- var _this = this;
- var triangleInit1 = function (i) {
- var t = _this.triangles[i];
- t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
- for (var j = 0; j < 3; j++) {
- 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))));
- }
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
- var triangleInit2 = function (i) {
- var t = _this.triangles[i];
- for (var j = 0; j < 3; ++j) {
- t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
- }
- t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
- _this.initialized = true;
- callback();
- });
- });
- };
- QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
- var newTriangles = [];
- var i;
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleCount = 0;
- }
- var t;
- var j;
- for (i = 0; i < this.triangles.length; ++i) {
- if (!this.triangles[i].deleted) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- t.vertices[j].triangleCount = 1;
- }
- newTriangles.push(t);
- }
- }
- var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
- var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
- var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
- var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
- var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var vertexCount = 0;
- for (i = 0; i < this.vertices.length; ++i) {
- var vertex = this.vertices[i];
- vertex.id = vertexCount;
- if (vertex.triangleCount) {
- vertex.originalOffsets.forEach(function (originalOffset) {
- newPositionData.push(vertex.position.x);
- newPositionData.push(vertex.position.y);
- newPositionData.push(vertex.position.z);
- newNormalData.push(normalData[originalOffset * 3]);
- newNormalData.push(normalData[(originalOffset * 3) + 1]);
- newNormalData.push(normalData[(originalOffset * 3) + 2]);
- if (uvs && uvs.length) {
- newUVsData.push(uvs[(originalOffset * 2)]);
- newUVsData.push(uvs[(originalOffset * 2) + 1]);
- }
- else if (colorsData && colorsData.length) {
- newColorsData.push(colorsData[(originalOffset * 4)]);
- newColorsData.push(colorsData[(originalOffset * 4) + 1]);
- newColorsData.push(colorsData[(originalOffset * 4) + 2]);
- newColorsData.push(colorsData[(originalOffset * 4) + 3]);
- }
- ++vertexCount;
- });
- }
- }
- var startingIndex = this._reconstructedMesh.getTotalIndices();
- var startingVertex = this._reconstructedMesh.getTotalVertices();
- var submeshesArray = this._reconstructedMesh.subMeshes;
- this._reconstructedMesh.subMeshes = [];
- var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
- var originalIndices = this._mesh.getIndices();
- for (i = 0; i < newTriangles.length; ++i) {
- t = newTriangles[i]; //now get the new referencing point for each vertex
- [0, 1, 2].forEach(function (idx) {
- var id = originalIndices[t.originalOffset + idx];
- var offset = t.vertices[idx].originalOffsets.indexOf(id);
- if (offset < 0)
- offset = 0;
- newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
- });
- }
- //overwriting the old vertex buffers and indices.
- this._reconstructedMesh.setIndices(newIndicesArray);
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
- if (newUVsData.length > 0)
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
- if (newColorsData.length > 0)
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
- //create submesh
- var originalSubmesh = this._mesh.subMeshes[submeshIndex];
- if (submeshIndex > 0) {
- this._reconstructedMesh.subMeshes = [];
- submeshesArray.forEach(function (submesh) {
- new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
- });
- var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
- }
- };
- QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
- this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
- this._reconstructedMesh.material = this._mesh.material;
- this._reconstructedMesh.parent = this._mesh.parent;
- this._reconstructedMesh.isVisible = false;
- this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
- };
- QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
- for (var i = 0; i < vertex1.triangleCount; ++i) {
- var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
- if (t.deleted)
- continue;
- var s = this.references[vertex1.triangleStart + i].vertexId;
- var v1 = t.vertices[(s + 1) % 3];
- var v2 = t.vertices[(s + 2) % 3];
- if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
- deletedArray[i] = true;
- delTr.push(t);
- continue;
- }
- var d1 = v1.position.subtract(point);
- d1 = d1.normalize();
- var d2 = v2.position.subtract(point);
- d2 = d2.normalize();
- if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
- return true;
- var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
- deletedArray[i] = false;
- if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
- return true;
- }
- return false;
- };
- QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
- var newDeleted = deletedTriangles;
- for (var i = 0; i < vertex.triangleCount; ++i) {
- var ref = this.references[vertex.triangleStart + i];
- var t = this.triangles[ref.triangleId];
- if (t.deleted)
- continue;
- if (deletedArray[i] && t.deletePending) {
- t.deleted = true;
- newDeleted++;
- continue;
- }
- t.vertices[ref.vertexId] = origVertex;
- t.isDirty = true;
- t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
- t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
- t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
- t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
- this.references.push(ref);
- }
- return newDeleted;
- };
- QuadraticErrorSimplification.prototype.identifyBorder = function () {
- for (var i = 0; i < this.vertices.length; ++i) {
- var vCount = [];
- var vId = [];
- var v = this.vertices[i];
- var j;
- for (j = 0; j < v.triangleCount; ++j) {
- var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
- for (var ii = 0; ii < 3; ii++) {
- var ofs = 0;
- var vv = triangle.vertices[ii];
- while (ofs < vCount.length) {
- if (vId[ofs] === vv.id)
- break;
- ++ofs;
- }
- if (ofs === vCount.length) {
- vCount.push(1);
- vId.push(vv.id);
- }
- else {
- vCount[ofs]++;
- }
- }
- }
- for (j = 0; j < vCount.length; ++j) {
- if (vCount[j] === 1) {
- this.vertices[vId[j]].isBorder = true;
- }
- else {
- this.vertices[vId[j]].isBorder = false;
- }
- }
- }
- };
- QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
- if (identifyBorders === void 0) { identifyBorders = false; }
- var i;
- if (!identifyBorders) {
- var newTrianglesVector = [];
- for (i = 0; i < this.triangles.length; ++i) {
- if (!this.triangles[i].deleted) {
- newTrianglesVector.push(this.triangles[i]);
- }
- }
- this.triangles = newTrianglesVector;
- }
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleCount = 0;
- this.vertices[i].triangleStart = 0;
- }
- var t;
- var j;
- var v;
- for (i = 0; i < this.triangles.length; ++i) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- v = t.vertices[j];
- v.triangleCount++;
- }
- }
- var tStart = 0;
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleStart = tStart;
- tStart += this.vertices[i].triangleCount;
- this.vertices[i].triangleCount = 0;
- }
- var newReferences = new Array(this.triangles.length * 3);
- for (i = 0; i < this.triangles.length; ++i) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- v = t.vertices[j];
- newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
- v.triangleCount++;
- }
- }
- this.references = newReferences;
- if (identifyBorders) {
- this.identifyBorder();
- }
- };
- QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
- var x = point.x;
- var y = point.y;
- var z = point.z;
- 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
- + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
- };
- QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
- var q = vertex1.q.add(vertex2.q);
- var border = vertex1.isBorder && vertex2.isBorder;
- var error = 0;
- var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
- if (qDet !== 0 && !border) {
- if (!pointResult) {
- pointResult = BABYLON.Vector3.Zero();
- }
- pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
- pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
- pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
- error = this.vertexError(q, pointResult);
- }
- else {
- var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
- //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
- var error1 = this.vertexError(q, vertex1.position);
- var error2 = this.vertexError(q, vertex2.position);
- var error3 = this.vertexError(q, p3);
- error = Math.min(error1, error2, error3);
- if (error === error1) {
- if (pointResult) {
- pointResult.copyFrom(vertex1.position);
- }
- }
- else if (error === error2) {
- if (pointResult) {
- pointResult.copyFrom(vertex2.position);
- }
- }
- else {
- if (pointResult) {
- pointResult.copyFrom(p3);
- }
- }
- }
- return error;
- };
- return QuadraticErrorSimplification;
- })();
- BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var serializedGeometries = [];
- var serializeGeometry = function (geometry, serializationGeometries) {
- if (serializedGeometries[geometry.id]) {
- return;
- }
- if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
- serializationGeometries.boxes.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
- serializationGeometries.spheres.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
- serializationGeometries.cylinders.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
- serializationGeometries.toruses.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
- serializationGeometries.grounds.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
- serializationGeometries.planes.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
- serializationGeometries.torusKnots.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
- throw new Error("Unknown primitive type");
- }
- else {
- serializationGeometries.vertexData.push(geometry.serializeVerticeData());
- }
- serializedGeometries[geometry.id] = true;
- };
- var serializeMesh = function (mesh, serializationScene) {
- var serializationObject = {};
- serializationObject.name = mesh.name;
- serializationObject.id = mesh.id;
- if (BABYLON.Tags.HasTags(mesh)) {
- serializationObject.tags = BABYLON.Tags.GetTags(mesh);
- }
- serializationObject.position = mesh.position.asArray();
- if (mesh.rotationQuaternion) {
- serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
- }
- else if (mesh.rotation) {
- serializationObject.rotation = mesh.rotation.asArray();
- }
- serializationObject.scaling = mesh.scaling.asArray();
- serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
- serializationObject.isEnabled = mesh.isEnabled();
- serializationObject.isVisible = mesh.isVisible;
- serializationObject.infiniteDistance = mesh.infiniteDistance;
- serializationObject.pickable = mesh.isPickable;
- serializationObject.receiveShadows = mesh.receiveShadows;
- serializationObject.billboardMode = mesh.billboardMode;
- serializationObject.visibility = mesh.visibility;
- serializationObject.checkCollisions = mesh.checkCollisions;
- // Parent
- if (mesh.parent) {
- serializationObject.parentId = mesh.parent.id;
- }
- // Geometry
- var geometry = mesh._geometry;
- if (geometry) {
- var geometryId = geometry.id;
- serializationObject.geometryId = geometryId;
- if (!mesh.getScene().getGeometryByID(geometryId)) {
- // 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
- serializeGeometry(geometry, serializationScene.geometries);
- }
- // SubMeshes
- serializationObject.subMeshes = [];
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- serializationObject.subMeshes.push({
- materialIndex: subMesh.materialIndex,
- verticesStart: subMesh.verticesStart,
- verticesCount: subMesh.verticesCount,
- indexStart: subMesh.indexStart,
- indexCount: subMesh.indexCount
- });
- }
- }
- // Material
- if (mesh.material) {
- serializationObject.materialId = mesh.material.id;
- }
- else {
- mesh.material = null;
- }
- // Skeleton
- if (mesh.skeleton) {
- serializationObject.skeletonId = mesh.skeleton.id;
- }
- // Physics
- if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
- serializationObject.physicsMass = mesh.getPhysicsMass();
- serializationObject.physicsFriction = mesh.getPhysicsFriction();
- serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
- switch (mesh.getPhysicsImpostor()) {
- case BABYLON.PhysicsEngine.BoxImpostor:
- serializationObject.physicsImpostor = 1;
- break;
- case BABYLON.PhysicsEngine.SphereImpostor:
- serializationObject.physicsImpostor = 2;
- break;
- }
- }
- // Instances
- serializationObject.instances = [];
- for (var index = 0; index < mesh.instances.length; index++) {
- var instance = mesh.instances[index];
- var serializationInstance = {
- name: instance.name,
- position: instance.position.asArray(),
- scaling: instance.scaling.asArray()
- };
- if (instance.rotationQuaternion) {
- serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
- }
- else if (instance.rotation) {
- serializationInstance.rotation = instance.rotation.asArray();
- }
- serializationObject.instances.push(serializationInstance);
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
- serializationInstance.ranges = instance.serializeAnimationRanges();
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
- serializationObject.ranges = mesh.serializeAnimationRanges();
- // Layer mask
- serializationObject.layerMask = mesh.layerMask;
- return serializationObject;
- };
- var finalizeSingleMesh = function (mesh, serializationObject) {
- //only works if the mesh is already loaded
- if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
- //serialize material
- if (mesh.material) {
- if (mesh.material instanceof BABYLON.StandardMaterial) {
- serializationObject.materials = serializationObject.materials || [];
- if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
- serializationObject.materials.push(mesh.material.serialize());
- }
- }
- else if (mesh.material instanceof BABYLON.MultiMaterial) {
- serializationObject.multiMaterials = serializationObject.multiMaterials || [];
- if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
- serializationObject.multiMaterials.push(mesh.material.serialize());
- }
- }
- }
- //serialize geometry
- var geometry = mesh._geometry;
- if (geometry) {
- if (!serializationObject.geometries) {
- serializationObject.geometries = {};
- serializationObject.geometries.boxes = [];
- serializationObject.geometries.spheres = [];
- serializationObject.geometries.cylinders = [];
- serializationObject.geometries.toruses = [];
- serializationObject.geometries.grounds = [];
- serializationObject.geometries.planes = [];
- serializationObject.geometries.torusKnots = [];
- serializationObject.geometries.vertexData = [];
- }
- serializeGeometry(geometry, serializationObject.geometries);
- }
- // Skeletons
- if (mesh.skeleton) {
- serializationObject.skeletons = serializationObject.skeletons || [];
- serializationObject.skeletons.push(mesh.skeleton.serialize());
- }
- //serialize the actual mesh
- serializationObject.meshes = serializationObject.meshes || [];
- serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
- }
- };
- var SceneSerializer = (function () {
- function SceneSerializer() {
- }
- SceneSerializer.ClearCache = function () {
- serializedGeometries = [];
- };
- SceneSerializer.Serialize = function (scene) {
- var serializationObject = {};
- // Scene
- serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
- serializationObject.autoClear = scene.autoClear;
- serializationObject.clearColor = scene.clearColor.asArray();
- serializationObject.ambientColor = scene.ambientColor.asArray();
- serializationObject.gravity = scene.gravity.asArray();
- serializationObject.collisionsEnabled = scene.collisionsEnabled;
- serializationObject.workerCollisions = scene.workerCollisions;
- // Fog
- if (scene.fogMode && scene.fogMode !== 0) {
- serializationObject.fogMode = scene.fogMode;
- serializationObject.fogColor = scene.fogColor.asArray();
- serializationObject.fogStart = scene.fogStart;
- serializationObject.fogEnd = scene.fogEnd;
- serializationObject.fogDensity = scene.fogDensity;
- }
- //Physics
- if (scene.isPhysicsEnabled()) {
- serializationObject.physicsEnabled = true;
- serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
- serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
- }
- // Lights
- serializationObject.lights = [];
- var index;
- var light;
- for (index = 0; index < scene.lights.length; index++) {
- light = scene.lights[index];
- serializationObject.lights.push(light.serialize());
- }
- // Cameras
- serializationObject.cameras = [];
- for (index = 0; index < scene.cameras.length; index++) {
- var camera = scene.cameras[index];
- serializationObject.cameras.push(camera.serialize());
- }
- if (scene.activeCamera) {
- serializationObject.activeCameraID = scene.activeCamera.id;
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
- // Materials
- serializationObject.materials = [];
- serializationObject.multiMaterials = [];
- var material;
- for (index = 0; index < scene.materials.length; index++) {
- material = scene.materials[index];
- serializationObject.materials.push(material.serialize());
- }
- // MultiMaterials
- serializationObject.multiMaterials = [];
- for (index = 0; index < scene.multiMaterials.length; index++) {
- var multiMaterial = scene.multiMaterials[index];
- serializationObject.multiMaterials.push(multiMaterial.serialize());
- }
- // Skeletons
- serializationObject.skeletons = [];
- for (index = 0; index < scene.skeletons.length; index++) {
- serializationObject.skeletons.push(scene.skeletons[index].serialize());
- }
- // Geometries
- serializationObject.geometries = {};
- serializationObject.geometries.boxes = [];
- serializationObject.geometries.spheres = [];
- serializationObject.geometries.cylinders = [];
- serializationObject.geometries.toruses = [];
- serializationObject.geometries.grounds = [];
- serializationObject.geometries.planes = [];
- serializationObject.geometries.torusKnots = [];
- serializationObject.geometries.vertexData = [];
- serializedGeometries = [];
- var geometries = scene.getGeometries();
- for (index = 0; index < geometries.length; index++) {
- var geometry = geometries[index];
- if (geometry.isReady()) {
- serializeGeometry(geometry, serializationObject.geometries);
- }
- }
- // Meshes
- serializationObject.meshes = [];
- for (index = 0; index < scene.meshes.length; index++) {
- var abstractMesh = scene.meshes[index];
- if (abstractMesh instanceof BABYLON.Mesh) {
- var mesh = abstractMesh;
- if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
- serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
- }
- }
- }
- // Particles Systems
- serializationObject.particleSystems = [];
- for (index = 0; index < scene.particleSystems.length; index++) {
- serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
- }
- // Lens flares
- serializationObject.lensFlareSystems = [];
- for (index = 0; index < scene.lensFlareSystems.length; index++) {
- serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
- }
- // Shadows
- serializationObject.shadowGenerators = [];
- for (index = 0; index < scene.lights.length; index++) {
- light = scene.lights[index];
- if (light.getShadowGenerator()) {
- serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
- }
- }
- return serializationObject;
- };
- SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
- if (withParents === void 0) { withParents = false; }
- if (withChildren === void 0) { withChildren = false; }
- var serializationObject = {};
- toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
- if (withParents || withChildren) {
- //deliberate for loop! not for each, appended should be processed as well.
- for (var i = 0; i < toSerialize.length; ++i) {
- if (withChildren) {
- toSerialize[i].getDescendants().forEach(function (node) {
- if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
- toSerialize.push(node);
- }
- });
- }
- //make sure the array doesn't contain the object already
- if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
- toSerialize.push(toSerialize[i].parent);
- }
- }
- }
- toSerialize.forEach(function (mesh) {
- finalizeSingleMesh(mesh, serializationObject);
- });
- return serializationObject;
- };
- return SceneSerializer;
- })();
- BABYLON.SceneSerializer = SceneSerializer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Unique ID when we import meshes from Babylon to CSG
- var currentCSGMeshId = 0;
- // # class Vertex
- // Represents a vertex of a polygon. Use your own vertex class instead of this
- // one to provide additional features like texture coordinates and vertex
- // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
- // `flip()`, and `interpolate()` methods that behave analogous to the ones
- // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
- // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
- // is not used anywhere else.
- // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
- var Vertex = (function () {
- function Vertex(pos, normal, uv) {
- this.pos = pos;
- this.normal = normal;
- this.uv = uv;
- }
- Vertex.prototype.clone = function () {
- return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
- };
- // Invert all orientation-specific data (e.g. vertex normal). Called when the
- // orientation of a polygon is flipped.
- Vertex.prototype.flip = function () {
- this.normal = this.normal.scale(-1);
- };
- // Create a new vertex between this vertex and `other` by linearly
- // interpolating all properties using a parameter of `t`. Subclasses should
- // override this to interpolate additional properties.
- Vertex.prototype.interpolate = function (other, t) {
- 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));
- };
- return Vertex;
- })();
- // # class Plane
- // Represents a plane in 3D space.
- var Plane = (function () {
- function Plane(normal, w) {
- this.normal = normal;
- this.w = w;
- }
- Plane.FromPoints = function (a, b, c) {
- var v0 = c.subtract(a);
- var v1 = b.subtract(a);
- if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
- return null;
- }
- var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
- return new Plane(n, BABYLON.Vector3.Dot(n, a));
- };
- Plane.prototype.clone = function () {
- return new Plane(this.normal.clone(), this.w);
- };
- Plane.prototype.flip = function () {
- this.normal.scaleInPlace(-1);
- this.w = -this.w;
- };
- // Split `polygon` by this plane if needed, then put the polygon or polygon
- // fragments in the appropriate lists. Coplanar polygons go into either
- // `coplanarFront` or `coplanarBack` depending on their orientation with
- // respect to this plane. Polygons in front or in back of this plane go into
- // either `front` or `back`.
- Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
- var COPLANAR = 0;
- var FRONT = 1;
- var BACK = 2;
- var SPANNING = 3;
- // Classify each point as well as the entire polygon into one of the above
- // four classes.
- var polygonType = 0;
- var types = [];
- var i;
- var t;
- for (i = 0; i < polygon.vertices.length; i++) {
- t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
- var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
- polygonType |= type;
- types.push(type);
- }
- // Put the polygon in the correct list, splitting it when necessary.
- switch (polygonType) {
- case COPLANAR:
- (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
- break;
- case FRONT:
- front.push(polygon);
- break;
- case BACK:
- back.push(polygon);
- break;
- case SPANNING:
- var f = [], b = [];
- for (i = 0; i < polygon.vertices.length; i++) {
- var j = (i + 1) % polygon.vertices.length;
- var ti = types[i], tj = types[j];
- var vi = polygon.vertices[i], vj = polygon.vertices[j];
- if (ti !== BACK)
- f.push(vi);
- if (ti !== FRONT)
- b.push(ti !== BACK ? vi.clone() : vi);
- if ((ti | tj) === SPANNING) {
- t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
- var v = vi.interpolate(vj, t);
- f.push(v);
- b.push(v.clone());
- }
- }
- var poly;
- if (f.length >= 3) {
- poly = new Polygon(f, polygon.shared);
- if (poly.plane)
- front.push(poly);
- }
- if (b.length >= 3) {
- poly = new Polygon(b, polygon.shared);
- if (poly.plane)
- back.push(poly);
- }
- break;
- }
- };
- // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
- // point is on the plane.
- Plane.EPSILON = 1e-5;
- return Plane;
- })();
- // # class Polygon
- // Represents a convex polygon. The vertices used to initialize a polygon must
- // be coplanar and form a convex loop.
- //
- // Each convex polygon has a `shared` property, which is shared between all
- // polygons that are clones of each other or were split from the same polygon.
- // This can be used to define per-polygon properties (such as surface color).
- var Polygon = (function () {
- function Polygon(vertices, shared) {
- this.vertices = vertices;
- this.shared = shared;
- this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
- }
- Polygon.prototype.clone = function () {
- var vertices = this.vertices.map(function (v) { return v.clone(); });
- return new Polygon(vertices, this.shared);
- };
- Polygon.prototype.flip = function () {
- this.vertices.reverse().map(function (v) { v.flip(); });
- this.plane.flip();
- };
- return Polygon;
- })();
- // # class Node
- // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
- // by picking a polygon to split along. That polygon (and all other coplanar
- // polygons) are added directly to that node and the other polygons are added to
- // the front and/or back subtrees. This is not a leafy BSP tree since there is
- // no distinction between internal and leaf nodes.
- var Node = (function () {
- function Node(polygons) {
- this.plane = null;
- this.front = null;
- this.back = null;
- this.polygons = [];
- if (polygons) {
- this.build(polygons);
- }
- }
- Node.prototype.clone = function () {
- var node = new Node();
- node.plane = this.plane && this.plane.clone();
- node.front = this.front && this.front.clone();
- node.back = this.back && this.back.clone();
- node.polygons = this.polygons.map(function (p) { return p.clone(); });
- return node;
- };
- // Convert solid space to empty space and empty space to solid space.
- Node.prototype.invert = function () {
- for (var i = 0; i < this.polygons.length; i++) {
- this.polygons[i].flip();
- }
- if (this.plane) {
- this.plane.flip();
- }
- if (this.front) {
- this.front.invert();
- }
- if (this.back) {
- this.back.invert();
- }
- var temp = this.front;
- this.front = this.back;
- this.back = temp;
- };
- // Recursively remove all polygons in `polygons` that are inside this BSP
- // tree.
- Node.prototype.clipPolygons = function (polygons) {
- if (!this.plane)
- return polygons.slice();
- var front = [], back = [];
- for (var i = 0; i < polygons.length; i++) {
- this.plane.splitPolygon(polygons[i], front, back, front, back);
- }
- if (this.front) {
- front = this.front.clipPolygons(front);
- }
- if (this.back) {
- back = this.back.clipPolygons(back);
- }
- else {
- back = [];
- }
- return front.concat(back);
- };
- // Remove all polygons in this BSP tree that are inside the other BSP tree
- // `bsp`.
- Node.prototype.clipTo = function (bsp) {
- this.polygons = bsp.clipPolygons(this.polygons);
- if (this.front)
- this.front.clipTo(bsp);
- if (this.back)
- this.back.clipTo(bsp);
- };
- // Return a list of all polygons in this BSP tree.
- Node.prototype.allPolygons = function () {
- var polygons = this.polygons.slice();
- if (this.front)
- polygons = polygons.concat(this.front.allPolygons());
- if (this.back)
- polygons = polygons.concat(this.back.allPolygons());
- return polygons;
- };
- // Build a BSP tree out of `polygons`. When called on an existing tree, the
- // new polygons are filtered down to the bottom of the tree and become new
- // nodes there. Each set of polygons is partitioned using the first polygon
- // (no heuristic is used to pick a good split).
- Node.prototype.build = function (polygons) {
- if (!polygons.length)
- return;
- if (!this.plane)
- this.plane = polygons[0].plane.clone();
- var front = [], back = [];
- for (var i = 0; i < polygons.length; i++) {
- this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
- }
- if (front.length) {
- if (!this.front)
- this.front = new Node();
- this.front.build(front);
- }
- if (back.length) {
- if (!this.back)
- this.back = new Node();
- this.back.build(back);
- }
- };
- return Node;
- })();
- var CSG = (function () {
- function CSG() {
- this.polygons = new Array();
- }
- // Convert BABYLON.Mesh to BABYLON.CSG
- CSG.FromMesh = function (mesh) {
- var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
- var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
- if (mesh instanceof BABYLON.Mesh) {
- mesh.computeWorldMatrix(true);
- matrix = mesh.getWorldMatrix();
- meshPosition = mesh.position.clone();
- meshRotation = mesh.rotation.clone();
- if (mesh.rotationQuaternion) {
- meshRotationQuaternion = mesh.rotationQuaternion.clone();
- }
- meshScaling = mesh.scaling.clone();
- }
- else {
- throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
- }
- var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var subMeshes = mesh.subMeshes;
- for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
- for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
- vertices = [];
- for (var j = 0; j < 3; j++) {
- var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
- uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
- var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
- position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
- normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
- vertex = new Vertex(position, normal, uv);
- vertices.push(vertex);
- }
- polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
- // To handle the case of degenerated triangle
- // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
- if (polygon.plane)
- polygons.push(polygon);
- }
- }
- var csg = CSG.FromPolygons(polygons);
- csg.matrix = matrix;
- csg.position = meshPosition;
- csg.rotation = meshRotation;
- csg.scaling = meshScaling;
- csg.rotationQuaternion = meshRotationQuaternion;
- currentCSGMeshId++;
- return csg;
- };
- // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
- CSG.FromPolygons = function (polygons) {
- var csg = new CSG();
- csg.polygons = polygons;
- return csg;
- };
- CSG.prototype.clone = function () {
- var csg = new CSG();
- csg.polygons = this.polygons.map(function (p) { return p.clone(); });
- csg.copyTransformAttributes(this);
- return csg;
- };
- CSG.prototype.toPolygons = function () {
- return this.polygons;
- };
- CSG.prototype.union = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.unionInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- this.polygons = a.allPolygons();
- };
- CSG.prototype.subtract = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.invert();
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- a.invert();
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.subtractInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.invert();
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- a.invert();
- this.polygons = a.allPolygons();
- };
- CSG.prototype.intersect = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.invert();
- b.clipTo(a);
- b.invert();
- a.clipTo(b);
- b.clipTo(a);
- a.build(b.allPolygons());
- a.invert();
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.intersectInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.invert();
- b.clipTo(a);
- b.invert();
- a.clipTo(b);
- b.clipTo(a);
- a.build(b.allPolygons());
- a.invert();
- this.polygons = a.allPolygons();
- };
- // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
- // not modified.
- CSG.prototype.inverse = function () {
- var csg = this.clone();
- csg.inverseInPlace();
- return csg;
- };
- CSG.prototype.inverseInPlace = function () {
- this.polygons.map(function (p) { p.flip(); });
- };
- // This is used to keep meshes transformations so they can be restored
- // when we build back a Babylon Mesh
- // NB : All CSG operations are performed in world coordinates
- CSG.prototype.copyTransformAttributes = function (csg) {
- this.matrix = csg.matrix;
- this.position = csg.position;
- this.rotation = csg.rotation;
- this.scaling = csg.scaling;
- this.rotationQuaternion = csg.rotationQuaternion;
- return this;
- };
- // Build Raw mesh from CSG
- // Coordinates here are in world space
- CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
- var matrix = this.matrix.clone();
- matrix.invert();
- 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;
- if (keepSubMeshes) {
- // Sort Polygons, since subMeshes are indices range
- polygons.sort(function (a, b) {
- if (a.shared.meshId === b.shared.meshId) {
- return a.shared.subMeshId - b.shared.subMeshId;
- }
- else {
- return a.shared.meshId - b.shared.meshId;
- }
- });
- }
- for (var i = 0, il = polygons.length; i < il; i++) {
- polygon = polygons[i];
- // Building SubMeshes
- if (!subMesh_dict[polygon.shared.meshId]) {
- subMesh_dict[polygon.shared.meshId] = {};
- }
- if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
- subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
- indexStart: +Infinity,
- indexEnd: -Infinity,
- materialIndex: polygon.shared.materialIndex
- };
- }
- subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
- for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
- polygonIndices[0] = 0;
- polygonIndices[1] = j - 1;
- polygonIndices[2] = j;
- for (var k = 0; k < 3; k++) {
- vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
- normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
- uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
- var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
- var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
- vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
- // Check if 2 points can be merged
- if (!(typeof vertex_idx !== 'undefined' &&
- normals[vertex_idx * 3] === localNormal.x &&
- normals[vertex_idx * 3 + 1] === localNormal.y &&
- normals[vertex_idx * 3 + 2] === localNormal.z &&
- uvs[vertex_idx * 2] === uv.x &&
- uvs[vertex_idx * 2 + 1] === uv.y)) {
- vertices.push(localVertex.x, localVertex.y, localVertex.z);
- uvs.push(uv.x, uv.y);
- normals.push(normal.x, normal.y, normal.z);
- vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
- }
- indices.push(vertex_idx);
- subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
- subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
- currentIndex++;
- }
- }
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
- mesh.setIndices(indices);
- if (keepSubMeshes) {
- // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
- var materialIndexOffset = 0, materialMaxIndex;
- mesh.subMeshes = new Array();
- for (var m in subMesh_dict) {
- materialMaxIndex = -1;
- for (var sm in subMesh_dict[m]) {
- subMesh_obj = subMesh_dict[m][sm];
- BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
- materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
- }
- materialIndexOffset += ++materialMaxIndex;
- }
- }
- return mesh;
- };
- // Build Mesh from CSG taking material and transforms into account
- CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
- var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
- mesh.material = material;
- mesh.position.copyFrom(this.position);
- mesh.rotation.copyFrom(this.rotation);
- if (this.rotationQuaternion) {
- mesh.rotationQuaternion = this.rotationQuaternion.clone();
- }
- mesh.scaling.copyFrom(this.scaling);
- mesh.computeWorldMatrix(true);
- return mesh;
- };
- return CSG;
- })();
- BABYLON.CSG = CSG;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRDistortionCorrectionPostProcess = (function (_super) {
- __extends(VRDistortionCorrectionPostProcess, _super);
- //ANY
- function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
- var _this = this;
- _super.call(this, name, "vrDistortionCorrection", [
- 'LensCenter',
- 'Scale',
- 'ScaleIn',
- 'HmdWarpParam'
- ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
- this._isRightEye = isRightEye;
- this._distortionFactors = vrMetrics.distortionK;
- this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
- this._lensCenterOffset = vrMetrics.lensCenterOffset;
- this.onSizeChanged = function () {
- _this.aspectRatio = _this.width * .5 / _this.height;
- _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
- _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
- _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
- };
- this.onApply = function (effect) {
- effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
- effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
- effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
- effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
- };
- }
- return VRDistortionCorrectionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
- })(BABYLON || (BABYLON = {}));
- // Mainly based on these 2 articles :
- // 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
- // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
- var BABYLON;
- (function (BABYLON) {
- (function (JoystickAxis) {
- JoystickAxis[JoystickAxis["X"] = 0] = "X";
- JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
- JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
- })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
- var JoystickAxis = BABYLON.JoystickAxis;
- var VirtualJoystick = (function () {
- function VirtualJoystick(leftJoystick) {
- var _this = this;
- if (leftJoystick) {
- this._leftJoystick = true;
- }
- else {
- this._leftJoystick = false;
- }
- this._joystickIndex = VirtualJoystick._globalJoystickIndex;
- VirtualJoystick._globalJoystickIndex++;
- // By default left & right arrow keys are moving the X
- // and up & down keys are moving the Y
- this._axisTargetedByLeftAndRight = JoystickAxis.X;
- this._axisTargetedByUpAndDown = JoystickAxis.Y;
- this.reverseLeftRight = false;
- this.reverseUpDown = false;
- // collections of pointers
- this._touches = new BABYLON.SmartCollection();
- this.deltaPosition = BABYLON.Vector3.Zero();
- this._joystickSensibility = 25;
- this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
- this._rotationSpeed = 25;
- this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
- this._rotateOnAxisRelativeToMesh = false;
- this._onResize = function (evt) {
- VirtualJoystick.vjCanvasWidth = window.innerWidth;
- VirtualJoystick.vjCanvasHeight = window.innerHeight;
- VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
- VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
- VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
- VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
- };
- // injecting a canvas element on top of the canvas 3D game
- if (!VirtualJoystick.vjCanvas) {
- window.addEventListener("resize", this._onResize, false);
- VirtualJoystick.vjCanvas = document.createElement("canvas");
- VirtualJoystick.vjCanvasWidth = window.innerWidth;
- VirtualJoystick.vjCanvasHeight = window.innerHeight;
- VirtualJoystick.vjCanvas.width = window.innerWidth;
- VirtualJoystick.vjCanvas.height = window.innerHeight;
- VirtualJoystick.vjCanvas.style.width = "100%";
- VirtualJoystick.vjCanvas.style.height = "100%";
- VirtualJoystick.vjCanvas.style.position = "absolute";
- VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
- VirtualJoystick.vjCanvas.style.top = "0px";
- VirtualJoystick.vjCanvas.style.left = "0px";
- VirtualJoystick.vjCanvas.style.zIndex = "5";
- VirtualJoystick.vjCanvas.style.msTouchAction = "none";
- // Support for jQuery PEP polyfill
- VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
- VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
- VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
- VirtualJoystick.vjCanvasContext.lineWidth = 2;
- document.body.appendChild(VirtualJoystick.vjCanvas);
- }
- VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
- VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
- this.pressed = false;
- // default joystick color
- this._joystickColor = "cyan";
- this._joystickPointerID = -1;
- // current joystick position
- this._joystickPointerPos = new BABYLON.Vector2(0, 0);
- this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
- // origin joystick position
- this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
- this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
- this._onPointerDownHandlerRef = function (evt) {
- _this._onPointerDown(evt);
- };
- this._onPointerMoveHandlerRef = function (evt) {
- _this._onPointerMove(evt);
- };
- this._onPointerOutHandlerRef = function (evt) {
- _this._onPointerUp(evt);
- };
- this._onPointerUpHandlerRef = function (evt) {
- _this._onPointerUp(evt);
- };
- VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
- evt.preventDefault(); // Disables system menu
- }, false);
- requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
- }
- VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
- this._joystickSensibility = newJoystickSensibility;
- this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
- };
- VirtualJoystick.prototype._onPointerDown = function (e) {
- var positionOnScreenCondition;
- e.preventDefault();
- if (this._leftJoystick === true) {
- positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
- }
- else {
- positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
- }
- if (positionOnScreenCondition && this._joystickPointerID < 0) {
- // First contact will be dedicated to the virtual joystick
- this._joystickPointerID = e.pointerId;
- this._joystickPointerStartPos.x = e.clientX;
- this._joystickPointerStartPos.y = e.clientY;
- this._joystickPointerPos = this._joystickPointerStartPos.clone();
- this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
- this._deltaJoystickVector.x = 0;
- this._deltaJoystickVector.y = 0;
- this.pressed = true;
- this._touches.add(e.pointerId.toString(), e);
- }
- else {
- // You can only trigger the action buttons with a joystick declared
- if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
- this._action();
- this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
- }
- }
- };
- VirtualJoystick.prototype._onPointerMove = function (e) {
- // If the current pointer is the one associated to the joystick (first touch contact)
- if (this._joystickPointerID == e.pointerId) {
- this._joystickPointerPos.x = e.clientX;
- this._joystickPointerPos.y = e.clientY;
- this._deltaJoystickVector = this._joystickPointerPos.clone();
- this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
- var directionLeftRight = this.reverseLeftRight ? -1 : 1;
- var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
- switch (this._axisTargetedByLeftAndRight) {
- case JoystickAxis.X:
- this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- case JoystickAxis.Y:
- this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- case JoystickAxis.Z:
- this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- }
- var directionUpDown = this.reverseUpDown ? 1 : -1;
- var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
- switch (this._axisTargetedByUpAndDown) {
- case JoystickAxis.X:
- this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- case JoystickAxis.Y:
- this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- case JoystickAxis.Z:
- this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- }
- }
- else {
- if (this._touches.item(e.pointerId.toString())) {
- this._touches.item(e.pointerId.toString()).x = e.clientX;
- this._touches.item(e.pointerId.toString()).y = e.clientY;
- }
- }
- };
- VirtualJoystick.prototype._onPointerUp = function (e) {
- if (this._joystickPointerID == e.pointerId) {
- VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
- VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
- this._joystickPointerID = -1;
- this.pressed = false;
- }
- else {
- var touch = this._touches.item(e.pointerId.toString());
- if (touch) {
- VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
- }
- }
- this._deltaJoystickVector.x = 0;
- this._deltaJoystickVector.y = 0;
- this._touches.remove(e.pointerId.toString());
- };
- /**
- * Change the color of the virtual joystick
- * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
- */
- VirtualJoystick.prototype.setJoystickColor = function (newColor) {
- this._joystickColor = newColor;
- };
- VirtualJoystick.prototype.setActionOnTouch = function (action) {
- this._action = action;
- };
- // Define which axis you'd like to control for left & right
- VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
- switch (axis) {
- case JoystickAxis.X:
- case JoystickAxis.Y:
- case JoystickAxis.Z:
- this._axisTargetedByLeftAndRight = axis;
- break;
- default:
- this._axisTargetedByLeftAndRight = JoystickAxis.X;
- break;
- }
- };
- // Define which axis you'd like to control for up & down
- VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
- switch (axis) {
- case JoystickAxis.X:
- case JoystickAxis.Y:
- case JoystickAxis.Z:
- this._axisTargetedByUpAndDown = axis;
- break;
- default:
- this._axisTargetedByUpAndDown = JoystickAxis.Y;
- break;
- }
- };
- VirtualJoystick.prototype._clearCanvas = function () {
- if (this._leftJoystick) {
- VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
- }
- else {
- VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
- }
- };
- VirtualJoystick.prototype._drawVirtualJoystick = function () {
- var _this = this;
- if (this.pressed) {
- this._touches.forEach(function (touch) {
- if (touch.pointerId === _this._joystickPointerID) {
- VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
- VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.lineWidth = 6;
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.lineWidth = 2;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
- }
- else {
- VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.fillStyle = "white";
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = "red";
- VirtualJoystick.vjCanvasContext.lineWidth = 6;
- VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- touch.prevX = touch.x;
- touch.prevY = touch.y;
- }
- ;
- });
- }
- requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
- };
- VirtualJoystick.prototype.releaseCanvas = function () {
- if (VirtualJoystick.vjCanvas) {
- VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
- window.removeEventListener("resize", this._onResize);
- document.body.removeChild(VirtualJoystick.vjCanvas);
- VirtualJoystick.vjCanvas = null;
- }
- };
- // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
- VirtualJoystick._globalJoystickIndex = 0;
- return VirtualJoystick;
- })();
- BABYLON.VirtualJoystick = VirtualJoystick;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var VirtualJoysticksCamera = (function (_super) {
- __extends(VirtualJoysticksCamera, _super);
- function VirtualJoysticksCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this._leftjoystick = new BABYLON.VirtualJoystick(true);
- this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
- this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
- this._leftjoystick.setJoystickSensibility(0.15);
- this._rightjoystick = new BABYLON.VirtualJoystick(false);
- this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
- this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
- this._rightjoystick.reverseUpDown = true;
- this._rightjoystick.setJoystickSensibility(0.05);
- this._rightjoystick.setJoystickColor("yellow");
- }
- VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
- return this._leftjoystick;
- };
- VirtualJoysticksCamera.prototype.getRightJoystick = function () {
- return this._rightjoystick;
- };
- VirtualJoysticksCamera.prototype._checkInputs = function () {
- var speed = this._computeLocalCameraSpeed() * 50;
- var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
- var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
- this.cameraDirection = this.cameraDirection.add(deltaTransform);
- this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
- if (!this._leftjoystick.pressed) {
- this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
- }
- if (!this._rightjoystick.pressed) {
- this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
- }
- _super.prototype._checkInputs.call(this);
- };
- VirtualJoysticksCamera.prototype.dispose = function () {
- this._leftjoystick.releaseCanvas();
- _super.prototype.dispose.call(this);
- };
- return VirtualJoysticksCamera;
- })(BABYLON.FreeCamera);
- BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnaglyphPostProcess = (function (_super) {
- __extends(AnaglyphPostProcess, _super);
- function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
- }
- return AnaglyphPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OutlineRenderer = (function () {
- function OutlineRenderer(scene) {
- this._scene = scene;
- }
- OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
- var _this = this;
- if (useOverlay === void 0) { useOverlay = false; }
- var scene = this._scene;
- var engine = this._scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- if (!this.isReady(subMesh, hardwareInstancedRendering)) {
- return;
- }
- var mesh = subMesh.getRenderingMesh();
- var material = subMesh.getMaterial();
- engine.enableEffect(this._effect);
- this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
- this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
- this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- this._effect.setTexture("diffuseSampler", alphaTexture);
- this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
- };
- OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
- var mesh = subMesh.getMesh();
- var material = subMesh.getMaterial();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- return OutlineRenderer;
- })();
- BABYLON.OutlineRenderer = OutlineRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MeshAssetTask = (function () {
- function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
- this.name = name;
- this.meshesNames = meshesNames;
- this.rootUrl = rootUrl;
- this.sceneFilename = sceneFilename;
- this.isCompleted = false;
- }
- MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
- _this.loadedMeshes = meshes;
- _this.loadedParticleSystems = particleSystems;
- _this.loadedSkeletons = skeletons;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return MeshAssetTask;
- })();
- BABYLON.MeshAssetTask = MeshAssetTask;
- var TextFileAssetTask = (function () {
- function TextFileAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.Tools.LoadFile(this.url, function (data) {
- _this.text = data;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, scene.database, false, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return TextFileAssetTask;
- })();
- BABYLON.TextFileAssetTask = TextFileAssetTask;
- var BinaryFileAssetTask = (function () {
- function BinaryFileAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.Tools.LoadFile(this.url, function (data) {
- _this.data = data;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, scene.database, true, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return BinaryFileAssetTask;
- })();
- BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
- var ImageAssetTask = (function () {
- function ImageAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- var img = new Image();
- img.onload = function () {
- _this.image = img;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- };
- img.onerror = function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- };
- img.src = this.url;
- };
- return ImageAssetTask;
- })();
- BABYLON.ImageAssetTask = ImageAssetTask;
- var TextureAssetTask = (function () {
- function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- this.name = name;
- this.url = url;
- this.noMipmap = noMipmap;
- this.invertY = invertY;
- this.samplingMode = samplingMode;
- this.isCompleted = false;
- }
- TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- var onload = function () {
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- };
- var onerror = function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- };
- this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
- };
- return TextureAssetTask;
- })();
- BABYLON.TextureAssetTask = TextureAssetTask;
- var AssetsManager = (function () {
- function AssetsManager(scene) {
- this._tasks = new Array();
- this._waitingTasksCount = 0;
- this.useDefaultLoadingScreen = true;
- this._scene = scene;
- }
- AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
- var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addTextFileTask = function (taskName, url) {
- var task = new TextFileAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
- var task = new BinaryFileAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addImageTask = function (taskName, url) {
- var task = new ImageAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype._decreaseWaitingTasksCount = function () {
- this._waitingTasksCount--;
- if (this._waitingTasksCount === 0) {
- if (this.onFinish) {
- this.onFinish(this._tasks);
- }
- this._scene.getEngine().hideLoadingUI();
- }
- };
- AssetsManager.prototype._runTask = function (task) {
- var _this = this;
- task.run(this._scene, function () {
- if (_this.onTaskSuccess) {
- _this.onTaskSuccess(task);
- }
- _this._decreaseWaitingTasksCount();
- }, function () {
- if (_this.onTaskError) {
- _this.onTaskError(task);
- }
- _this._decreaseWaitingTasksCount();
- });
- };
- AssetsManager.prototype.reset = function () {
- this._tasks = new Array();
- return this;
- };
- AssetsManager.prototype.load = function () {
- this._waitingTasksCount = this._tasks.length;
- if (this._waitingTasksCount === 0) {
- if (this.onFinish) {
- this.onFinish(this._tasks);
- }
- return this;
- }
- if (this.useDefaultLoadingScreen) {
- this._scene.getEngine().displayLoadingUI();
- }
- for (var index = 0; index < this._tasks.length; index++) {
- var task = this._tasks[index];
- this._runTask(task);
- }
- return this;
- };
- return AssetsManager;
- })();
- BABYLON.AssetsManager = AssetsManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRDeviceOrientationFreeCamera = (function (_super) {
- __extends(VRDeviceOrientationFreeCamera, _super);
- function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
- if (compensateDistortion === void 0) { compensateDistortion = true; }
- _super.call(this, name, position, scene);
- this._alpha = 0;
- this._beta = 0;
- this._gamma = 0;
- var metrics = BABYLON.VRCameraMetrics.GetDefault();
- metrics.compensateDistortion = compensateDistortion;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
- this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
- }
- VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
- this._alpha = +evt.alpha | 0;
- this._beta = +evt.beta | 0;
- this._gamma = +evt.gamma | 0;
- if (this._gamma < 0) {
- this._gamma = 90 + this._gamma;
- }
- else {
- // Incline it in the correct angle.
- this._gamma = 270 - this._gamma;
- }
- this.rotation.x = this._gamma / 180.0 * Math.PI;
- this.rotation.y = -this._alpha / 180.0 * Math.PI;
- this.rotation.z = this._beta / 180.0 * Math.PI;
- };
- VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
- _super.prototype.attachControl.call(this, element, noPreventDefault);
- window.addEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
- _super.prototype.detachControl.call(this, element);
- window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- return VRDeviceOrientationFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var WebVRFreeCamera = (function (_super) {
- __extends(WebVRFreeCamera, _super);
- function WebVRFreeCamera(name, position, scene, compensateDistortion) {
- if (compensateDistortion === void 0) { compensateDistortion = true; }
- _super.call(this, name, position, scene);
- this._hmdDevice = null;
- this._sensorDevice = null;
- this._cacheState = null;
- this._cacheQuaternion = new BABYLON.Quaternion();
- this._cacheRotation = BABYLON.Vector3.Zero();
- this._vrEnabled = false;
- var metrics = BABYLON.VRCameraMetrics.GetDefault();
- metrics.compensateDistortion = compensateDistortion;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
- this._getWebVRDevices = this._getWebVRDevices.bind(this);
- }
- WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
- var size = devices.length;
- var i = 0;
- // Reset devices.
- this._sensorDevice = null;
- this._hmdDevice = null;
- // Search for a HmdDevice.
- while (i < size && this._hmdDevice === null) {
- if (devices[i] instanceof HMDVRDevice) {
- this._hmdDevice = devices[i];
- }
- i++;
- }
- i = 0;
- while (i < size && this._sensorDevice === null) {
- if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
- this._sensorDevice = devices[i];
- }
- i++;
- }
- this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
- };
- WebVRFreeCamera.prototype._checkInputs = function () {
- if (this._vrEnabled) {
- this._cacheState = this._sensorDevice.getState();
- this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
- this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
- this.rotation.x = -this._cacheRotation.z;
- this.rotation.y = -this._cacheRotation.y;
- this.rotation.z = this._cacheRotation.x;
- }
- _super.prototype._checkInputs.call(this);
- };
- WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
- _super.prototype.attachControl.call(this, element, noPreventDefault);
- if (navigator.getVRDevices) {
- navigator.getVRDevices().then(this._getWebVRDevices);
- }
- else if (navigator.mozGetVRDevices) {
- navigator.mozGetVRDevices(this._getWebVRDevices);
- }
- };
- WebVRFreeCamera.prototype.detachControl = function (element) {
- _super.prototype.detachControl.call(this, element);
- this._vrEnabled = false;
- };
- return WebVRFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.WebVRFreeCamera = WebVRFreeCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Standard optimizations
- var SceneOptimization = (function () {
- function SceneOptimization(priority) {
- if (priority === void 0) { priority = 0; }
- this.priority = priority;
- this.apply = function (scene) {
- return true; // Return true if everything that can be done was applied
- };
- }
- return SceneOptimization;
- })();
- BABYLON.SceneOptimization = SceneOptimization;
- var TextureOptimization = (function (_super) {
- __extends(TextureOptimization, _super);
- function TextureOptimization(priority, maximumSize) {
- var _this = this;
- if (priority === void 0) { priority = 0; }
- if (maximumSize === void 0) { maximumSize = 1024; }
- _super.call(this, priority);
- this.priority = priority;
- this.maximumSize = maximumSize;
- this.apply = function (scene) {
- var allDone = true;
- for (var index = 0; index < scene.textures.length; index++) {
- var texture = scene.textures[index];
- if (!texture.canRescale) {
- continue;
- }
- var currentSize = texture.getSize();
- var maxDimension = Math.max(currentSize.width, currentSize.height);
- if (maxDimension > _this.maximumSize) {
- texture.scale(0.5);
- allDone = false;
- }
- }
- return allDone;
- };
- }
- return TextureOptimization;
- })(SceneOptimization);
- BABYLON.TextureOptimization = TextureOptimization;
- var HardwareScalingOptimization = (function (_super) {
- __extends(HardwareScalingOptimization, _super);
- function HardwareScalingOptimization(priority, maximumScale) {
- var _this = this;
- if (priority === void 0) { priority = 0; }
- if (maximumScale === void 0) { maximumScale = 2; }
- _super.call(this, priority);
- this.priority = priority;
- this.maximumScale = maximumScale;
- this._currentScale = 1;
- this.apply = function (scene) {
- _this._currentScale++;
- scene.getEngine().setHardwareScalingLevel(_this._currentScale);
- return _this._currentScale >= _this.maximumScale;
- };
- }
- return HardwareScalingOptimization;
- })(SceneOptimization);
- BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
- var ShadowsOptimization = (function (_super) {
- __extends(ShadowsOptimization, _super);
- function ShadowsOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.shadowsEnabled = false;
- return true;
- };
- }
- return ShadowsOptimization;
- })(SceneOptimization);
- BABYLON.ShadowsOptimization = ShadowsOptimization;
- var PostProcessesOptimization = (function (_super) {
- __extends(PostProcessesOptimization, _super);
- function PostProcessesOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.postProcessesEnabled = false;
- return true;
- };
- }
- return PostProcessesOptimization;
- })(SceneOptimization);
- BABYLON.PostProcessesOptimization = PostProcessesOptimization;
- var LensFlaresOptimization = (function (_super) {
- __extends(LensFlaresOptimization, _super);
- function LensFlaresOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.lensFlaresEnabled = false;
- return true;
- };
- }
- return LensFlaresOptimization;
- })(SceneOptimization);
- BABYLON.LensFlaresOptimization = LensFlaresOptimization;
- var ParticlesOptimization = (function (_super) {
- __extends(ParticlesOptimization, _super);
- function ParticlesOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.particlesEnabled = false;
- return true;
- };
- }
- return ParticlesOptimization;
- })(SceneOptimization);
- BABYLON.ParticlesOptimization = ParticlesOptimization;
- var RenderTargetsOptimization = (function (_super) {
- __extends(RenderTargetsOptimization, _super);
- function RenderTargetsOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.renderTargetsEnabled = false;
- return true;
- };
- }
- return RenderTargetsOptimization;
- })(SceneOptimization);
- BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
- var MergeMeshesOptimization = (function (_super) {
- __extends(MergeMeshesOptimization, _super);
- function MergeMeshesOptimization() {
- var _this = this;
- _super.apply(this, arguments);
- this._canBeMerged = function (abstractMesh) {
- if (!(abstractMesh instanceof BABYLON.Mesh)) {
- return false;
- }
- var mesh = abstractMesh;
- if (!mesh.isVisible || !mesh.isEnabled()) {
- return false;
- }
- if (mesh.instances.length > 0) {
- return false;
- }
- if (mesh.skeleton || mesh.hasLODLevels) {
- return false;
- }
- if (mesh.parent) {
- return false;
- }
- return true;
- };
- this.apply = function (scene, updateSelectionTree) {
- var globalPool = scene.meshes.slice(0);
- var globalLength = globalPool.length;
- for (var index = 0; index < globalLength; index++) {
- var currentPool = new Array();
- var current = globalPool[index];
- // Checks
- if (!_this._canBeMerged(current)) {
- continue;
- }
- currentPool.push(current);
- // Find compatible meshes
- for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
- var otherMesh = globalPool[subIndex];
- if (!_this._canBeMerged(otherMesh)) {
- continue;
- }
- if (otherMesh.material !== current.material) {
- continue;
- }
- if (otherMesh.checkCollisions !== current.checkCollisions) {
- continue;
- }
- currentPool.push(otherMesh);
- globalLength--;
- globalPool.splice(subIndex, 1);
- subIndex--;
- }
- if (currentPool.length < 2) {
- continue;
- }
- // Merge meshes
- BABYLON.Mesh.MergeMeshes(currentPool);
- }
- if (updateSelectionTree != undefined) {
- if (updateSelectionTree) {
- scene.createOrUpdateSelectionOctree();
- }
- }
- else if (MergeMeshesOptimization.UpdateSelectionTree) {
- scene.createOrUpdateSelectionOctree();
- }
- return true;
- };
- }
- Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
- get: function () {
- return MergeMeshesOptimization._UpdateSelectionTree;
- },
- set: function (value) {
- MergeMeshesOptimization._UpdateSelectionTree = value;
- },
- enumerable: true,
- configurable: true
- });
- MergeMeshesOptimization._UpdateSelectionTree = false;
- return MergeMeshesOptimization;
- })(SceneOptimization);
- BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
- // Options
- var SceneOptimizerOptions = (function () {
- function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
- if (targetFrameRate === void 0) { targetFrameRate = 60; }
- if (trackerDuration === void 0) { trackerDuration = 2000; }
- this.targetFrameRate = targetFrameRate;
- this.trackerDuration = trackerDuration;
- this.optimizations = new Array();
- }
- SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 1024));
- return result;
- };
- SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 512));
- // Next priority
- priority++;
- result.optimizations.push(new RenderTargetsOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new HardwareScalingOptimization(priority, 2));
- return result;
- };
- SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 256));
- // Next priority
- priority++;
- result.optimizations.push(new RenderTargetsOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new HardwareScalingOptimization(priority, 4));
- return result;
- };
- return SceneOptimizerOptions;
- })();
- BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
- // Scene optimizer tool
- var SceneOptimizer = (function () {
- function SceneOptimizer() {
- }
- SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
- // TODO: add an epsilon
- if (scene.getEngine().getFps() >= options.targetFrameRate) {
- if (onSuccess) {
- onSuccess();
- }
- return;
- }
- // Apply current level of optimizations
- var allDone = true;
- var noOptimizationApplied = true;
- for (var index = 0; index < options.optimizations.length; index++) {
- var optimization = options.optimizations[index];
- if (optimization.priority === currentPriorityLevel) {
- noOptimizationApplied = false;
- allDone = allDone && optimization.apply(scene);
- }
- }
- // If no optimization was applied, this is a failure :(
- if (noOptimizationApplied) {
- if (onFailure) {
- onFailure();
- }
- return;
- }
- // If all optimizations were done, move to next level
- if (allDone) {
- currentPriorityLevel++;
- }
- // Let's the system running for a specific amount of time before checking FPS
- scene.executeWhenReady(function () {
- setTimeout(function () {
- SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
- }, options.trackerDuration);
- });
- };
- SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
- if (!options) {
- options = SceneOptimizerOptions.ModerateDegradationAllowed();
- }
- // Let's the system running for a specific amount of time before checking FPS
- scene.executeWhenReady(function () {
- setTimeout(function () {
- SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
- }, options.trackerDuration);
- });
- };
- return SceneOptimizer;
- })();
- BABYLON.SceneOptimizer = SceneOptimizer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var MeshLODLevel = (function () {
- function MeshLODLevel(distance, mesh) {
- this.distance = distance;
- this.mesh = mesh;
- }
- return MeshLODLevel;
- })();
- Internals.MeshLODLevel = MeshLODLevel;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RawTexture = (function (_super) {
- __extends(RawTexture, _super);
- function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps, invertY);
- this.format = format;
- this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
- this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- }
- RawTexture.prototype.update = function (data) {
- this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
- };
- // Statics
- RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
- };
- return RawTexture;
- })(BABYLON.Texture);
- BABYLON.RawTexture = RawTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var IndexedVector2 = (function (_super) {
- __extends(IndexedVector2, _super);
- function IndexedVector2(original, index) {
- _super.call(this, original.x, original.y);
- this.index = index;
- }
- return IndexedVector2;
- })(BABYLON.Vector2);
- var PolygonPoints = (function () {
- function PolygonPoints() {
- this.elements = new Array();
- }
- PolygonPoints.prototype.add = function (originalPoints) {
- var _this = this;
- var result = new Array();
- originalPoints.forEach(function (point) {
- if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
- var newPoint = new IndexedVector2(point, _this.elements.length);
- result.push(newPoint);
- _this.elements.push(newPoint);
- }
- });
- return result;
- };
- PolygonPoints.prototype.computeBounds = function () {
- var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
- var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
- this.elements.forEach(function (point) {
- // x
- if (point.x < lmin.x) {
- lmin.x = point.x;
- }
- else if (point.x > lmax.x) {
- lmax.x = point.x;
- }
- // y
- if (point.y < lmin.y) {
- lmin.y = point.y;
- }
- else if (point.y > lmax.y) {
- lmax.y = point.y;
- }
- });
- return {
- min: lmin,
- max: lmax,
- width: lmax.x - lmin.x,
- height: lmax.y - lmin.y
- };
- };
- return PolygonPoints;
- })();
- var Polygon = (function () {
- function Polygon() {
- }
- Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
- return [
- new BABYLON.Vector2(xmin, ymin),
- new BABYLON.Vector2(xmax, ymin),
- new BABYLON.Vector2(xmax, ymax),
- new BABYLON.Vector2(xmin, ymax)
- ];
- };
- Polygon.Circle = function (radius, cx, cy, numberOfSides) {
- if (cx === void 0) { cx = 0; }
- if (cy === void 0) { cy = 0; }
- if (numberOfSides === void 0) { numberOfSides = 32; }
- var result = new Array();
- var angle = 0;
- var increment = (Math.PI * 2) / numberOfSides;
- for (var i = 0; i < numberOfSides; i++) {
- result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
- angle -= increment;
- }
- return result;
- };
- Polygon.Parse = function (input) {
- var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
- var i, result = [];
- for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
- result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
- }
- return result;
- };
- Polygon.StartingAt = function (x, y) {
- return BABYLON.Path2.StartingAt(x, y);
- };
- return Polygon;
- })();
- BABYLON.Polygon = Polygon;
- var PolygonMeshBuilder = (function () {
- function PolygonMeshBuilder(name, contours, scene) {
- this._points = new PolygonPoints();
- this._outlinepoints = new PolygonPoints();
- this._holes = [];
- if (!("poly2tri" in window)) {
- throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
- }
- this._name = name;
- this._scene = scene;
- var points;
- if (contours instanceof BABYLON.Path2) {
- points = contours.getPoints();
- }
- else {
- points = contours;
- }
- this._swctx = new poly2tri.SweepContext(this._points.add(points));
- this._outlinepoints.add(points);
- }
- PolygonMeshBuilder.prototype.addHole = function (hole) {
- this._swctx.addHole(this._points.add(hole));
- var holepoints = new PolygonPoints();
- holepoints.add(hole);
- this._holes.push(holepoints);
- return this;
- };
- PolygonMeshBuilder.prototype.build = function (updatable, depth) {
- var _this = this;
- if (updatable === void 0) { updatable = false; }
- var result = new BABYLON.Mesh(this._name, this._scene);
- var normals = [];
- var positions = [];
- var uvs = [];
- var bounds = this._points.computeBounds();
- this._points.elements.forEach(function (p) {
- normals.push(0, 1.0, 0);
- positions.push(p.x, 0, p.y);
- uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
- });
- var indices = [];
- this._swctx.triangulate();
- this._swctx.getTriangles().forEach(function (triangle) {
- triangle.getPoints().forEach(function (point) {
- indices.push(point.index);
- });
- });
- if (depth > 0) {
- var positionscount = (positions.length / 3); //get the current pointcount
- this._points.elements.forEach(function (p) {
- normals.push(0, -1.0, 0);
- positions.push(p.x, -depth, p.y);
- uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
- });
- var p1; //we need to change order of point so the triangles are made in the rigth way.
- var p2;
- var poscounter = 0;
- this._swctx.getTriangles().forEach(function (triangle) {
- triangle.getPoints().forEach(function (point) {
- switch (poscounter) {
- case 0:
- p1 = point;
- break;
- case 1:
- p2 = point;
- break;
- case 2:
- indices.push(point.index + positionscount);
- indices.push(p2.index + positionscount);
- indices.push(p1.index + positionscount);
- poscounter = -1;
- break;
- }
- poscounter++;
- //indices.push((<IndexedVector2>point).index + positionscount);
- });
- });
- //Add the sides
- this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
- this._holes.forEach(function (hole) {
- _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
- });
- }
- result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
- result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
- result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
- result.setIndices(indices);
- return result;
- };
- PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
- var StartIndex = positions.length / 3;
- var ulength = 0;
- for (var i = 0; i < points.elements.length; i++) {
- var p = points.elements[i];
- var p1;
- if ((i + 1) > points.elements.length - 1) {
- p1 = points.elements[0];
- }
- else {
- p1 = points.elements[i + 1];
- }
- positions.push(p.x, 0, p.y);
- positions.push(p.x, -depth, p.y);
- positions.push(p1.x, 0, p1.y);
- positions.push(p1.x, -depth, p1.y);
- var v1 = new BABYLON.Vector3(p.x, 0, p.y);
- var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
- var v3 = v2.subtract(v1);
- var v4 = new BABYLON.Vector3(0, 1, 0);
- var vn = BABYLON.Vector3.Cross(v3, v4);
- vn = vn.normalize();
- uvs.push(ulength / bounds.width, 0);
- uvs.push(ulength / bounds.width, 1);
- ulength += v3.length();
- uvs.push((ulength / bounds.width), 0);
- uvs.push((ulength / bounds.width), 1);
- if (!flip) {
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- indices.push(StartIndex);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 3);
- indices.push(StartIndex + 2);
- }
- else {
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- indices.push(StartIndex);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 3);
- }
- StartIndex += 4;
- }
- ;
- };
- return PolygonMeshBuilder;
- })();
- BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Octree = (function () {
- function Octree(creationFunc, maxBlockCapacity, maxDepth) {
- if (maxDepth === void 0) { maxDepth = 2; }
- this.maxDepth = maxDepth;
- this.dynamicContent = new Array();
- this._maxBlockCapacity = maxBlockCapacity || 64;
- this._selectionContent = new BABYLON.SmartArray(1024);
- this._creationFunc = creationFunc;
- }
- // Methods
- Octree.prototype.update = function (worldMin, worldMax, entries) {
- Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
- };
- Octree.prototype.addMesh = function (entry) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.addEntry(entry);
- }
- };
- Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.select(frustumPlanes, this._selectionContent, allowDuplicate);
- }
- if (allowDuplicate) {
- this._selectionContent.concat(this.dynamicContent);
- }
- else {
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- }
- return this._selectionContent;
- };
- Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
- }
- if (allowDuplicate) {
- this._selectionContent.concat(this.dynamicContent);
- }
- else {
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- }
- return this._selectionContent;
- };
- Octree.prototype.intersectsRay = function (ray) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersectsRay(ray, this._selectionContent);
- }
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- return this._selectionContent;
- };
- Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
- target.blocks = new Array();
- var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
- // Segmenting space
- for (var x = 0; x < 2; x++) {
- for (var y = 0; y < 2; y++) {
- for (var z = 0; z < 2; z++) {
- var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
- var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
- var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
- block.addEntries(entries);
- target.blocks.push(block);
- }
- }
- }
- };
- Octree.CreationFuncForMeshes = function (entry, block) {
- if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
- block.entries.push(entry);
- }
- };
- Octree.CreationFuncForSubMeshes = function (entry, block) {
- if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
- block.entries.push(entry);
- }
- };
- return Octree;
- })();
- BABYLON.Octree = Octree;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OctreeBlock = (function () {
- function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
- this.entries = new Array();
- this._boundingVectors = new Array();
- this._capacity = capacity;
- this._depth = depth;
- this._maxDepth = maxDepth;
- this._creationFunc = creationFunc;
- this._minPoint = minPoint;
- this._maxPoint = maxPoint;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[2].x = maxPoint.x;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[3].y = maxPoint.y;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[4].z = maxPoint.z;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[5].z = minPoint.z;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[6].x = minPoint.x;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[7].y = minPoint.y;
- }
- Object.defineProperty(OctreeBlock.prototype, "capacity", {
- // Property
- get: function () {
- return this._capacity;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(OctreeBlock.prototype, "minPoint", {
- get: function () {
- return this._minPoint;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
- get: function () {
- return this._maxPoint;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- OctreeBlock.prototype.addEntry = function (entry) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.addEntry(entry);
- }
- return;
- }
- this._creationFunc(entry, this);
- if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
- this.createInnerBlocks();
- }
- };
- OctreeBlock.prototype.addEntries = function (entries) {
- for (var index = 0; index < entries.length; index++) {
- var mesh = entries[index];
- this.addEntry(mesh);
- }
- };
- OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
- if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.select(frustumPlanes, selection, allowDuplicate);
- }
- return;
- }
- if (allowDuplicate) {
- selection.concat(this.entries);
- }
- else {
- selection.concatWithNoDuplicate(this.entries);
- }
- }
- };
- OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
- if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
- }
- return;
- }
- if (allowDuplicate) {
- selection.concat(this.entries);
- }
- else {
- selection.concatWithNoDuplicate(this.entries);
- }
- }
- };
- OctreeBlock.prototype.intersectsRay = function (ray, selection) {
- if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersectsRay(ray, selection);
- }
- return;
- }
- selection.concatWithNoDuplicate(this.entries);
- }
- };
- OctreeBlock.prototype.createInnerBlocks = function () {
- BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
- };
- return OctreeBlock;
- })();
- BABYLON.OctreeBlock = OctreeBlock;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BlurPostProcess = (function (_super) {
- __extends(BlurPostProcess, _super);
- function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
- this.direction = direction;
- this.blurWidth = blurWidth;
- this.onApply = function (effect) {
- effect.setFloat2("screenSize", _this.width, _this.height);
- effect.setVector2("direction", _this.direction);
- effect.setFloat("blurWidth", _this.blurWidth);
- };
- }
- return BlurPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.BlurPostProcess = BlurPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RefractionPostProcess = (function (_super) {
- __extends(RefractionPostProcess, _super);
- function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
- this.color = color;
- this.depth = depth;
- this.colorLevel = colorLevel;
- this.onActivate = function (cam) {
- _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
- };
- this.onApply = function (effect) {
- effect.setColor3("baseColor", _this.color);
- effect.setFloat("depth", _this.depth);
- effect.setFloat("colorLevel", _this.colorLevel);
- effect.setTexture("refractionSampler", _this._refRexture);
- };
- }
- // Methods
- RefractionPostProcess.prototype.dispose = function (camera) {
- if (this._refRexture) {
- this._refRexture.dispose();
- }
- _super.prototype.dispose.call(this, camera);
- };
- return RefractionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.RefractionPostProcess = RefractionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BlackAndWhitePostProcess = (function (_super) {
- __extends(BlackAndWhitePostProcess, _super);
- function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
- }
- return BlackAndWhitePostProcess;
- })(BABYLON.PostProcess);
- BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ConvolutionPostProcess = (function (_super) {
- __extends(ConvolutionPostProcess, _super);
- function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
- this.kernel = kernel;
- this.onApply = function (effect) {
- effect.setFloat2("screenSize", _this.width, _this.height);
- effect.setArray("kernel", _this.kernel);
- };
- }
- // Statics
- // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
- ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
- ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
- ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
- ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
- ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
- ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
- return ConvolutionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FilterPostProcess = (function (_super) {
- __extends(FilterPostProcess, _super);
- function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
- this.kernelMatrix = kernelMatrix;
- this.onApply = function (effect) {
- effect.setMatrix("kernelMatrix", _this.kernelMatrix);
- };
- }
- return FilterPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.FilterPostProcess = FilterPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FxaaPostProcess = (function (_super) {
- __extends(FxaaPostProcess, _super);
- function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
- this.onSizeChanged = function () {
- _this.texelWidth = 1.0 / _this.width;
- _this.texelHeight = 1.0 / _this.height;
- };
- this.onApply = function (effect) {
- effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
- };
- }
- return FxaaPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.FxaaPostProcess = FxaaPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var StereoscopicInterlacePostProcess = (function (_super) {
- __extends(StereoscopicInterlacePostProcess, _super);
- function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
- var _this = this;
- _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
- this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
- this.onSizeChanged = function () {
- _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
- };
- this.onApply = function (effect) {
- effect.setTextureFromPostProcess("camASampler", postProcessA);
- effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
- };
- }
- return StereoscopicInterlacePostProcess;
- })(BABYLON.PostProcess);
- BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LensFlare = (function () {
- function LensFlare(size, position, color, imgUrl, system) {
- this.size = size;
- this.position = position;
- this.dispose = function () {
- if (this.texture) {
- this.texture.dispose();
- }
- // Remove from scene
- var index = this._system.lensFlares.indexOf(this);
- this._system.lensFlares.splice(index, 1);
- };
- this.color = color || new BABYLON.Color3(1, 1, 1);
- this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
- this._system = system;
- system.lensFlares.push(this);
- }
- return LensFlare;
- })();
- BABYLON.LensFlare = LensFlare;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LensFlareSystem = (function () {
- function LensFlareSystem(name, emitter, scene) {
- this.name = name;
- this.lensFlares = new Array();
- this.borderLimit = 300;
- this.layerMask = 0x0FFFFFFF;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._isEnabled = true;
- this._scene = scene;
- this._emitter = emitter;
- scene.lensFlareSystems.push(this);
- this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- // Effects
- this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
- }
- Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
- get: function () {
- return this._isEnabled;
- },
- set: function (value) {
- this._isEnabled = value;
- },
- enumerable: true,
- configurable: true
- });
- LensFlareSystem.prototype.getScene = function () {
- return this._scene;
- };
- LensFlareSystem.prototype.getEmitter = function () {
- return this._emitter;
- };
- LensFlareSystem.prototype.setEmitter = function (newEmitter) {
- this._emitter = newEmitter;
- };
- LensFlareSystem.prototype.getEmitterPosition = function () {
- return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
- };
- LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
- var position = this.getEmitterPosition();
- position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
- this._positionX = position.x;
- this._positionY = position.y;
- position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
- if (position.z > 0) {
- if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
- if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
- return true;
- }
- }
- return false;
- };
- LensFlareSystem.prototype._isVisible = function () {
- if (!this._isEnabled) {
- return false;
- }
- var emitterPosition = this.getEmitterPosition();
- var direction = emitterPosition.subtract(this._scene.activeCamera.position);
- var distance = direction.length();
- direction.normalize();
- var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
- var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
- return !pickInfo.hit || pickInfo.distance > distance;
- };
- LensFlareSystem.prototype.render = function () {
- if (!this._effect.isReady())
- return false;
- var engine = this._scene.getEngine();
- var viewport = this._scene.activeCamera.viewport;
- var globalViewport = viewport.toScreenGlobal(engine);
- // Position
- if (!this.computeEffectivePosition(globalViewport)) {
- return false;
- }
- // Visibility
- if (!this._isVisible()) {
- return false;
- }
- // Intensity
- var awayX;
- var awayY;
- if (this._positionX < this.borderLimit + globalViewport.x) {
- awayX = this.borderLimit + globalViewport.x - this._positionX;
- }
- else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
- awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
- }
- else {
- awayX = 0;
- }
- if (this._positionY < this.borderLimit + globalViewport.y) {
- awayY = this.borderLimit + globalViewport.y - this._positionY;
- }
- else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
- awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
- }
- else {
- awayY = 0;
- }
- var away = (awayX > awayY) ? awayX : awayY;
- if (away > this.borderLimit) {
- away = this.borderLimit;
- }
- var intensity = 1.0 - (away / this.borderLimit);
- if (intensity < 0) {
- return false;
- }
- if (intensity > 1.0) {
- intensity = 1.0;
- }
- // Position
- var centerX = globalViewport.x + globalViewport.width / 2;
- var centerY = globalViewport.y + globalViewport.height / 2;
- var distX = centerX - this._positionX;
- var distY = centerY - this._positionY;
- // Effects
- engine.enableEffect(this._effect);
- engine.setState(false);
- engine.setDepthBuffer(false);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
- // Flares
- for (var index = 0; index < this.lensFlares.length; index++) {
- var flare = this.lensFlares[index];
- var x = centerX - (distX * flare.position);
- var y = centerY - (distY * flare.position);
- var cw = flare.size;
- var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
- var cx = 2 * (x / globalViewport.width) - 1.0;
- var cy = 1.0 - 2 * (y / globalViewport.height);
- var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
- this._effect.setMatrix("viewportMatrix", viewportMatrix);
- // Texture
- this._effect.setTexture("textureSampler", flare.texture);
- // Color
- this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
- // Draw order
- engine.draw(true, 0, 6);
- }
- engine.setDepthBuffer(true);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- return true;
- };
- LensFlareSystem.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- while (this.lensFlares.length) {
- this.lensFlares[0].dispose();
- }
- // Remove from scene
- var index = this._scene.lensFlareSystems.indexOf(this);
- this._scene.lensFlareSystems.splice(index, 1);
- };
- LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
- var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
- var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
- lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
- for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
- var parsedFlare = parsedLensFlareSystem.flares[index];
- var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
- }
- return lensFlareSystem;
- };
- LensFlareSystem.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.emitterId = this.getEmitter().id;
- serializationObject.borderLimit = this.borderLimit;
- serializationObject.flares = [];
- for (var index = 0; index < this.lensFlares.length; index++) {
- var flare = this.lensFlares[index];
- serializationObject.flares.push({
- size: flare.size,
- position: flare.position,
- color: flare.color.asArray(),
- textureName: BABYLON.Tools.GetFilename(flare.texture.name)
- });
- }
- return serializationObject;
- };
- return LensFlareSystem;
- })();
- BABYLON.LensFlareSystem = LensFlareSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var DeviceOrientationCamera = (function (_super) {
- __extends(DeviceOrientationCamera, _super);
- function DeviceOrientationCamera(name, position, scene) {
- var _this = this;
- _super.call(this, name, position, scene);
- this._offsetX = null;
- this._offsetY = null;
- this._orientationGamma = 0;
- this._orientationBeta = 0;
- this._initialOrientationGamma = 0;
- this._initialOrientationBeta = 0;
- this.angularSensibility = 10000.0;
- this.moveSensibility = 50.0;
- window.addEventListener("resize", function () {
- _this._initialOrientationGamma = null;
- }, false);
- }
- DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
- var _this = this;
- if (this._attachedCanvas) {
- return;
- }
- this._attachedCanvas = canvas;
- if (!this._orientationChanged) {
- this._orientationChanged = function (evt) {
- if (!_this._initialOrientationGamma) {
- _this._initialOrientationGamma = evt.gamma;
- _this._initialOrientationBeta = evt.beta;
- }
- _this._orientationGamma = evt.gamma;
- _this._orientationBeta = evt.beta;
- _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
- _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
- };
- }
- window.addEventListener("deviceorientation", this._orientationChanged);
- };
- DeviceOrientationCamera.prototype.detachControl = function (canvas) {
- if (this._attachedCanvas !== canvas) {
- return;
- }
- window.removeEventListener("deviceorientation", this._orientationChanged);
- this._attachedCanvas = null;
- this._orientationGamma = 0;
- this._orientationBeta = 0;
- this._initialOrientationGamma = 0;
- this._initialOrientationBeta = 0;
- };
- DeviceOrientationCamera.prototype._checkInputs = function () {
- if (!this._offsetX) {
- return;
- }
- this.cameraRotation.y -= this._offsetX / this.angularSensibility;
- var speed = this._computeLocalCameraSpeed();
- var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
- this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
- _super.prototype._checkInputs.call(this);
- };
- return DeviceOrientationCamera;
- })(BABYLON.FreeCamera);
- BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Analyser = (function () {
- function Analyser(scene) {
- this.SMOOTHING = 0.75;
- this.FFT_SIZE = 512;
- this.BARGRAPHAMPLITUDE = 256;
- this.DEBUGCANVASPOS = { x: 20, y: 20 };
- this.DEBUGCANVASSIZE = { width: 320, height: 200 };
- this._scene = scene;
- this._audioEngine = BABYLON.Engine.audioEngine;
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
- this._webAudioAnalyser.minDecibels = -140;
- this._webAudioAnalyser.maxDecibels = 0;
- this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
- this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
- this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
- }
- }
- Analyser.prototype.getFrequencyBinCount = function () {
- if (this._audioEngine.canUseWebAudio) {
- return this._webAudioAnalyser.frequencyBinCount;
- }
- else {
- return 0;
- }
- };
- Analyser.prototype.getByteFrequencyData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
- }
- return this._byteFreqs;
- };
- Analyser.prototype.getByteTimeDomainData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
- }
- return this._byteTime;
- };
- Analyser.prototype.getFloatFrequencyData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
- }
- return this._floatFreqs;
- };
- Analyser.prototype.drawDebugCanvas = function () {
- var _this = this;
- if (this._audioEngine.canUseWebAudio) {
- if (!this._debugCanvas) {
- this._debugCanvas = document.createElement("canvas");
- this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
- this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
- this._debugCanvas.style.position = "absolute";
- this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
- this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
- this._debugCanvasContext = this._debugCanvas.getContext("2d");
- document.body.appendChild(this._debugCanvas);
- this._registerFunc = function () {
- _this.drawDebugCanvas();
- };
- this._scene.registerBeforeRender(this._registerFunc);
- }
- if (this._registerFunc) {
- var workingArray = this.getByteFrequencyData();
- this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
- this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
- // Draw the frequency domain chart.
- for (var i = 0; i < this.getFrequencyBinCount(); i++) {
- var value = workingArray[i];
- var percent = value / this.BARGRAPHAMPLITUDE;
- var height = this.DEBUGCANVASSIZE.height * percent;
- var offset = this.DEBUGCANVASSIZE.height - height - 1;
- var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
- var hue = i / this.getFrequencyBinCount() * 360;
- this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
- this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
- }
- }
- }
- };
- Analyser.prototype.stopDebugCanvas = function () {
- if (this._debugCanvas) {
- this._scene.unregisterBeforeRender(this._registerFunc);
- this._registerFunc = null;
- document.body.removeChild(this._debugCanvas);
- this._debugCanvas = null;
- this._debugCanvasContext = null;
- }
- };
- Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
- if (this._audioEngine.canUseWebAudio) {
- inputAudioNode.connect(this._webAudioAnalyser);
- this._webAudioAnalyser.connect(outputAudioNode);
- }
- };
- Analyser.prototype.dispose = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.disconnect();
- }
- };
- return Analyser;
- })();
- BABYLON.Analyser = Analyser;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AudioEngine = (function () {
- function AudioEngine() {
- this._audioContext = null;
- this._audioContextInitialized = false;
- this.canUseWebAudio = false;
- this.WarnedWebAudioUnsupported = false;
- this.unlocked = false;
- if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
- window.AudioContext = window.AudioContext || window.webkitAudioContext;
- this.canUseWebAudio = true;
- }
- if (/iPad|iPhone|iPod/.test(navigator.platform)) {
- this._unlockiOSaudio();
- }
- else {
- this.unlocked = true;
- }
- }
- Object.defineProperty(AudioEngine.prototype, "audioContext", {
- get: function () {
- if (!this._audioContextInitialized) {
- this._initializeAudioContext();
- }
- return this._audioContext;
- },
- enumerable: true,
- configurable: true
- });
- AudioEngine.prototype._unlockiOSaudio = function () {
- var _this = this;
- var unlockaudio = function () {
- var buffer = _this.audioContext.createBuffer(1, 1, 22050);
- var source = _this.audioContext.createBufferSource();
- source.buffer = buffer;
- source.connect(_this.audioContext.destination);
- source.start(0);
- setTimeout(function () {
- if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
- _this.unlocked = true;
- window.removeEventListener('touchend', unlockaudio, false);
- if (_this.onAudioUnlocked) {
- _this.onAudioUnlocked();
- }
- }
- }, 0);
- };
- window.addEventListener('touchend', unlockaudio, false);
- };
- AudioEngine.prototype._initializeAudioContext = function () {
- try {
- if (this.canUseWebAudio) {
- this._audioContext = new AudioContext();
- // create a global volume gain node
- this.masterGain = this._audioContext.createGain();
- this.masterGain.gain.value = 1;
- this.masterGain.connect(this._audioContext.destination);
- this._audioContextInitialized = true;
- }
- }
- catch (e) {
- this.canUseWebAudio = false;
- BABYLON.Tools.Error("Web Audio: " + e.message);
- }
- };
- AudioEngine.prototype.dispose = function () {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- this._connectedAnalyser.dispose();
- this.masterGain.disconnect();
- this.masterGain.connect(this._audioContext.destination);
- this._connectedAnalyser = null;
- }
- this.masterGain.gain.value = 1;
- }
- this.WarnedWebAudioUnsupported = false;
- };
- AudioEngine.prototype.getGlobalVolume = function () {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- return this.masterGain.gain.value;
- }
- else {
- return -1;
- }
- };
- AudioEngine.prototype.setGlobalVolume = function (newVolume) {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- this.masterGain.gain.value = newVolume;
- }
- };
- AudioEngine.prototype.connectToAnalyser = function (analyser) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- if (this.canUseWebAudio && this._audioContextInitialized) {
- this._connectedAnalyser = analyser;
- this.masterGain.disconnect();
- this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
- }
- };
- return AudioEngine;
- })();
- BABYLON.AudioEngine = AudioEngine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Sound = (function () {
- /**
- * Create a sound and attach it to a scene
- * @param name Name of your sound
- * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
- * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
- * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
- */
- function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
- var _this = this;
- this.autoplay = false;
- this.loop = false;
- this.useCustomAttenuation = false;
- this.spatialSound = false;
- this.refDistance = 1;
- this.rolloffFactor = 1;
- this.maxDistance = 100;
- this.distanceModel = "linear";
- this._panningModel = "equalpower";
- this._playbackRate = 1;
- this._streaming = false;
- this._startTime = 0;
- this._startOffset = 0;
- this._position = BABYLON.Vector3.Zero();
- this._localDirection = new BABYLON.Vector3(1, 0, 0);
- this._volume = 1;
- this._isLoaded = false;
- this._isReadyToPlay = false;
- this.isPlaying = false;
- this.isPaused = false;
- this._isDirectional = false;
- // Used if you'd like to create a directional sound.
- // If not set, the sound will be omnidirectional
- this._coneInnerAngle = 360;
- this._coneOuterAngle = 360;
- this._coneOuterGain = 0;
- this._isOutputConnected = false;
- this.name = name;
- this._scene = scene;
- this._readyToPlayCallback = readyToPlayCallback;
- // Default custom attenuation function is a linear attenuation
- this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
- if (currentDistance < maxDistance) {
- return currentVolume * (1 - currentDistance / maxDistance);
- }
- else {
- return 0;
- }
- };
- if (options) {
- this.autoplay = options.autoplay || false;
- this.loop = options.loop || false;
- // if volume === 0, we need another way to check this option
- if (options.volume !== undefined) {
- this._volume = options.volume;
- }
- this.spatialSound = options.spatialSound || false;
- this.maxDistance = options.maxDistance || 100;
- this.useCustomAttenuation = options.useCustomAttenuation || false;
- this.rolloffFactor = options.rolloffFactor || 1;
- this.refDistance = options.refDistance || 1;
- this.distanceModel = options.distanceModel || "linear";
- this._playbackRate = options.playbackRate || 1;
- this._streaming = options.streaming || false;
- }
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
- this._soundGain.gain.value = this._volume;
- this._inputAudioNode = this._soundGain;
- this._ouputAudioNode = this._soundGain;
- if (this.spatialSound) {
- this._createSpatialParameters();
- }
- this._scene.mainSoundTrack.AddSound(this);
- // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
- if (urlOrArrayBuffer) {
- // If it's an URL
- if (typeof (urlOrArrayBuffer) === "string") {
- // Loading sound using XHR2
- if (!this._streaming) {
- BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
- }
- else {
- this._htmlAudioElement = new Audio(urlOrArrayBuffer);
- this._htmlAudioElement.controls = false;
- this._htmlAudioElement.loop = this.loop;
- this._htmlAudioElement.crossOrigin = "anonymous";
- this._htmlAudioElement.preload = "auto";
- this._htmlAudioElement.addEventListener("canplaythrough", function () {
- _this._isReadyToPlay = true;
- if (_this.autoplay) {
- _this.play();
- }
- if (_this._readyToPlayCallback) {
- _this._readyToPlayCallback();
- }
- });
- document.body.appendChild(this._htmlAudioElement);
- }
- }
- else {
- if (urlOrArrayBuffer instanceof ArrayBuffer) {
- if (urlOrArrayBuffer.byteLength > 0) {
- this._soundLoaded(urlOrArrayBuffer);
- }
- }
- else {
- BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
- }
- }
- }
- }
- else {
- // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
- this._scene.mainSoundTrack.AddSound(this);
- if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
- BABYLON.Tools.Error("Web Audio is not supported by your browser.");
- BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
- }
- // Simulating a ready to play event to avoid breaking code for non web audio browsers
- if (this._readyToPlayCallback) {
- window.setTimeout(function () {
- _this._readyToPlayCallback();
- }, 1000);
- }
- }
- }
- Sound.prototype.dispose = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
- if (this.isPlaying) {
- this.stop();
- }
- this._isReadyToPlay = false;
- if (this.soundTrackId === -1) {
- this._scene.mainSoundTrack.RemoveSound(this);
- }
- else {
- this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
- }
- if (this._soundGain) {
- this._soundGain.disconnect();
- this._soundGain = null;
- }
- if (this._soundPanner) {
- this._soundPanner.disconnect();
- this._soundPanner = null;
- }
- if (this._soundSource) {
- this._soundSource.disconnect();
- this._soundSource = null;
- }
- this._audioBuffer = null;
- if (this._htmlAudioElement) {
- this._htmlAudioElement.pause();
- this._htmlAudioElement.src = "";
- document.body.removeChild(this._htmlAudioElement);
- }
- if (this._connectedMesh) {
- this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
- this._connectedMesh = null;
- }
- }
- };
- Sound.prototype._soundLoaded = function (audioData) {
- var _this = this;
- this._isLoaded = true;
- BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
- _this._audioBuffer = buffer;
- _this._isReadyToPlay = true;
- if (_this.autoplay) {
- _this.play();
- }
- if (_this._readyToPlayCallback) {
- _this._readyToPlayCallback();
- }
- }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
- };
- Sound.prototype.setAudioBuffer = function (audioBuffer) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._audioBuffer = audioBuffer;
- this._isReadyToPlay = true;
- }
- };
- Sound.prototype.updateOptions = function (options) {
- if (options) {
- this.loop = options.loop || this.loop;
- this.maxDistance = options.maxDistance || this.maxDistance;
- this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
- this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
- this.refDistance = options.refDistance || this.refDistance;
- this.distanceModel = options.distanceModel || this.distanceModel;
- this._playbackRate = options.playbackRate || this._playbackRate;
- this._updateSpatialParameters();
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- else {
- this._soundSource.playbackRate.value = this._playbackRate;
- }
- }
- }
- };
- Sound.prototype._createSpatialParameters = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._scene.headphone) {
- this._panningModel = "HRTF";
- }
- this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
- this._updateSpatialParameters();
- this._soundPanner.connect(this._ouputAudioNode);
- this._inputAudioNode = this._soundPanner;
- }
- };
- Sound.prototype._updateSpatialParameters = function () {
- if (this.spatialSound) {
- if (this.useCustomAttenuation) {
- // Tricks to disable in a way embedded Web Audio attenuation
- this._soundPanner.distanceModel = "linear";
- this._soundPanner.maxDistance = Number.MAX_VALUE;
- this._soundPanner.refDistance = 1;
- this._soundPanner.rolloffFactor = 1;
- this._soundPanner.panningModel = this._panningModel;
- }
- else {
- this._soundPanner.distanceModel = this.distanceModel;
- this._soundPanner.maxDistance = this.maxDistance;
- this._soundPanner.refDistance = this.refDistance;
- this._soundPanner.rolloffFactor = this.rolloffFactor;
- this._soundPanner.panningModel = this._panningModel;
- }
- }
- };
- Sound.prototype.switchPanningModelToHRTF = function () {
- this._panningModel = "HRTF";
- this._switchPanningModel();
- };
- Sound.prototype.switchPanningModelToEqualPower = function () {
- this._panningModel = "equalpower";
- this._switchPanningModel();
- };
- Sound.prototype._switchPanningModel = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
- this._soundPanner.panningModel = this._panningModel;
- }
- };
- Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._isOutputConnected) {
- this._ouputAudioNode.disconnect();
- }
- this._ouputAudioNode.connect(soundTrackAudioNode);
- this._isOutputConnected = true;
- }
- };
- /**
- * Transform this sound into a directional source
- * @param coneInnerAngle Size of the inner cone in degree
- * @param coneOuterAngle Size of the outer cone in degree
- * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
- */
- Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
- if (coneOuterAngle < coneInnerAngle) {
- BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
- return;
- }
- this._coneInnerAngle = coneInnerAngle;
- this._coneOuterAngle = coneOuterAngle;
- this._coneOuterGain = coneOuterGain;
- this._isDirectional = true;
- if (this.isPlaying && this.loop) {
- this.stop();
- this.play();
- }
- };
- Sound.prototype.setPosition = function (newPosition) {
- this._position = newPosition;
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
- this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
- }
- };
- Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
- this._localDirection = newLocalDirection;
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
- this._updateDirection();
- }
- };
- Sound.prototype._updateDirection = function () {
- var mat = this._connectedMesh.getWorldMatrix();
- var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
- direction.normalize();
- this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
- };
- Sound.prototype.updateDistanceFromListener = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
- var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
- this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
- }
- };
- Sound.prototype.setAttenuationFunction = function (callback) {
- this._customAttenuationFunction = callback;
- };
- /**
- * Play the sound
- * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
- */
- Sound.prototype.play = function (time) {
- var _this = this;
- if (this._isReadyToPlay && this._scene.audioEnabled) {
- try {
- if (this._startOffset < 0) {
- time = -this._startOffset;
- this._startOffset = 0;
- }
- var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
- if (!this._soundSource || !this._streamingSource) {
- if (this.spatialSound) {
- this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
- if (this._isDirectional) {
- this._soundPanner.coneInnerAngle = this._coneInnerAngle;
- this._soundPanner.coneOuterAngle = this._coneOuterAngle;
- this._soundPanner.coneOuterGain = this._coneOuterGain;
- if (this._connectedMesh) {
- this._updateDirection();
- }
- else {
- this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
- }
- }
- }
- }
- if (this._streaming) {
- if (!this._streamingSource) {
- this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
- this._htmlAudioElement.onended = function () { _this._onended(); };
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- this._streamingSource.disconnect();
- this._streamingSource.connect(this._inputAudioNode);
- this._htmlAudioElement.play();
- }
- else {
- this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
- this._soundSource.buffer = this._audioBuffer;
- this._soundSource.connect(this._inputAudioNode);
- this._soundSource.loop = this.loop;
- this._soundSource.playbackRate.value = this._playbackRate;
- this._soundSource.onended = function () { _this._onended(); };
- this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
- }
- this._startTime = startTime;
- this.isPlaying = true;
- this.isPaused = false;
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
- }
- }
- };
- Sound.prototype._onended = function () {
- this.isPlaying = false;
- if (this.onended) {
- this.onended();
- }
- };
- /**
- * Stop the sound
- * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
- */
- Sound.prototype.stop = function (time) {
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.pause();
- // Test needed for Firefox or it will generate an Invalid State Error
- if (this._htmlAudioElement.currentTime > 0) {
- this._htmlAudioElement.currentTime = 0;
- }
- }
- else {
- var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
- this._soundSource.stop(stopTime);
- if (!this.isPaused) {
- this._startOffset = 0;
- }
- }
- this.isPlaying = false;
- }
- };
- Sound.prototype.pause = function () {
- if (this.isPlaying) {
- this.isPaused = true;
- if (this._streaming) {
- this._htmlAudioElement.pause();
- }
- else {
- this.stop(0);
- this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
- }
- }
- };
- Sound.prototype.setVolume = function (newVolume, time) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (time) {
- this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
- this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
- this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
- }
- else {
- this._soundGain.gain.value = newVolume;
- }
- }
- this._volume = newVolume;
- };
- Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
- this._playbackRate = newPlaybackRate;
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- else {
- this._soundSource.playbackRate.value = this._playbackRate;
- }
- }
- };
- Sound.prototype.getVolume = function () {
- return this._volume;
- };
- Sound.prototype.attachToMesh = function (meshToConnectTo) {
- var _this = this;
- if (this._connectedMesh) {
- this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
- this._registerFunc = null;
- }
- this._connectedMesh = meshToConnectTo;
- if (!this.spatialSound) {
- this.spatialSound = true;
- this._createSpatialParameters();
- if (this.isPlaying && this.loop) {
- this.stop();
- this.play();
- }
- }
- this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
- this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
- meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
- };
- Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
- this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
- this._updateDirection();
- }
- };
- Sound.prototype.clone = function () {
- var _this = this;
- if (!this._streaming) {
- var setBufferAndRun = function () {
- if (_this._isReadyToPlay) {
- clonedSound._audioBuffer = _this.getAudioBuffer();
- clonedSound._isReadyToPlay = true;
- if (clonedSound.autoplay) {
- clonedSound.play();
- }
- }
- else {
- window.setTimeout(setBufferAndRun, 300);
- }
- };
- var currentOptions = {
- autoplay: this.autoplay, loop: this.loop,
- volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
- useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
- refDistance: this.refDistance, distanceModel: this.distanceModel
- };
- var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
- if (this.useCustomAttenuation) {
- clonedSound.setAttenuationFunction(this._customAttenuationFunction);
- }
- clonedSound.setPosition(this._position);
- clonedSound.setPlaybackRate(this._playbackRate);
- setBufferAndRun();
- return clonedSound;
- }
- else {
- return null;
- }
- };
- Sound.prototype.getAudioBuffer = function () {
- return this._audioBuffer;
- };
- Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
- var soundName = parsedSound.name;
- var soundUrl;
- if (parsedSound.url) {
- soundUrl = rootUrl + parsedSound.url;
- }
- else {
- soundUrl = rootUrl + soundName;
- }
- var options = {
- autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
- spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
- rolloffFactor: parsedSound.rolloffFactor,
- refDistance: parsedSound.refDistance,
- distanceModel: parsedSound.distanceModel,
- playbackRate: parsedSound.playbackRate
- };
- var newSound;
- if (!sourceSound) {
- newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
- scene._addPendingData(newSound);
- }
- else {
- var setBufferAndRun = function () {
- if (sourceSound._isReadyToPlay) {
- newSound._audioBuffer = sourceSound.getAudioBuffer();
- newSound._isReadyToPlay = true;
- if (newSound.autoplay) {
- newSound.play();
- }
- }
- else {
- window.setTimeout(setBufferAndRun, 300);
- }
- };
- newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
- setBufferAndRun();
- }
- if (parsedSound.position) {
- var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
- newSound.setPosition(soundPosition);
- }
- if (parsedSound.isDirectional) {
- newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
- if (parsedSound.localDirectionToMesh) {
- var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
- newSound.setLocalDirectionToMesh(localDirectionToMesh);
- }
- }
- if (parsedSound.connectedMeshId) {
- var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
- if (connectedMesh) {
- newSound.attachToMesh(connectedMesh);
- }
- }
- return newSound;
- };
- return Sound;
- })();
- BABYLON.Sound = Sound;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SoundTrack = (function () {
- function SoundTrack(scene, options) {
- this.id = -1;
- this._isMainTrack = false;
- this._isInitialized = false;
- this._scene = scene;
- this.soundCollection = new Array();
- this._options = options;
- if (!this._isMainTrack) {
- this._scene.soundTracks.push(this);
- this.id = this._scene.soundTracks.length - 1;
- }
- }
- SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
- this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
- if (this._options) {
- if (this._options.volume) {
- this._outputAudioNode.gain.value = this._options.volume;
- }
- if (this._options.mainTrack) {
- this._isMainTrack = this._options.mainTrack;
- }
- }
- this._isInitialized = true;
- }
- };
- SoundTrack.prototype.dispose = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- while (this.soundCollection.length) {
- this.soundCollection[0].dispose();
- }
- if (this._outputAudioNode) {
- this._outputAudioNode.disconnect();
- }
- this._outputAudioNode = null;
- }
- };
- SoundTrack.prototype.AddSound = function (sound) {
- if (!this._isInitialized) {
- this._initializeSoundTrackAudioGraph();
- }
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- sound.connectToSoundTrackAudioNode(this._outputAudioNode);
- }
- if (sound.soundTrackId) {
- if (sound.soundTrackId === -1) {
- this._scene.mainSoundTrack.RemoveSound(sound);
- }
- else {
- this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
- }
- }
- this.soundCollection.push(sound);
- sound.soundTrackId = this.id;
- };
- SoundTrack.prototype.RemoveSound = function (sound) {
- var index = this.soundCollection.indexOf(sound);
- if (index !== -1) {
- this.soundCollection.splice(index, 1);
- }
- };
- SoundTrack.prototype.setVolume = function (newVolume) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode.gain.value = newVolume;
- }
- };
- SoundTrack.prototype.switchPanningModelToHRTF = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- for (var i = 0; i < this.soundCollection.length; i++) {
- this.soundCollection[i].switchPanningModelToHRTF();
- }
- }
- };
- SoundTrack.prototype.switchPanningModelToEqualPower = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- for (var i = 0; i < this.soundCollection.length; i++) {
- this.soundCollection[i].switchPanningModelToEqualPower();
- }
- }
- };
- SoundTrack.prototype.connectToAnalyser = function (analyser) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- this._connectedAnalyser = analyser;
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode.disconnect();
- this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
- }
- };
- return SoundTrack;
- })();
- BABYLON.SoundTrack = SoundTrack;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DepthRenderer = (function () {
- function DepthRenderer(scene, type) {
- var _this = this;
- if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._projectionMatrix = BABYLON.Matrix.Zero();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._worldViewProjection = BABYLON.Matrix.Zero();
- this._scene = scene;
- var engine = scene.getEngine();
- // Render target
- this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
- this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._depthMap.refreshRate = 1;
- this._depthMap.renderParticles = false;
- this._depthMap.renderList = null;
- // set default depth value to 1.0 (far away)
- this._depthMap.onClear = function (engine) {
- engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
- };
- // Custom render function
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- var scene = _this._scene;
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(_this._effect);
- mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
- var material = subMesh.getMaterial();
- _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- _this._effect.setFloat("far", scene.activeCamera.maxZ);
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- _this._effect.setTexture("diffuseSampler", alphaTexture);
- _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- // Draw
- mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
- }
- };
- this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- };
- }
- DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var mesh = subMesh.getMesh();
- var scene = mesh.getScene();
- var material = subMesh.getMaterial();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- DepthRenderer.prototype.getDepthMap = function () {
- return this._depthMap;
- };
- // Methods
- DepthRenderer.prototype.dispose = function () {
- this._depthMap.dispose();
- };
- return DepthRenderer;
- })();
- BABYLON.DepthRenderer = DepthRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SSAORenderingPipeline = (function (_super) {
- __extends(SSAORenderingPipeline, _super);
- /**
- * @constructor
- * @param {string} name - The rendering pipeline name
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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 }
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function SSAORenderingPipeline(name, scene, ratio, cameras) {
- var _this = this;
- _super.call(this, scene.getEngine(), name);
- // Members
- /**
- * The PassPostProcess id in the pipeline that contains the original scene color
- * @type {string}
- */
- this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
- /**
- * The SSAO PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAORenderEffect = "SSAORenderEffect";
- /**
- * The horizontal blur PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
- /**
- * The vertical blur PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
- /**
- * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
- * @type {string}
- */
- this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
- /**
- * The output strength of the SSAO post-process. Default value is 1.0.
- * @type {number}
- */
- this.totalStrength = 1.0;
- /**
- * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
- * @type {number}
- */
- this.radius = 0.0001;
- /**
- * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
- * Must not be equal to fallOff and superior to fallOff.
- * Default value is 0.975
- * @type {number}
- */
- this.area = 0.0075;
- /**
- * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
- * Must not be equal to area and inferior to area.
- * Default value is 0.0
- * @type {number}
- */
- this.fallOff = 0.000001;
- /**
- * The base color of the SSAO post-process
- * The final result is "base + ssao" between [0, 1]
- * @type {number}
- */
- this.base = 0.5;
- this._firstUpdate = true;
- this._scene = scene;
- // Set up assets
- this._createRandomTexture();
- this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
- var ssaoRatio = ratio.ssaoRatio || ratio;
- var combineRatio = ratio.combineRatio || ratio;
- this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._createSSAOPostProcess(ssaoRatio);
- this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._createSSAOCombinePostProcess(combineRatio);
- // Set up pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras)
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- // Public Methods
- /**
- * Returns the horizontal blur PostProcess
- * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
- */
- SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
- return this._blurHPostProcess;
- };
- /**
- * Returns the vertical blur PostProcess
- * @return {BABYLON.BlurPostProcess} The vertical blur post-process
- */
- SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
- return this._blurVPostProcess;
- };
- /**
- * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
- */
- SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
- if (disableDepthRender === void 0) { disableDepthRender = false; }
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- this._originalColorPostProcess = undefined;
- this._ssaoPostProcess = undefined;
- this._blurHPostProcess = undefined;
- this._blurVPostProcess = undefined;
- this._ssaoCombinePostProcess = undefined;
- this._randomTexture.dispose();
- if (disableDepthRender)
- this._scene.disableDepthRenderer();
- };
- // Private Methods
- SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
- var _this = this;
- var numSamples = 16;
- var sampleSphere = [
- 0.5381, 0.1856, -0.4319,
- 0.1379, 0.2486, 0.4430,
- 0.3371, 0.5679, -0.0057,
- -0.6999, -0.0451, -0.0019,
- 0.0689, -0.1598, -0.8547,
- 0.0560, 0.0069, -0.1843,
- -0.0146, 0.1402, 0.0762,
- 0.0100, -0.1924, -0.0344,
- -0.3577, -0.5301, -0.4358,
- -0.3169, 0.1063, 0.0158,
- 0.0103, -0.5869, 0.0046,
- -0.0897, -0.4940, 0.3287,
- 0.7119, -0.0154, -0.0918,
- -0.0533, 0.0596, -0.5411,
- 0.0352, -0.0631, 0.5460,
- -0.4776, 0.2847, -0.0271
- ];
- var samplesFactor = 1.0 / numSamples;
- this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
- "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
- "area", "fallOff", "base"
- ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
- this._ssaoPostProcess.onApply = function (effect) {
- if (_this._firstUpdate) {
- effect.setArray3("sampleSphere", sampleSphere);
- effect.setFloat("samplesFactor", samplesFactor);
- effect.setFloat("randTextureTiles", 4.0);
- _this._firstUpdate = false;
- }
- effect.setFloat("totalStrength", _this.totalStrength);
- effect.setFloat("radius", _this.radius);
- effect.setFloat("area", _this.area);
- effect.setFloat("fallOff", _this.fallOff);
- effect.setFloat("base", _this.base);
- effect.setTexture("textureSampler", _this._depthTexture);
- effect.setTexture("randomSampler", _this._randomTexture);
- };
- };
- SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
- var _this = this;
- this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._ssaoCombinePostProcess.onApply = function (effect) {
- effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
- };
- };
- SSAORenderingPipeline.prototype._createRandomTexture = function () {
- var size = 512;
- this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- var context = this._randomTexture.getContext();
- var rand = function (min, max) {
- return Math.random() * (max - min) + min;
- };
- var randVector = BABYLON.Vector3.Zero();
- for (var x = 0; x < size; x++) {
- for (var y = 0; y < size; y++) {
- randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
- randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
- randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
- context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
- context.fillRect(x, y, 1, 1);
- }
- }
- this._randomTexture.update(false);
- };
- return SSAORenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
- var VolumetricLightScatteringPostProcess = (function (_super) {
- __extends(VolumetricLightScatteringPostProcess, _super);
- /**
- * @constructor
- * @param {string} name - The post-process name
- * @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)
- * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
- * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
- * @param {number} samples - The post-process quality, default 100
- * @param {number} samplingMode - The post-process filtering mode
- * @param {BABYLON.Engine} engine - The babylon engine
- * @param {boolean} reusable - If the post-process is reusable
- * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
- */
- function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
- var _this = this;
- if (samples === void 0) { samples = 100; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
- this._screenCoordinates = BABYLON.Vector2.Zero();
- /**
- * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
- * @type {boolean}
- */
- this.useCustomMeshPosition = false;
- /**
- * If the post-process should inverse the light scattering direction
- * @type {boolean}
- */
- this.invert = true;
- /**
- * Set to true to use the diffuseColor instead of the diffuseTexture
- * @type {boolean}
- */
- this.useDiffuseColor = false;
- /**
- * Array containing the excluded meshes not rendered in the internal pass
- */
- this.excludedMeshes = new Array();
- /**
- * Controls the overall intensity of the post-process
- * @type {number}
- */
- this.exposure = 0.3;
- /**
- * Dissipates each sample's contribution in range [0, 1]
- * @type {number}
- */
- this.decay = 0.96815;
- /**
- * Controls the overall intensity of each sample
- * @type {number}
- */
- this.weight = 0.58767;
- /**
- * Controls the density of each sample
- * @type {number}
- */
- this.density = 0.926;
- scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
- this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
- // Configure mesh
- this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
- // Configure
- this._createPass(scene, ratio.passRatio || ratio);
- this.onActivate = function (camera) {
- if (!_this.isSupported) {
- _this.dispose(camera);
- }
- _this.onActivate = null;
- };
- this.onApply = function (effect) {
- _this._updateMeshScreenCoordinates(scene);
- effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
- effect.setFloat("exposure", _this.exposure);
- effect.setFloat("decay", _this.decay);
- effect.setFloat("weight", _this.weight);
- effect.setFloat("density", _this.density);
- effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
- };
- }
- VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
- var mesh = subMesh.getMesh();
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var material = subMesh.getMaterial();
- var needUV = false;
- // Render this.mesh as default
- if (mesh === this.mesh) {
- if (this.useDiffuseColor) {
- defines.push("#define DIFFUSE_COLOR_RENDER");
- }
- else if (material) {
- if (material.diffuseTexture !== undefined) {
- defines.push("#define BASIC_RENDER");
- }
- else {
- defines.push("#define DIFFUSE_COLOR_RENDER");
- }
- }
- defines.push("#define NEED_UV");
- needUV = true;
- }
- // Alpha test
- if (material) {
- if (material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- }
- if (material.opacityTexture !== undefined) {
- defines.push("#define OPACITY");
- if (material.opacityTexture.getAlphaFromRGB) {
- defines.push("#define OPACITYRGB");
- }
- if (!needUV) {
- defines.push("#define NEED_UV");
- }
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
- }
- return this._volumetricLightScatteringPass.isReady();
- };
- /**
- * Sets the new light position for light scattering effect
- * @param {BABYLON.Vector3} The new custom light position
- */
- VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
- this._customMeshPosition = position;
- };
- /**
- * Returns the light position for light scattering effect
- * @return {BABYLON.Vector3} The custom light position
- */
- VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
- return this._customMeshPosition;
- };
- /**
- * Disposes the internal assets and detaches the post-process from the camera
- */
- VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
- var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
- if (rttIndex !== -1) {
- camera.getScene().customRenderTargets.splice(rttIndex, 1);
- }
- this._volumetricLightScatteringRTT.dispose();
- _super.prototype.dispose.call(this, camera);
- };
- /**
- * Returns the render target texture used by the post-process
- * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
- */
- VolumetricLightScatteringPostProcess.prototype.getPass = function () {
- return this._volumetricLightScatteringRTT;
- };
- // Private methods
- VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
- if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
- return true;
- }
- return false;
- };
- VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
- var _this = this;
- var engine = scene.getEngine();
- this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
- this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.renderList = null;
- this._volumetricLightScatteringRTT.renderParticles = false;
- scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
- // Custom render function for submeshes
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- if (_this._meshExcluded(mesh)) {
- return;
- }
- var scene = mesh.getScene();
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(_this._volumetricLightScatteringPass);
- mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
- var material = subMesh.getMaterial();
- _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
- // Alpha test
- if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
- var alphaTexture = material.getAlphaTestTexture();
- if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
- _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
- }
- if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
- _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
- if (alphaTexture) {
- _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- }
- if (material.opacityTexture !== undefined) {
- _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
- _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- // Draw
- mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
- }
- };
- // Render target texture callbacks
- var savedSceneClearColor;
- var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
- this._volumetricLightScatteringRTT.onBeforeRender = function () {
- savedSceneClearColor = scene.clearColor;
- scene.clearColor = sceneClearColor;
- };
- this._volumetricLightScatteringRTT.onAfterRender = function () {
- scene.clearColor = savedSceneClearColor;
- };
- this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
- var engine = scene.getEngine();
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- engine.setAlphaTesting(true);
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- engine.setAlphaTesting(false);
- if (transparentSubMeshes.length) {
- // Sort sub meshes
- for (index = 0; index < transparentSubMeshes.length; index++) {
- var submesh = transparentSubMeshes.data[index];
- submesh._alphaIndex = submesh.getMesh().alphaIndex;
- submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
- }
- var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
- sortedArray.sort(function (a, b) {
- // Alpha index first
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- });
- // Render sub meshes
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- for (index = 0; index < sortedArray.length; index++) {
- renderSubMesh(sortedArray[index]);
- }
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- };
- };
- VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
- var transform = scene.getTransformMatrix();
- var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
- var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
- this._screenCoordinates.x = pos.x / this._viewPort.width;
- this._screenCoordinates.y = pos.y / this._viewPort.height;
- if (this.invert)
- this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
- };
- // Static methods
- /**
- * Creates a default mesh for the Volumeric Light Scattering post-process
- * @param {string} The mesh name
- * @param {BABYLON.Scene} The scene where to create the mesh
- * @return {BABYLON.Mesh} the default mesh
- */
- VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
- var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
- mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
- mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
- return mesh;
- };
- return VolumetricLightScatteringPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
- })(BABYLON || (BABYLON = {}));
- // BABYLON.JS Chromatic Aberration GLSL Shader
- // Author: Olivier Guyot
- // Separates very slightly R, G and B colors on the edges of the screen
- // Inspired by Francois Tarlier & Martins Upitis
- var BABYLON;
- (function (BABYLON) {
- var LensRenderingPipeline = (function (_super) {
- __extends(LensRenderingPipeline, _super);
- /**
- * @constructor
- *
- * Effect parameters are as follow:
- * {
- * chromatic_aberration: number; // from 0 to x (1 for realism)
- * edge_blur: number; // from 0 to x (1 for realism)
- * distortion: number; // from 0 to x (1 for realism)
- * grain_amount: number; // from 0 to 1
- * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
- * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
- * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
- * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
- * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
- * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
- * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
- * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
- * }
- * Note: if an effect parameter is unset, effect is disabled
- *
- * @param {string} name - The rendering pipeline name
- * @param {object} parameters - An object containing all parameters (see above)
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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)
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
- var _this = this;
- if (ratio === void 0) { ratio = 1.0; }
- _super.call(this, scene.getEngine(), name);
- // Lens effects can be of the following:
- // - chromatic aberration (slight shift of RGB colors)
- // - blur on the edge of the lens
- // - lens distortion
- // - depth-of-field blur & highlights enhancing
- // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
- // - grain effect (noise or custom texture)
- // Two additional texture samplers are needed:
- // - depth map (for depth-of-field)
- // - grain texture
- /**
- * The chromatic aberration PostProcess id in the pipeline
- * @type {string}
- */
- this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
- /**
- * The highlights enhancing PostProcess id in the pipeline
- * @type {string}
- */
- this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
- /**
- * The depth-of-field PostProcess id in the pipeline
- * @type {string}
- */
- this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
- this._scene = scene;
- // Fetch texture samplers
- this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
- if (parameters.grain_texture) {
- this._grainTexture = parameters.grain_texture;
- }
- else {
- this._createGrainTexture();
- }
- // save parameters
- this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
- this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
- this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
- this._distortion = parameters.distortion ? parameters.distortion : 0;
- this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
- this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
- this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
- this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
- this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
- this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
- this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
- // Create effects
- this._createChromaticAberrationPostProcess(ratio);
- this._createHighlightsPostProcess(ratio);
- this._createDepthOfFieldPostProcess(ratio / 4);
- // Set up pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
- if (this._highlightsGain === -1) {
- this._disableEffect(this.HighlightsEnhancingEffect, null);
- }
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras) {
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- }
- // public methods (self explanatory)
- LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
- LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
- LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
- LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
- LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
- LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
- LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
- LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
- LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
- LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
- LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
- LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
- LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
- this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
- };
- LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
- this._highlightsPostProcess.updateEffect();
- };
- LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
- LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
- LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
- this._highlightsGain = amount;
- };
- LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
- if (this._highlightsGain === -1) {
- this._highlightsGain = 1.0;
- }
- this._highlightsThreshold = amount;
- };
- LensRenderingPipeline.prototype.disableHighlights = function () {
- this._highlightsGain = -1;
- };
- /**
- * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
- */
- LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
- if (disableDepthRender === void 0) { disableDepthRender = false; }
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- this._chromaticAberrationPostProcess = undefined;
- this._highlightsPostProcess = undefined;
- this._depthOfFieldPostProcess = undefined;
- this._grainTexture.dispose();
- if (disableDepthRender)
- this._scene.disableDepthRenderer();
- };
- // colors shifting and distortion
- LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
- var _this = this;
- this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
- [], // samplers
- ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._chromaticAberrationPostProcess.onApply = function (effect) {
- effect.setFloat('chromatic_aberration', _this._chromaticAberration);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- };
- };
- // highlights enhancing
- LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
- var _this = this;
- this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
- [], // samplers
- ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
- this._highlightsPostProcess.onApply = function (effect) {
- effect.setFloat('gain', _this._highlightsGain);
- effect.setFloat('threshold', _this._highlightsThreshold);
- effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- };
- };
- // colors shifting and distortion
- LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
- var _this = this;
- this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
- "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
- "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
- ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._depthOfFieldPostProcess.onApply = function (effect) {
- effect.setTexture("depthSampler", _this._depthTexture);
- effect.setTexture("grainSampler", _this._grainTexture);
- effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
- effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
- effect.setFloat('grain_amount', _this._grainAmount);
- effect.setBool('blur_noise', _this._blurNoise);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- effect.setFloat('distortion', _this._distortion);
- effect.setBool('dof_enabled', (_this._dofDistance !== -1));
- effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
- effect.setFloat('aperture', _this._dofAperture);
- effect.setFloat('darken', _this._dofDarken);
- effect.setFloat('edge_blur', _this._edgeBlur);
- effect.setBool('highlights', (_this._highlightsGain !== -1));
- effect.setFloat('near', _this._scene.activeCamera.minZ);
- effect.setFloat('far', _this._scene.activeCamera.maxZ);
- };
- };
- // creates a black and white random noise texture, 512x512
- LensRenderingPipeline.prototype._createGrainTexture = function () {
- var size = 512;
- this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- var context = this._grainTexture.getContext();
- var rand = function (min, max) {
- return Math.random() * (max - min) + min;
- };
- var value;
- for (var x = 0; x < size; x++) {
- for (var y = 0; y < size; y++) {
- value = Math.floor(rand(0.42, 0.58) * 255);
- context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
- context.fillRect(x, y, 1, 1);
- }
- }
- this._grainTexture.update(false);
- };
- return LensRenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.LensRenderingPipeline = LensRenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- //
- // This post-process allows the modification of rendered colors by using
- // a 'look-up table' (LUT). This effect is also called Color Grading.
- //
- // The object needs to be provided an url to a texture containing the color
- // look-up table: the texture must be 256 pixels wide and 16 pixels high.
- // Use an image editing software to tweak the LUT to match your needs.
- //
- // For an example of a color LUT, see here:
- // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
- // For explanations on color grading, see here:
- // http://udn.epicgames.com/Three/ColorGrading.html
- //
- var BABYLON;
- (function (BABYLON) {
- var ColorCorrectionPostProcess = (function (_super) {
- __extends(ColorCorrectionPostProcess, _super);
- function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
- this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
- this._colorTableTexture.anisotropicFilteringLevel = 1;
- this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.onApply = function (effect) {
- effect.setTexture("colorTable", _this._colorTableTexture);
- };
- }
- return ColorCorrectionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var HDRRenderingPipeline = (function (_super) {
- __extends(HDRRenderingPipeline, _super);
- /**
- * @constructor
- * @param {string} name - The rendering pipeline name
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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)
- * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
- var _this = this;
- if (originalPostProcess === void 0) { originalPostProcess = null; }
- _super.call(this, scene.getEngine(), name);
- /**
- * Public members
- */
- // Gaussian Blur
- /**
- * Gaussian blur coefficient
- * @type {number}
- */
- this.gaussCoeff = 0.3;
- /**
- * Gaussian blur mean
- * @type {number}
- */
- this.gaussMean = 1.0;
- /**
- * Gaussian blur standard deviation
- * @type {number}
- */
- this.gaussStandDev = 0.8;
- /**
- * Gaussian blur multiplier. Multiplies the blur effect
- * @type {number}
- */
- this.gaussMultiplier = 4.0;
- // HDR
- /**
- * Exposure, controls the overall intensity of the pipeline
- * @type {number}
- */
- this.exposure = 1.0;
- /**
- * Minimum luminance that the post-process can output. Luminance is >= 0
- * @type {number}
- */
- this.minimumLuminance = 1.0;
- /**
- * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
- * @type {number}
- */
- this.maximumLuminance = 1e20;
- /**
- * Increase rate for luminance: eye adaptation speed to dark
- * @type {number}
- */
- this.luminanceIncreaserate = 0.5;
- /**
- * Decrease rate for luminance: eye adaptation speed to bright
- * @type {number}
- */
- this.luminanceDecreaseRate = 0.5;
- // Bright pass
- /**
- * Minimum luminance needed to compute HDR
- * @type {number}
- */
- this.brightThreshold = 0.8;
- this._needUpdate = true;
- this._scene = scene;
- // Bright pass
- this._createBrightPassPostProcess(scene, ratio);
- // Down sample X4
- this._createDownSampleX4PostProcess(scene, ratio);
- // Create gaussian blur post-processes
- this._createGaussianBlurPostProcess(scene, ratio);
- // Texture adder
- this._createTextureAdderPostProcess(scene, ratio);
- // Luminance generator
- this._createLuminanceGeneratorPostProcess(scene);
- // HDR
- this._createHDRPostProcess(scene, ratio);
- // Pass postprocess
- if (originalPostProcess === null) {
- this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- }
- else {
- this._originalPostProcess = originalPostProcess;
- }
- // Configure pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
- var addDownSamplerPostProcess = function (id) {
- _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
- };
- for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
- addDownSamplerPostProcess(i);
- }
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras !== null) {
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- this.update();
- }
- /**
- * Tells the pipeline to update its post-processes
- */
- HDRRenderingPipeline.prototype.update = function () {
- this._needUpdate = true;
- };
- /**
- * Returns the current calculated luminance
- */
- HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
- return this._hdrCurrentLuminance;
- };
- /**
- * Returns the currently drawn luminance
- */
- HDRRenderingPipeline.prototype.getOutputLuminance = function () {
- return this._hdrOutputLuminance;
- };
- /**
- * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
- */
- HDRRenderingPipeline.prototype.dispose = function () {
- this._originalPostProcess = undefined;
- this._brightPassPostProcess = undefined;
- this._downSampleX4PostProcess = undefined;
- this._guassianBlurHPostProcess = undefined;
- this._guassianBlurVPostProcess = undefined;
- this._textureAdderPostProcess = undefined;
- for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
- this._downSamplePostProcesses[i] = undefined;
- }
- this._hdrPostProcess = undefined;
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- };
- /**
- * Creates the HDR post-process and computes the luminance adaptation
- */
- HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
- var _this = this;
- var hdrLastLuminance = 0.0;
- this._hdrOutputLuminance = -1.0;
- this._hdrCurrentLuminance = 1.0;
- this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
- this._hdrPostProcess.onApply = function (effect) {
- if (_this._hdrOutputLuminance < 0.0) {
- _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
- }
- else {
- var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
- if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
- _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
- }
- else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
- _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
- }
- else {
- _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
- }
- }
- _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
- hdrLastLuminance += scene.getEngine().getDeltaTime();
- effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
- effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
- effect.setFloat("exposure", _this.exposure);
- effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
- _this._needUpdate = false;
- };
- };
- /**
- * Texture Adder post-process
- */
- HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
- var _this = this;
- this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
- this._textureAdderPostProcess.onApply = function (effect) {
- effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
- };
- };
- /**
- * Down sample X4 post-process
- */
- HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
- var _this = this;
- var downSampleX4Offsets = new Array(32);
- this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
- this._downSampleX4PostProcess.onApply = function (effect) {
- if (_this._needUpdate) {
- var id = 0;
- for (var i = -2; i < 2; i++) {
- for (var j = -2; j < 2; j++) {
- downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
- downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
- id += 2;
- }
- }
- }
- effect.setArray2("dsOffsets", downSampleX4Offsets);
- };
- };
- /**
- * Bright pass post-process
- */
- HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
- var _this = this;
- var brightOffsets = new Array(8);
- var brightPassCallback = function (effect) {
- if (_this._needUpdate) {
- var sU = (1.0 / _this._brightPassPostProcess.width);
- var sV = (1.0 / _this._brightPassPostProcess.height);
- brightOffsets[0] = -0.5 * sU;
- brightOffsets[1] = 0.5 * sV;
- brightOffsets[2] = 0.5 * sU;
- brightOffsets[3] = 0.5 * sV;
- brightOffsets[4] = -0.5 * sU;
- brightOffsets[5] = -0.5 * sV;
- brightOffsets[6] = 0.5 * sU;
- brightOffsets[7] = -0.5 * sV;
- }
- effect.setArray2("dsOffsets", brightOffsets);
- effect.setFloat("brightThreshold", _this.brightThreshold);
- };
- this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
- this._brightPassPostProcess.onApply = brightPassCallback;
- };
- /**
- * Luminance generator. Creates the luminance post-process and down sample post-processes
- */
- HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
- var _this = this;
- var lumSteps = HDRRenderingPipeline.LUM_STEPS;
- var luminanceOffsets = new Array(8);
- var downSampleOffsets = new Array(18);
- var halfDestPixelSize;
- this._downSamplePostProcesses = new Array(lumSteps);
- // Utils for luminance
- var luminanceUpdateSourceOffsets = function (width, height) {
- var sU = (1.0 / width);
- var sV = (1.0 / height);
- luminanceOffsets[0] = -0.5 * sU;
- luminanceOffsets[1] = 0.5 * sV;
- luminanceOffsets[2] = 0.5 * sU;
- luminanceOffsets[3] = 0.5 * sV;
- luminanceOffsets[4] = -0.5 * sU;
- luminanceOffsets[5] = -0.5 * sV;
- luminanceOffsets[6] = 0.5 * sU;
- luminanceOffsets[7] = -0.5 * sV;
- };
- var luminanceUpdateDestOffsets = function (width, height) {
- var id = 0;
- for (var x = -1; x < 2; x++) {
- for (var y = -1; y < 2; y++) {
- downSampleOffsets[id] = (x) / width;
- downSampleOffsets[id + 1] = (y) / height;
- id += 2;
- }
- }
- };
- // Luminance callback
- var luminanceCallback = function (effect) {
- if (_this._needUpdate) {
- luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
- }
- effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
- effect.setArray2("lumOffsets", luminanceOffsets);
- };
- // Down sample callbacks
- var downSampleCallback = function (indice) {
- var i = indice;
- return function (effect) {
- luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
- luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
- halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
- effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
- effect.setFloat("halfDestPixelSize", halfDestPixelSize);
- effect.setArray2("dsOffsets", downSampleOffsets);
- };
- };
- var downSampleAfterRenderCallback = function (effect) {
- // Unpack result
- var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
- 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);
- _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
- };
- // Create luminance post-process
- var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
- this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
- this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
- // Create down sample post-processes
- for (var i = lumSteps - 2; i >= 0; i--) {
- var length = Math.pow(3, i);
- ratio = { width: length, height: length };
- var defines = "#define DOWN_SAMPLE\n";
- if (i === 0) {
- defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
- }
- this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
- this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
- if (i === 0) {
- this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
- }
- }
- };
- /**
- * Gaussian blur post-processes. Horizontal and Vertical
- */
- HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
- var _this = this;
- var blurOffsetsW = new Array(9);
- var blurOffsetsH = new Array(9);
- var blurWeights = new Array(9);
- var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
- // Utils for gaussian blur
- var calculateBlurOffsets = function (height) {
- var lastOutputDimensions = {
- width: scene.getEngine().getRenderWidth(),
- height: scene.getEngine().getRenderHeight()
- };
- for (var i = 0; i < 9; i++) {
- var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
- if (height) {
- blurOffsetsH[i] = value;
- }
- else {
- blurOffsetsW[i] = value;
- }
- }
- };
- var calculateWeights = function () {
- var x = 0.0;
- for (var i = 0; i < 9; i++) {
- x = (i - 4.0) / 4.0;
- blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
- }
- };
- // Callback
- var gaussianBlurCallback = function (height) {
- return function (effect) {
- if (_this._needUpdate) {
- calculateWeights();
- calculateBlurOffsets(height);
- }
- effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
- effect.setArray("blurWeights", blurWeights);
- effect.setFloat("multiplier", _this.gaussMultiplier);
- };
- };
- // Create horizontal gaussian blur post-processes
- this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
- this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
- // Create vertical gaussian blur post-process
- this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
- this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
- };
- // Luminance generator
- HDRRenderingPipeline.LUM_STEPS = 6;
- return HDRRenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FaceAdjacencies = (function () {
- function FaceAdjacencies() {
- this.edges = new Array();
- this.edgesConnectedCount = 0;
- }
- return FaceAdjacencies;
- })();
- var EdgesRenderer = (function () {
- // Beware when you use this class with complex objects as the adjacencies computation can be really long
- function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
- if (epsilon === void 0) { epsilon = 0.95; }
- if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
- this.edgesWidthScalerForOrthographic = 1000.0;
- this.edgesWidthScalerForPerspective = 50.0;
- this._linesPositions = new Array();
- this._linesNormals = new Array();
- this._linesIndices = new Array();
- this._buffers = new Array();
- this._checkVerticesInsteadOfIndices = false;
- this._source = source;
- this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
- this._epsilon = epsilon;
- this._prepareRessources();
- this._generateEdgesLines();
- }
- EdgesRenderer.prototype._prepareRessources = function () {
- if (this._lineShader) {
- return;
- }
- this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
- attributes: ["position", "normal"],
- uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
- });
- this._lineShader.disableDepthWrite = true;
- this._lineShader.backFaceCulling = false;
- };
- EdgesRenderer.prototype.dispose = function () {
- this._vb0.dispose();
- this._vb1.dispose();
- this._source.getScene().getEngine()._releaseBuffer(this._ib);
- this._lineShader.dispose();
- };
- EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
- if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
- return 0;
- }
- if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
- return 1;
- }
- if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
- return 2;
- }
- return -1;
- };
- EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
- if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
- return 0;
- }
- if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
- return 1;
- }
- if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
- return 2;
- }
- return -1;
- };
- EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
- var needToCreateLine;
- if (edge === undefined) {
- needToCreateLine = true;
- }
- else {
- var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
- needToCreateLine = dotProduct < this._epsilon;
- }
- if (needToCreateLine) {
- var offset = this._linesPositions.length / 3;
- var normal = p0.subtract(p1);
- normal.normalize();
- // Positions
- this._linesPositions.push(p0.x);
- this._linesPositions.push(p0.y);
- this._linesPositions.push(p0.z);
- this._linesPositions.push(p0.x);
- this._linesPositions.push(p0.y);
- this._linesPositions.push(p0.z);
- this._linesPositions.push(p1.x);
- this._linesPositions.push(p1.y);
- this._linesPositions.push(p1.z);
- this._linesPositions.push(p1.x);
- this._linesPositions.push(p1.y);
- this._linesPositions.push(p1.z);
- // Normals
- this._linesNormals.push(p1.x);
- this._linesNormals.push(p1.y);
- this._linesNormals.push(p1.z);
- this._linesNormals.push(-1);
- this._linesNormals.push(p1.x);
- this._linesNormals.push(p1.y);
- this._linesNormals.push(p1.z);
- this._linesNormals.push(1);
- this._linesNormals.push(p0.x);
- this._linesNormals.push(p0.y);
- this._linesNormals.push(p0.z);
- this._linesNormals.push(-1);
- this._linesNormals.push(p0.x);
- this._linesNormals.push(p0.y);
- this._linesNormals.push(p0.z);
- this._linesNormals.push(1);
- // Indices
- this._linesIndices.push(offset);
- this._linesIndices.push(offset + 1);
- this._linesIndices.push(offset + 2);
- this._linesIndices.push(offset);
- this._linesIndices.push(offset + 2);
- this._linesIndices.push(offset + 3);
- }
- };
- EdgesRenderer.prototype._generateEdgesLines = function () {
- var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this._source.getIndices();
- // First let's find adjacencies
- var adjacencies = new Array();
- var faceNormals = new Array();
- var index;
- var faceAdjacencies;
- // Prepare faces
- for (index = 0; index < indices.length; index += 3) {
- faceAdjacencies = new FaceAdjacencies();
- var p0Index = indices[index];
- var p1Index = indices[index + 1];
- var p2Index = indices[index + 2];
- faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
- faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
- faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
- var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
- faceNormal.normalize();
- faceNormals.push(faceNormal);
- adjacencies.push(faceAdjacencies);
- }
- // Scan
- for (index = 0; index < adjacencies.length; index++) {
- faceAdjacencies = adjacencies[index];
- for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
- var otherFaceAdjacencies = adjacencies[otherIndex];
- if (faceAdjacencies.edgesConnectedCount === 3) {
- break;
- }
- if (otherFaceAdjacencies.edgesConnectedCount === 3) {
- continue;
- }
- var otherP0 = indices[otherIndex * 3];
- var otherP1 = indices[otherIndex * 3 + 1];
- var otherP2 = indices[otherIndex * 3 + 2];
- for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
- var otherEdgeIndex;
- if (faceAdjacencies.edges[edgeIndex] !== undefined) {
- continue;
- }
- switch (edgeIndex) {
- case 0:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
- }
- break;
- case 1:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
- }
- break;
- case 2:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
- }
- break;
- }
- if (otherEdgeIndex === -1) {
- continue;
- }
- faceAdjacencies.edges[edgeIndex] = otherIndex;
- otherFaceAdjacencies.edges[otherEdgeIndex] = index;
- faceAdjacencies.edgesConnectedCount++;
- otherFaceAdjacencies.edgesConnectedCount++;
- if (faceAdjacencies.edgesConnectedCount === 3) {
- break;
- }
- }
- }
- }
- // Create lines
- for (index = 0; index < adjacencies.length; index++) {
- // 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
- var current = adjacencies[index];
- this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
- this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
- this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
- }
- // Merge into a single mesh
- var engine = this._source.getScene().getEngine();
- this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
- this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
- this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
- this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
- this._ib = engine.createIndexBuffer(this._linesIndices);
- this._indicesCount = this._linesIndices.length;
- };
- EdgesRenderer.prototype.render = function () {
- if (!this._lineShader.isReady()) {
- return;
- }
- var scene = this._source.getScene();
- var engine = scene.getEngine();
- this._lineShader._preBind();
- // VBOs
- engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
- scene.resetCachedMaterial();
- this._lineShader.setColor4("color", this._source.edgesColor);
- if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
- this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
- }
- else {
- this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
- }
- this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
- this._lineShader.bind(this._source.getWorldMatrix());
- // Draw order
- engine.draw(true, 0, this._indicesCount);
- this._lineShader.unbind();
- engine.setDepthWrite(true);
- };
- return EdgesRenderer;
- })();
- BABYLON.EdgesRenderer = EdgesRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- (function (TonemappingOperator) {
- TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
- TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
- TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
- TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
- })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
- var TonemappingOperator = BABYLON.TonemappingOperator;
- ;
- var TonemapPostProcess = (function (_super) {
- __extends(TonemapPostProcess, _super);
- function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- this._operator = operator;
- this.exposureAdjustment = exposureAdjustment;
- var params = ["_ExposureAdjustment"];
- var defines = "#define ";
- if (operator === TonemappingOperator.Hable)
- defines += "HABLE_TONEMAPPING";
- else if (operator === TonemappingOperator.Reinhard)
- defines += "REINHARD_TONEMAPPING";
- else if (operator === TonemappingOperator.HejiDawson)
- defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
- else if (operator === TonemappingOperator.Photographic)
- defines += "PHOTOGRAPHIC_TONEMAPPING";
- _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
- this.onApply = function (effect) {
- effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
- };
- }
- return TonemapPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.TonemapPostProcess = TonemapPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ReflectionProbe = (function () {
- function ReflectionProbe(name, size, scene, generateMipMaps) {
- var _this = this;
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- this.name = name;
- this._viewMatrix = BABYLON.Matrix.Identity();
- this._target = BABYLON.Vector3.Zero();
- this._add = BABYLON.Vector3.Zero();
- this.position = BABYLON.Vector3.Zero();
- this._scene = scene;
- this._scene.reflectionProbes.push(this);
- this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
- this._renderTargetTexture.onBeforeRender = function (faceIndex) {
- switch (faceIndex) {
- case 0:
- _this._add.copyFromFloats(1, 0, 0);
- break;
- case 1:
- _this._add.copyFromFloats(-1, 0, 0);
- break;
- case 2:
- _this._add.copyFromFloats(0, -1, 0);
- break;
- case 3:
- _this._add.copyFromFloats(0, 1, 0);
- break;
- case 4:
- _this._add.copyFromFloats(0, 0, 1);
- break;
- case 5:
- _this._add.copyFromFloats(0, 0, -1);
- break;
- }
- if (_this._attachedMesh) {
- _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
- }
- _this.position.addToRef(_this._add, _this._target);
- BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
- scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
- };
- this._renderTargetTexture.onAfterUnbind = function () {
- scene.updateTransformMatrix(true);
- };
- this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
- get: function () {
- return this._renderTargetTexture.refreshRate;
- },
- set: function (value) {
- this._renderTargetTexture.refreshRate = value;
- },
- enumerable: true,
- configurable: true
- });
- ReflectionProbe.prototype.getScene = function () {
- return this._scene;
- };
- Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
- get: function () {
- return this._renderTargetTexture;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ReflectionProbe.prototype, "renderList", {
- get: function () {
- return this._renderTargetTexture.renderList;
- },
- enumerable: true,
- configurable: true
- });
- ReflectionProbe.prototype.attachToMesh = function (mesh) {
- this._attachedMesh = mesh;
- };
- ReflectionProbe.prototype.dispose = function () {
- var index = this._scene.reflectionProbes.indexOf(this);
- if (index !== -1) {
- // Remove from the scene if found
- this._scene.reflectionProbes.splice(index, 1);
- }
- if (this._renderTargetTexture) {
- this._renderTargetTexture.dispose();
- this._renderTargetTexture = null;
- }
- };
- return ReflectionProbe;
- })();
- BABYLON.ReflectionProbe = ReflectionProbe;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SolidParticle = (function () {
- function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
- this.color = new BABYLON.Color4(1, 1, 1, 1); // color
- this.position = BABYLON.Vector3.Zero(); // position
- this.rotation = BABYLON.Vector3.Zero(); // rotation
- this.scale = new BABYLON.Vector3(1, 1, 1); // scale
- this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
- this.velocity = BABYLON.Vector3.Zero(); // velocity
- this.alive = true; // alive
- this.idx = particleIndex;
- this._pos = positionIndex;
- this._model = model;
- this.shapeId = shapeId;
- this.idxInShape = idxInShape;
- }
- return SolidParticle;
- })();
- BABYLON.SolidParticle = SolidParticle;
- var ModelShape = (function () {
- function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
- this.shapeID = id;
- this._shape = shape;
- this._shapeUV = shapeUV;
- this._positionFunction = posFunction;
- this._vertexFunction = vtxFunction;
- }
- return ModelShape;
- })();
- BABYLON.ModelShape = ModelShape;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
- */
- var SolidParticleSystem = (function () {
- /**
- * Creates a SPS (Solid Particle System) object.
- * @param name the SPS name, this will be the underlying mesh name
- * @param scene the scene in which the SPS is added
- * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
- */
- function SolidParticleSystem(name, scene, options) {
- // public members
- /**
- * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
- * Example : var p = SPS.particles[i];
- */
- this.particles = new Array();
- /**
- * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
- */
- this.nbParticles = 0;
- /**
- * If the particles must ever face the camera (default false). Useful for planar particles.
- */
- this.billboard = false;
- /**
- * This a counter ofr your own usage. It's not set by any SPS functions.
- */
- this.counter = 0;
- /**
- * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
- * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
- */
- this.vars = {};
- this._positions = new Array();
- this._indices = new Array();
- this._normals = new Array();
- this._colors = new Array();
- this._uvs = new Array();
- this._index = 0; // indices index
- this._updatable = true;
- this._pickable = false;
- this._isVisibilityBoxLocked = false;
- this._alwaysVisible = false;
- this._shapeCounter = 0;
- this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
- this._color = new BABYLON.Color4(0, 0, 0, 0);
- this._computeParticleColor = true;
- this._computeParticleTexture = true;
- this._computeParticleRotation = true;
- this._computeParticleVertex = false;
- this._computeBoundingBox = false;
- this._cam_axisZ = BABYLON.Vector3.Zero();
- this._cam_axisY = BABYLON.Vector3.Zero();
- this._cam_axisX = BABYLON.Vector3.Zero();
- this._axisX = BABYLON.Axis.X;
- this._axisY = BABYLON.Axis.Y;
- this._axisZ = BABYLON.Axis.Z;
- this._fakeCamPos = BABYLON.Vector3.Zero();
- this._rotMatrix = new BABYLON.Matrix();
- this._invertMatrix = new BABYLON.Matrix();
- this._rotated = BABYLON.Vector3.Zero();
- this._quaternion = new BABYLON.Quaternion();
- this._vertex = BABYLON.Vector3.Zero();
- this._normal = BABYLON.Vector3.Zero();
- this._yaw = 0.0;
- this._pitch = 0.0;
- this._roll = 0.0;
- this._halfroll = 0.0;
- this._halfpitch = 0.0;
- this._halfyaw = 0.0;
- this._sinRoll = 0.0;
- this._cosRoll = 0.0;
- this._sinPitch = 0.0;
- this._cosPitch = 0.0;
- this._sinYaw = 0.0;
- this._cosYaw = 0.0;
- this._w = 0.0;
- this._minimum = BABYLON.Tmp.Vector3[0];
- this._maximum = BABYLON.Tmp.Vector3[1];
- this.name = name;
- this._scene = scene;
- this._camera = scene.activeCamera;
- this._pickable = options ? options.isPickable : false;
- if (options && options.updatable) {
- this._updatable = options.updatable;
- }
- else {
- this._updatable = true;
- }
- if (this._pickable) {
- this.pickedParticles = [];
- }
- }
- /**
- * Builds the SPS underlying mesh. Returns a standard Mesh.
- * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
- */
- SolidParticleSystem.prototype.buildMesh = function () {
- if (this.nbParticles === 0) {
- var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
- this.addShape(triangle, 1);
- triangle.dispose();
- }
- this._positions32 = new Float32Array(this._positions);
- this._uvs32 = new Float32Array(this._uvs);
- this._colors32 = new Float32Array(this._colors);
- BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
- this._normals32 = new Float32Array(this._normals);
- this._fixedNormal32 = new Float32Array(this._normals);
- var vertexData = new BABYLON.VertexData();
- vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
- vertexData.indices = this._indices;
- vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
- if (this._uvs32) {
- vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
- ;
- }
- if (this._colors32) {
- vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
- }
- var mesh = new BABYLON.Mesh(this.name, this._scene);
- vertexData.applyToMesh(mesh, this._updatable);
- this.mesh = mesh;
- this.mesh.isPickable = this._pickable;
- // free memory
- this._positions = null;
- this._normals = null;
- this._uvs = null;
- this._colors = null;
- if (!this._updatable) {
- this.particles.length = 0;
- }
- return mesh;
- };
- /**
- * Digests the mesh and generates as many solid particles in the system as wanted.
- * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
- * Thus the particles generated from digest() have their property "positiion" yet set.
- * @param mesh the mesh to be digested
- * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
- * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
- */
- SolidParticleSystem.prototype.digest = function (mesh, options) {
- var size = (options && options.facetNb) || 1;
- var number = (options && options.number);
- var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var meshInd = mesh.getIndices();
- var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var f = 0; // facet counter
- var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
- // compute size from number
- if (number) {
- number = (number > totalFacets) ? totalFacets : number;
- size = Math.round(totalFacets / number);
- }
- else {
- size = (size > totalFacets) ? totalFacets : size;
- }
- var facetPos = []; // submesh positions
- var facetInd = []; // submesh indices
- var facetUV = []; // submesh UV
- var facetCol = []; // submesh colors
- var barycenter = BABYLON.Tmp.Vector3[0];
- while (f < totalFacets) {
- if (f > totalFacets - size) {
- size = totalFacets - f;
- }
- // reset temp arrays
- facetPos.length = 0;
- facetInd.length = 0;
- facetUV.length = 0;
- facetCol.length = 0;
- // iterate over "size" facets
- var fi = 0;
- for (var j = f * 3; j < (f + size) * 3; j++) {
- facetInd.push(fi);
- var i = meshInd[j];
- facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
- if (meshUV) {
- facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
- }
- if (meshCol) {
- facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
- }
- fi++;
- }
- // create a model shape for each single particle
- var idx = this.nbParticles;
- var shape = this._posToShape(facetPos);
- var shapeUV = this._uvsToShapeUV(facetUV);
- // compute the barycenter of the shape
- var v;
- for (v = 0; v < shape.length; v++) {
- barycenter.addInPlace(shape[v]);
- }
- barycenter.scaleInPlace(1 / shape.length);
- // shift the shape from its barycenter to the origin
- for (v = 0; v < shape.length; v++) {
- shape[v].subtractInPlace(barycenter);
- }
- var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
- // add the particle in the SPS
- this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
- this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
- // initialize the particle position
- this.particles[this.nbParticles].position.addInPlace(barycenter);
- this._index += shape.length;
- idx++;
- this.nbParticles++;
- this._shapeCounter++;
- f += size;
- }
- };
- //reset copy
- SolidParticleSystem.prototype._resetCopy = function () {
- this._copy.position.x = 0;
- this._copy.position.y = 0;
- this._copy.position.z = 0;
- this._copy.rotation.x = 0;
- this._copy.rotation.y = 0;
- this._copy.rotation.z = 0;
- this._copy.quaternion = null;
- this._copy.scale.x = 1;
- this._copy.scale.y = 1;
- this._copy.scale.z = 1;
- this._copy.uvs.x = 0;
- this._copy.uvs.y = 0;
- this._copy.uvs.z = 1;
- this._copy.uvs.w = 1;
- this._copy.color = null;
- };
- // _meshBuilder : inserts the shape model in the global SPS mesh
- SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
- var i;
- var u = 0;
- var c = 0;
- this._resetCopy();
- if (options && options.positionFunction) {
- options.positionFunction(this._copy, idx, idxInShape);
- }
- if (this._copy.quaternion) {
- this._quaternion.x = this._copy.quaternion.x;
- this._quaternion.y = this._copy.quaternion.y;
- this._quaternion.z = this._copy.quaternion.z;
- this._quaternion.w = this._copy.quaternion.w;
- }
- else {
- this._yaw = this._copy.rotation.y;
- this._pitch = this._copy.rotation.x;
- this._roll = this._copy.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- for (i = 0; i < shape.length; i++) {
- this._vertex.x = shape[i].x;
- this._vertex.y = shape[i].y;
- this._vertex.z = shape[i].z;
- if (options && options.vertexFunction) {
- options.vertexFunction(this._copy, this._vertex, i);
- }
- this._vertex.x *= this._copy.scale.x;
- this._vertex.y *= this._copy.scale.y;
- this._vertex.z *= this._copy.scale.z;
- BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
- positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
- if (meshUV) {
- 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);
- u += 2;
- }
- if (this._copy.color) {
- this._color = this._copy.color;
- }
- else if (meshCol && meshCol[c]) {
- this._color.r = meshCol[c];
- this._color.g = meshCol[c + 1];
- this._color.b = meshCol[c + 2];
- this._color.a = meshCol[c + 3];
- }
- else {
- this._color.r = 1;
- this._color.g = 1;
- this._color.b = 1;
- this._color.a = 1;
- }
- colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
- c += 4;
- }
- for (i = 0; i < meshInd.length; i++) {
- indices.push(p + meshInd[i]);
- }
- if (this._pickable) {
- var nbfaces = meshInd.length / 3;
- for (i = 0; i < nbfaces; i++) {
- this.pickedParticles.push({ idx: idx, faceId: i });
- }
- }
- };
- // returns a shape array from positions array
- SolidParticleSystem.prototype._posToShape = function (positions) {
- var shape = [];
- for (var i = 0; i < positions.length; i += 3) {
- shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
- }
- return shape;
- };
- // returns a shapeUV array from a Vector4 uvs
- SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
- var shapeUV = [];
- if (uvs) {
- for (var i = 0; i < uvs.length; i++)
- shapeUV.push(uvs[i]);
- }
- return shapeUV;
- };
- // adds a new particle object in the particles array
- SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
- this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
- };
- /**
- * Adds some particles to the SPS from the model shape.
- * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
- * @param mesh any Mesh object that will be used as a model for the solid particles.
- * @param nb the number of particles to be created from this model
- * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
- */
- SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
- var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var meshInd = mesh.getIndices();
- var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var shape = this._posToShape(meshPos);
- var shapeUV = this._uvsToShapeUV(meshUV);
- var posfunc = options ? options.positionFunction : null;
- var vtxfunc = options ? options.vertexFunction : null;
- var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
- // particles
- var idx = this.nbParticles;
- for (var i = 0; i < nb; i++) {
- this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
- if (this._updatable) {
- this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
- }
- this._index += shape.length;
- idx++;
- }
- this.nbParticles += nb;
- this._shapeCounter++;
- return this._shapeCounter - 1;
- };
- // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
- SolidParticleSystem.prototype._rebuildParticle = function (particle) {
- this._resetCopy();
- if (particle._model._positionFunction) {
- particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
- }
- if (this._copy.quaternion) {
- this._quaternion.x = this._copy.quaternion.x;
- this._quaternion.y = this._copy.quaternion.y;
- this._quaternion.z = this._copy.quaternion.z;
- this._quaternion.w = this._copy.quaternion.w;
- }
- else {
- this._yaw = this._copy.rotation.y;
- this._pitch = this._copy.rotation.x;
- this._roll = this._copy.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- this._shape = particle._model._shape;
- for (var pt = 0; pt < this._shape.length; pt++) {
- this._vertex.x = this._shape[pt].x;
- this._vertex.y = this._shape[pt].y;
- this._vertex.z = this._shape[pt].z;
- if (particle._model._vertexFunction) {
- particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
- }
- this._vertex.x *= this._copy.scale.x;
- this._vertex.y *= this._copy.scale.y;
- this._vertex.z *= this._copy.scale.z;
- BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
- this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
- this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
- this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
- }
- particle.position.x = 0;
- particle.position.y = 0;
- particle.position.z = 0;
- particle.rotation.x = 0;
- particle.rotation.y = 0;
- particle.rotation.z = 0;
- particle.quaternion = null;
- particle.scale.x = 1;
- particle.scale.y = 1;
- particle.scale.z = 1;
- };
- /**
- * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
- */
- SolidParticleSystem.prototype.rebuildMesh = function () {
- for (var p = 0; p < this.particles.length; p++) {
- this._rebuildParticle(this.particles[p]);
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
- };
- /**
- * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
- * This method calls updateParticle() for each particles of the SPS.
- * For an animated SPS, it is usually called within the render loop.
- * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
- * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
- * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
- */
- SolidParticleSystem.prototype.setParticles = function (start, end, update) {
- if (start === void 0) { start = 0; }
- if (end === void 0) { end = this.nbParticles - 1; }
- if (update === void 0) { update = true; }
- if (!this._updatable) {
- return;
- }
- // custom beforeUpdate
- this.beforeUpdateParticles(start, end, update);
- this._cam_axisX.x = 1;
- this._cam_axisX.y = 0;
- this._cam_axisX.z = 0;
- this._cam_axisY.x = 0;
- this._cam_axisY.y = 1;
- this._cam_axisY.z = 0;
- this._cam_axisZ.x = 0;
- this._cam_axisZ.y = 0;
- this._cam_axisZ.z = 1;
- // if the particles will always face the camera
- if (this.billboard) {
- // compute a fake camera position : un-rotate the camera position by the current mesh rotation
- this._yaw = this.mesh.rotation.y;
- this._pitch = this.mesh.rotation.x;
- this._roll = this.mesh.rotation.z;
- this._quaternionRotationYPR();
- this._quaternionToRotationMatrix();
- this._rotMatrix.invertToRef(this._invertMatrix);
- BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
- // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
- (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
- BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
- BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
- this._cam_axisY.normalize();
- this._cam_axisX.normalize();
- this._cam_axisZ.normalize();
- }
- BABYLON.Matrix.IdentityToRef(this._rotMatrix);
- var idx = 0;
- var index = 0;
- var colidx = 0;
- var colorIndex = 0;
- var uvidx = 0;
- var uvIndex = 0;
- if (this._computeBoundingBox) {
- BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
- BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
- }
- // particle loop
- end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
- for (var p = start; p <= end; p++) {
- this._particle = this.particles[p];
- this._shape = this._particle._model._shape;
- this._shapeUV = this._particle._model._shapeUV;
- // call to custom user function to update the particle properties
- this.updateParticle(this._particle);
- // particle rotation matrix
- if (this.billboard) {
- this._particle.rotation.x = 0.0;
- this._particle.rotation.y = 0.0;
- }
- if (this._computeParticleRotation) {
- if (this._particle.quaternion) {
- this._quaternion.x = this._particle.quaternion.x;
- this._quaternion.y = this._particle.quaternion.y;
- this._quaternion.z = this._particle.quaternion.z;
- this._quaternion.w = this._particle.quaternion.w;
- }
- else {
- this._yaw = this._particle.rotation.y;
- this._pitch = this._particle.rotation.x;
- this._roll = this._particle.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- }
- for (var pt = 0; pt < this._shape.length; pt++) {
- idx = index + pt * 3;
- colidx = colorIndex + pt * 4;
- uvidx = uvIndex + pt * 2;
- this._vertex.x = this._shape[pt].x;
- this._vertex.y = this._shape[pt].y;
- this._vertex.z = this._shape[pt].z;
- if (this._computeParticleVertex) {
- this.updateParticleVertex(this._particle, this._vertex, pt);
- }
- // positions
- this._vertex.x *= this._particle.scale.x;
- this._vertex.y *= this._particle.scale.y;
- this._vertex.z *= this._particle.scale.z;
- this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
- this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
- this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
- this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
- this._positions32[idx] = 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;
- this._positions32[idx + 1] = 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;
- this._positions32[idx + 2] = 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;
- if (this._computeBoundingBox) {
- if (this._positions32[idx] < this._minimum.x) {
- this._minimum.x = this._positions32[idx];
- }
- if (this._positions32[idx] > this._maximum.x) {
- this._maximum.x = this._positions32[idx];
- }
- if (this._positions32[idx + 1] < this._minimum.y) {
- this._minimum.y = this._positions32[idx + 1];
- }
- if (this._positions32[idx + 1] > this._maximum.y) {
- this._maximum.y = this._positions32[idx + 1];
- }
- if (this._positions32[idx + 2] < this._minimum.z) {
- this._minimum.z = this._positions32[idx + 2];
- }
- if (this._positions32[idx + 2] > this._maximum.z) {
- this._maximum.z = this._positions32[idx + 2];
- }
- }
- // normals : if the particles can't be morphed then just rotate the normals
- if (!this._computeParticleVertex && !this.billboard) {
- this._normal.x = this._fixedNormal32[idx];
- this._normal.y = this._fixedNormal32[idx + 1];
- this._normal.z = this._fixedNormal32[idx + 2];
- this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
- this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
- this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
- this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
- this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
- 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;
- 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;
- }
- if (this._computeParticleColor) {
- this._colors32[colidx] = this._particle.color.r;
- this._colors32[colidx + 1] = this._particle.color.g;
- this._colors32[colidx + 2] = this._particle.color.b;
- this._colors32[colidx + 3] = this._particle.color.a;
- }
- if (this._computeParticleTexture) {
- this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
- this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
- }
- }
- index = idx + 3;
- colorIndex = colidx + 4;
- uvIndex = uvidx + 2;
- }
- if (update) {
- if (this._computeParticleColor) {
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
- }
- if (this._computeParticleTexture) {
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
- if (!this.mesh.areNormalsFrozen) {
- if (this._computeParticleVertex || this.billboard) {
- // recompute the normals only if the particles can be morphed, update then the normal reference array
- BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
- for (var i = 0; i < this._normals32.length; i++) {
- this._fixedNormal32[i] = this._normals32[i];
- }
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
- }
- }
- if (this._computeBoundingBox) {
- this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
- this.mesh._boundingInfo.update(this.mesh._worldMatrix);
- }
- this.afterUpdateParticles(start, end, update);
- };
- SolidParticleSystem.prototype._quaternionRotationYPR = function () {
- this._halfroll = this._roll * 0.5;
- this._halfpitch = this._pitch * 0.5;
- this._halfyaw = this._yaw * 0.5;
- this._sinRoll = Math.sin(this._halfroll);
- this._cosRoll = Math.cos(this._halfroll);
- this._sinPitch = Math.sin(this._halfpitch);
- this._cosPitch = Math.cos(this._halfpitch);
- this._sinYaw = Math.sin(this._halfyaw);
- this._cosYaw = Math.cos(this._halfyaw);
- this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
- this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
- this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
- this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
- };
- SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
- this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
- this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
- this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
- this._rotMatrix.m[3] = 0;
- this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
- this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
- this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
- this._rotMatrix.m[7] = 0;
- this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
- this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
- this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
- this._rotMatrix.m[11] = 0;
- this._rotMatrix.m[12] = 0;
- this._rotMatrix.m[13] = 0;
- this._rotMatrix.m[14] = 0;
- this._rotMatrix.m[15] = 1.0;
- };
- /**
- * Disposes the SPS
- */
- SolidParticleSystem.prototype.dispose = function () {
- this.mesh.dispose();
- this.vars = null;
- // drop references to internal big arrays for the GC
- this._positions = null;
- this._indices = null;
- this._normals = null;
- this._uvs = null;
- this._colors = null;
- this._positions32 = null;
- this._normals32 = null;
- this._fixedNormal32 = null;
- this._uvs32 = null;
- this._colors32 = null;
- this.pickedParticles = null;
- };
- /**
- * Visibilty helper : Recomputes the visible size according to the mesh bounding box
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- SolidParticleSystem.prototype.refreshVisibleSize = function () {
- if (!this._isVisibilityBoxLocked) {
- this.mesh.refreshBoundingInfo();
- }
- };
- /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
- * @param size the size (float) of the visibility box
- * note : this doesn't lock the SPS mesh bounding box.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- SolidParticleSystem.prototype.setVisibilityBox = function (size) {
- var vis = size / 2;
- this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
- };
- Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
- // getter and setter
- /**
- * True if the SPS is set as always visible
- */
- get: function () {
- return this._alwaysVisible;
- },
- /**
- * Sets the SPS as always visible or not
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- set: function (val) {
- this._alwaysVisible = val;
- this.mesh.alwaysSelectAsActiveMesh = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
- /**
- * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
- */
- get: function () {
- return this._isVisibilityBoxLocked;
- },
- /**
- * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- set: function (val) {
- this._isVisibilityBoxLocked = val;
- this.mesh.getBoundingInfo().isLocked = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
- // getters
- get: function () {
- return this._computeParticleRotation;
- },
- // Optimizer setters
- /**
- * Tells to setParticles() to compute the particle rotations or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
- */
- set: function (val) {
- this._computeParticleRotation = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
- get: function () {
- return this._computeParticleColor;
- },
- /**
- * Tells to setParticles() to compute the particle colors or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
- */
- set: function (val) {
- this._computeParticleColor = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
- get: function () {
- return this._computeParticleTexture;
- },
- /**
- * Tells to setParticles() to compute the particle textures or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
- */
- set: function (val) {
- this._computeParticleTexture = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
- get: function () {
- return this._computeParticleVertex;
- },
- /**
- * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
- * Default value : false. The SPS is faster when it's set to false.
- * Note : the particle custom vertex positions aren't stored values.
- */
- set: function (val) {
- this._computeParticleVertex = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
- get: function () {
- return this._computeBoundingBox;
- },
- /**
- * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
- */
- set: function (val) {
- this._computeBoundingBox = val;
- },
- enumerable: true,
- configurable: true
- });
- // =======================================================================
- // Particle behavior logic
- // these following methods may be overwritten by the user to fit his needs
- /**
- * This function does nothing. It may be overwritten to set all the particles first values.
- * The SPS doesn't call this function, you may have to call it by your own.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- */
- SolidParticleSystem.prototype.initParticles = function () {
- };
- /**
- * This function does nothing. It may be overwritten to recycle a particle.
- * The SPS doesn't call this function, you may have to call it by your own.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- */
- SolidParticleSystem.prototype.recycleParticle = function (particle) {
- return particle;
- };
- /**
- * Updates a particle : this function should be overwritten by the user.
- * It is called on each particle by setParticles(). This is the place to code each particle behavior.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- * ex : just set a particle position or velocity and recycle conditions
- */
- SolidParticleSystem.prototype.updateParticle = function (particle) {
- return particle;
- };
- /**
- * Updates a vertex of a particle : it can be overwritten by the user.
- * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
- * @param particle the current particle
- * @param vertex the current index of the current particle
- * @param pt the index of the current vertex in the particle shape
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
- * ex : just set a vertex particle position
- */
- SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
- return vertex;
- };
- /**
- * This will be called before any other treatment by setParticles() and will be passed three parameters.
- * This does nothing and may be overwritten by the user.
- * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param update the boolean update value actually passed to setParticles()
- */
- SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
- };
- /**
- * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
- * This will be passed three parameters.
- * This does nothing and may be overwritten by the user.
- * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param update the boolean update value actually passed to setParticles()
- */
- SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
- };
- return SolidParticleSystem;
- })();
- BABYLON.SolidParticleSystem = SolidParticleSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var UniversalCamera = (function (_super) {
- __extends(UniversalCamera, _super);
- function UniversalCamera(name, position, scene) {
- var _this = this;
- _super.call(this, name, position, scene);
- this.gamepadAngularSensibility = 200;
- this.gamepadMoveSensibility = 40;
- this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
- }
- UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
- // Only the first gamepad can control the camera
- if (gamepad.index === 0) {
- this.gamepad = gamepad;
- }
- };
- UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
- _super.prototype.attachControl.call(this, canvas, false);
- };
- UniversalCamera.prototype.detachControl = function (canvas) {
- _super.prototype.detachControl.call(this, canvas);
- };
- UniversalCamera.prototype._checkInputs = function () {
- if (this.gamepad) {
- var LSValues = this.gamepad.leftStick;
- var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
- var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
- LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
- LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
- var RSValues = this.gamepad.rightStick;
- var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
- var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
- RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
- RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
- var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
- var speed = this._computeLocalCameraSpeed() * 50.0;
- var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
- this.cameraDirection = this.cameraDirection.add(deltaTransform);
- this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
- }
- _super.prototype._checkInputs.call(this);
- };
- UniversalCamera.prototype.dispose = function () {
- this._gamepads.dispose();
- _super.prototype.dispose.call(this);
- };
- return UniversalCamera;
- })(BABYLON.TouchCamera);
- BABYLON.UniversalCamera = UniversalCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Gamepads = (function () {
- function Gamepads(ongamedpadconnected) {
- var _this = this;
- this.babylonGamepads = [];
- this.oneGamepadConnected = false;
- this.isMonitoring = false;
- this.gamepadEventSupported = 'GamepadEvent' in window;
- this.gamepadSupportAvailable = (navigator.getGamepads ||
- !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
- this._callbackGamepadConnected = ongamedpadconnected;
- if (this.gamepadSupportAvailable) {
- // Checking if the gamepad connected event is supported (like in Firefox)
- if (this.gamepadEventSupported) {
- window.addEventListener('gamepadconnected', function (evt) {
- _this._onGamepadConnected(evt);
- }, false);
- window.addEventListener('gamepaddisconnected', function (evt) {
- _this._onGamepadDisconnected(evt);
- }, false);
- }
- else {
- this._startMonitoringGamepads();
- }
- }
- }
- Gamepads.prototype.dispose = function () {
- if (Gamepads.gamepadDOMInfo) {
- document.body.removeChild(Gamepads.gamepadDOMInfo);
- }
- };
- Gamepads.prototype._onGamepadConnected = function (evt) {
- var newGamepad = this._addNewGamepad(evt.gamepad);
- if (this._callbackGamepadConnected)
- this._callbackGamepadConnected(newGamepad);
- this._startMonitoringGamepads();
- };
- Gamepads.prototype._addNewGamepad = function (gamepad) {
- if (!this.oneGamepadConnected) {
- this.oneGamepadConnected = true;
- if (Gamepads.gamepadDOMInfo) {
- document.body.removeChild(Gamepads.gamepadDOMInfo);
- Gamepads.gamepadDOMInfo = null;
- }
- }
- var newGamepad;
- if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
- newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
- }
- else {
- newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
- }
- this.babylonGamepads.push(newGamepad);
- return newGamepad;
- };
- Gamepads.prototype._onGamepadDisconnected = function (evt) {
- // Remove the gamepad from the list of gamepads to monitor.
- for (var i in this.babylonGamepads) {
- if (this.babylonGamepads[i].index == evt.gamepad.index) {
- this.babylonGamepads.splice(i, 1);
- break;
- }
- }
- // If no gamepads are left, stop the polling loop.
- if (this.babylonGamepads.length == 0) {
- this._stopMonitoringGamepads();
- }
- };
- Gamepads.prototype._startMonitoringGamepads = function () {
- if (!this.isMonitoring) {
- this.isMonitoring = true;
- this._checkGamepadsStatus();
- }
- };
- Gamepads.prototype._stopMonitoringGamepads = function () {
- this.isMonitoring = false;
- };
- Gamepads.prototype._checkGamepadsStatus = function () {
- var _this = this;
- // updating gamepad objects
- this._updateGamepadObjects();
- for (var i in this.babylonGamepads) {
- this.babylonGamepads[i].update();
- }
- if (this.isMonitoring) {
- if (window.requestAnimationFrame) {
- window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- else if (window.mozRequestAnimationFrame) {
- window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- else if (window.webkitRequestAnimationFrame) {
- window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- }
- };
- // This function is called only on Chrome, which does not yet support
- // connection/disconnection events, but requires you to monitor
- // an array for changes.
- Gamepads.prototype._updateGamepadObjects = function () {
- var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
- for (var i = 0; i < gamepads.length; i++) {
- if (gamepads[i]) {
- if (!(gamepads[i].index in this.babylonGamepads)) {
- var newGamepad = this._addNewGamepad(gamepads[i]);
- if (this._callbackGamepadConnected) {
- this._callbackGamepadConnected(newGamepad);
- }
- }
- else {
- this.babylonGamepads[i].browserGamepad = gamepads[i];
- }
- }
- }
- };
- return Gamepads;
- })();
- BABYLON.Gamepads = Gamepads;
- var StickValues = (function () {
- function StickValues(x, y) {
- this.x = x;
- this.y = y;
- }
- return StickValues;
- })();
- BABYLON.StickValues = StickValues;
- var Gamepad = (function () {
- function Gamepad(id, index, browserGamepad) {
- this.id = id;
- this.index = index;
- this.browserGamepad = browserGamepad;
- if (this.browserGamepad.axes.length >= 2) {
- this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
- }
- if (this.browserGamepad.axes.length >= 4) {
- this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
- }
- }
- Gamepad.prototype.onleftstickchanged = function (callback) {
- this._onleftstickchanged = callback;
- };
- Gamepad.prototype.onrightstickchanged = function (callback) {
- this._onrightstickchanged = callback;
- };
- Object.defineProperty(Gamepad.prototype, "leftStick", {
- get: function () {
- return this._leftStick;
- },
- set: function (newValues) {
- if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
- this._onleftstickchanged(newValues);
- }
- this._leftStick = newValues;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Gamepad.prototype, "rightStick", {
- get: function () {
- return this._rightStick;
- },
- set: function (newValues) {
- if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
- this._onrightstickchanged(newValues);
- }
- this._rightStick = newValues;
- },
- enumerable: true,
- configurable: true
- });
- Gamepad.prototype.update = function () {
- if (this._leftStick) {
- this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
- }
- if (this._rightStick) {
- this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
- }
- };
- return Gamepad;
- })();
- BABYLON.Gamepad = Gamepad;
- var GenericPad = (function (_super) {
- __extends(GenericPad, _super);
- function GenericPad(id, index, gamepad) {
- _super.call(this, id, index, gamepad);
- this.id = id;
- this.index = index;
- this.gamepad = gamepad;
- this._buttons = new Array(gamepad.buttons.length);
- }
- GenericPad.prototype.onbuttondown = function (callback) {
- this._onbuttondown = callback;
- };
- GenericPad.prototype.onbuttonup = function (callback) {
- this._onbuttonup = callback;
- };
- GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
- if (newValue !== currentValue) {
- if (this._onbuttondown && newValue === 1) {
- this._onbuttondown(buttonIndex);
- }
- if (this._onbuttonup && newValue === 0) {
- this._onbuttonup(buttonIndex);
- }
- }
- return newValue;
- };
- GenericPad.prototype.update = function () {
- _super.prototype.update.call(this);
- for (var index = 0; index < this._buttons.length; index++) {
- this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
- }
- };
- return GenericPad;
- })(Gamepad);
- BABYLON.GenericPad = GenericPad;
- (function (Xbox360Button) {
- Xbox360Button[Xbox360Button["A"] = 0] = "A";
- Xbox360Button[Xbox360Button["B"] = 1] = "B";
- Xbox360Button[Xbox360Button["X"] = 2] = "X";
- Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
- Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
- Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
- Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
- Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
- Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
- Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
- })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
- var Xbox360Button = BABYLON.Xbox360Button;
- (function (Xbox360Dpad) {
- Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
- Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
- Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
- Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
- })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
- var Xbox360Dpad = BABYLON.Xbox360Dpad;
- var Xbox360Pad = (function (_super) {
- __extends(Xbox360Pad, _super);
- function Xbox360Pad() {
- _super.apply(this, arguments);
- this._leftTrigger = 0;
- this._rightTrigger = 0;
- this._buttonA = 0;
- this._buttonB = 0;
- this._buttonX = 0;
- this._buttonY = 0;
- this._buttonBack = 0;
- this._buttonStart = 0;
- this._buttonLB = 0;
- this._buttonRB = 0;
- this._buttonLeftStick = 0;
- this._buttonRightStick = 0;
- this._dPadUp = 0;
- this._dPadDown = 0;
- this._dPadLeft = 0;
- this._dPadRight = 0;
- }
- Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
- this._onlefttriggerchanged = callback;
- };
- Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
- this._onrighttriggerchanged = callback;
- };
- Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
- get: function () {
- return this._leftTrigger;
- },
- set: function (newValue) {
- if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
- this._onlefttriggerchanged(newValue);
- }
- this._leftTrigger = newValue;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
- get: function () {
- return this._rightTrigger;
- },
- set: function (newValue) {
- if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
- this._onrighttriggerchanged(newValue);
- }
- this._rightTrigger = newValue;
- },
- enumerable: true,
- configurable: true
- });
- Xbox360Pad.prototype.onbuttondown = function (callback) {
- this._onbuttondown = callback;
- };
- Xbox360Pad.prototype.onbuttonup = function (callback) {
- this._onbuttonup = callback;
- };
- Xbox360Pad.prototype.ondpaddown = function (callback) {
- this._ondpaddown = callback;
- };
- Xbox360Pad.prototype.ondpadup = function (callback) {
- this._ondpadup = callback;
- };
- Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
- if (newValue !== currentValue) {
- if (this._onbuttondown && newValue === 1) {
- this._onbuttondown(buttonType);
- }
- if (this._onbuttonup && newValue === 0) {
- this._onbuttonup(buttonType);
- }
- }
- return newValue;
- };
- Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
- if (newValue !== currentValue) {
- if (this._ondpaddown && newValue === 1) {
- this._ondpaddown(buttonType);
- }
- if (this._ondpadup && newValue === 0) {
- this._ondpadup(buttonType);
- }
- }
- return newValue;
- };
- Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
- get: function () {
- return this._buttonA;
- },
- set: function (value) {
- this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
- get: function () {
- return this._buttonB;
- },
- set: function (value) {
- this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
- get: function () {
- return this._buttonX;
- },
- set: function (value) {
- this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
- get: function () {
- return this._buttonY;
- },
- set: function (value) {
- this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
- get: function () {
- return this._buttonStart;
- },
- set: function (value) {
- this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
- get: function () {
- return this._buttonBack;
- },
- set: function (value) {
- this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
- get: function () {
- return this._buttonLB;
- },
- set: function (value) {
- this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
- get: function () {
- return this._buttonRB;
- },
- set: function (value) {
- this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
- get: function () {
- return this._buttonLeftStick;
- },
- set: function (value) {
- this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
- get: function () {
- return this._buttonRightStick;
- },
- set: function (value) {
- this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
- get: function () {
- return this._dPadUp;
- },
- set: function (value) {
- this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
- get: function () {
- return this._dPadDown;
- },
- set: function (value) {
- this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
- get: function () {
- return this._dPadLeft;
- },
- set: function (value) {
- this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
- get: function () {
- return this._dPadRight;
- },
- set: function (value) {
- this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
- },
- enumerable: true,
- configurable: true
- });
- Xbox360Pad.prototype.update = function () {
- _super.prototype.update.call(this);
- this.buttonA = this.browserGamepad.buttons[0].value;
- this.buttonB = this.browserGamepad.buttons[1].value;
- this.buttonX = this.browserGamepad.buttons[2].value;
- this.buttonY = this.browserGamepad.buttons[3].value;
- this.buttonLB = this.browserGamepad.buttons[4].value;
- this.buttonRB = this.browserGamepad.buttons[5].value;
- this.leftTrigger = this.browserGamepad.buttons[6].value;
- this.rightTrigger = this.browserGamepad.buttons[7].value;
- this.buttonBack = this.browserGamepad.buttons[8].value;
- this.buttonStart = this.browserGamepad.buttons[9].value;
- this.buttonLeftStick = this.browserGamepad.buttons[10].value;
- this.buttonRightStick = this.browserGamepad.buttons[11].value;
- this.dPadUp = this.browserGamepad.buttons[12].value;
- this.dPadDown = this.browserGamepad.buttons[13].value;
- this.dPadLeft = this.browserGamepad.buttons[14].value;
- this.dPadRight = this.browserGamepad.buttons[15].value;
- };
- return Xbox360Pad;
- })(Gamepad);
- BABYLON.Xbox360Pad = Xbox360Pad;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var GamepadCamera = (function (_super) {
- __extends(GamepadCamera, _super);
- function GamepadCamera(name, position, scene) {
- BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
- _super.call(this, name, position, scene);
- }
- return GamepadCamera;
- })(BABYLON.UniversalCamera);
- BABYLON.GamepadCamera = GamepadCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnaglyphFreeCamera = (function (_super) {
- __extends(AnaglyphFreeCamera, _super);
- function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- return AnaglyphFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
- var AnaglyphArcRotateCamera = (function (_super) {
- __extends(AnaglyphArcRotateCamera, _super);
- function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
- _super.call(this, name, alpha, beta, radius, target, scene);
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- return AnaglyphArcRotateCamera;
- })(BABYLON.ArcRotateCamera);
- BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
- var AnaglyphGamepadCamera = (function (_super) {
- __extends(AnaglyphGamepadCamera, _super);
- function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
- _super.call(this, name, position, scene);
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- return AnaglyphGamepadCamera;
- })(BABYLON.GamepadCamera);
- BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
- var StereoscopicFreeCamera = (function (_super) {
- __extends(StereoscopicFreeCamera, _super);
- function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
- _super.call(this, name, position, scene);
- this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- return StereoscopicFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
- var StereoscopicArcRotateCamera = (function (_super) {
- __extends(StereoscopicArcRotateCamera, _super);
- function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
- _super.call(this, name, alpha, beta, radius, target, scene);
- this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- return StereoscopicArcRotateCamera;
- })(BABYLON.ArcRotateCamera);
- BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
- var StereoscopicGamepadCamera = (function (_super) {
- __extends(StereoscopicGamepadCamera, _super);
- function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
- _super.call(this, name, position, scene);
- this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- return StereoscopicGamepadCamera;
- })(BABYLON.GamepadCamera);
- BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var FileFaceOrientation = (function () {
- function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
- this.name = name;
- this.worldAxisForNormal = worldAxisForNormal;
- this.worldAxisForFileX = worldAxisForFileX;
- this.worldAxisForFileY = worldAxisForFileY;
- }
- return FileFaceOrientation;
- })();
- ;
- var CubeMapToSphericalPolynomialTools = (function () {
- function CubeMapToSphericalPolynomialTools() {
- }
- CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
- var sphericalHarmonics = new BABYLON.SphericalHarmonics();
- var totalSolidAngle = 0.0;
- // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
- var du = 2.0 / cubeInfo.size;
- var dv = du;
- // The (u,v) of the first texel is half a texel from the corner (-1,-1).
- var minUV = du * 0.5 - 1.0;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- var fileFace = this.FileFaces[faceIndex];
- var dataArray = cubeInfo[fileFace.name];
- var v = minUV;
- // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
- // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
- // Because SP is still linear, so summation is fine in that basis.
- for (var y = 0; y < cubeInfo.size; y++) {
- var u = minUV;
- for (var x = 0; x < cubeInfo.size; x++) {
- // World direction (not normalised)
- var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
- worldDirection.normalize();
- var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
- if (1) {
- var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
- var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
- var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
- var color = new BABYLON.Color3(r, g, b);
- sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
- }
- else {
- if (faceIndex == 0) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 1) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 2) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- else if (faceIndex == 3) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 4) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- else if (faceIndex == 5) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
- sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
- }
- totalSolidAngle += deltaSolidAngle;
- u += du;
- }
- v += dv;
- }
- }
- var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
- var correction = correctSolidAngle / totalSolidAngle;
- sphericalHarmonics.scale(correction);
- // Additionally scale by pi -- audit needed
- sphericalHarmonics.scale(1.0 / Math.PI);
- return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
- };
- CubeMapToSphericalPolynomialTools.FileFaces = [
- new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
- new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
- new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
- ];
- return CubeMapToSphericalPolynomialTools;
- })();
- Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var PanoramaToCubeMapTools = (function () {
- function PanoramaToCubeMapTools() {
- }
- PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
- if (!float32Array) {
- throw "ConvertPanoramaToCubemap: input cannot be null";
- }
- if (float32Array.length != inputWidth * inputHeight * 3) {
- throw "ConvertPanoramaToCubemap: input size is wrong";
- }
- var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
- var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
- var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
- var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
- var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
- var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
- return {
- front: textureFront,
- back: textureBack,
- left: textureLeft,
- right: textureRight,
- up: textureUp,
- down: textureDown,
- size: size
- };
- };
- PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
- var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
- var textureArray = new Float32Array(buffer);
- var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
- var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
- var dy = 1 / texSize;
- var fy = 0;
- for (var y = 0; y < texSize; y++) {
- var xv1 = faceData[0];
- var xv2 = faceData[2];
- for (var x = 0; x < texSize; x++) {
- var v = xv2.subtract(xv1).scale(fy).add(xv1);
- v.normalize();
- var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
- // 3 channels per pixels
- textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
- textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
- textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
- xv1 = xv1.add(rotDX1);
- xv2 = xv2.add(rotDX2);
- }
- fy += dy;
- }
- return textureArray;
- };
- PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
- var theta = Math.atan2(vDir.z, vDir.x);
- var phi = Math.acos(vDir.y);
- while (theta < -Math.PI)
- theta += 2 * Math.PI;
- while (theta > Math.PI)
- theta -= 2 * Math.PI;
- var dx = theta / Math.PI;
- var dy = phi / Math.PI;
- // recenter.
- dx = dx * 0.5 + 0.5;
- var px = Math.round(dx * inputWidth);
- if (px < 0)
- px = 0;
- else if (px >= inputWidth)
- px = inputWidth - 1;
- var py = Math.round(dy * inputHeight);
- if (py < 0)
- py = 0;
- else if (py >= inputHeight)
- py = inputHeight - 1;
- var inputY = (inputHeight - py - 1);
- var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
- var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
- var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
- return {
- r: r,
- g: g,
- b: b
- };
- };
- PanoramaToCubeMapTools.FACE_FRONT = [
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0)
- ];
- PanoramaToCubeMapTools.FACE_BACK = [
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_LEFT = [
- new BABYLON.Vector3(1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_RIGHT = [
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0),
- new BABYLON.Vector3(-1.0, 1.0, -1.0)
- ];
- PanoramaToCubeMapTools.FACE_UP = [
- new BABYLON.Vector3(-1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_DOWN = [
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, -1.0)
- ];
- return PanoramaToCubeMapTools;
- })();
- Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- ;
- var HDRTools = (function () {
- function HDRTools() {
- }
- HDRTools.Ldexp = function (mantissa, exponent) {
- if (exponent > 1023) {
- return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
- }
- if (exponent < -1074) {
- return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
- }
- return mantissa * Math.pow(2, exponent);
- };
- HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
- if (exponent > 0) {
- exponent = this.Ldexp(1.0, exponent - (128 + 8));
- float32array[index + 0] = red * exponent;
- float32array[index + 1] = green * exponent;
- float32array[index + 2] = blue * exponent;
- }
- else {
- float32array[index + 0] = 0;
- float32array[index + 1] = 0;
- float32array[index + 2] = 0;
- }
- };
- HDRTools.readStringLine = function (uint8array, startIndex) {
- var line = "";
- var character = "";
- for (var i = startIndex; i < uint8array.length - startIndex; i++) {
- character = String.fromCharCode(uint8array[i]);
- if (character == "\n") {
- break;
- }
- line += character;
- }
- return line;
- };
- /* minimal header reading. modify if you want to parse more information */
- HDRTools.RGBE_ReadHeader = function (uint8array) {
- var height = 0;
- var width = 0;
- var line = this.readStringLine(uint8array, 0);
- if (line[0] != '#' || line[1] != '?') {
- throw "Bad HDR Format.";
- }
- var endOfHeader = false;
- var findFormat = false;
- var lineIndex = 0;
- do {
- lineIndex += (line.length + 1);
- line = this.readStringLine(uint8array, lineIndex);
- if (line == "FORMAT=32-bit_rle_rgbe") {
- findFormat = true;
- }
- else if (line.length == 0) {
- endOfHeader = true;
- }
- } while (!endOfHeader);
- if (!findFormat) {
- throw "HDR Bad header format, unsupported FORMAT";
- }
- lineIndex += (line.length + 1);
- line = this.readStringLine(uint8array, lineIndex);
- var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
- var match = sizeRegexp.exec(line);
- // TODO. Support +Y and -X if needed.
- if (match.length < 3) {
- throw "HDR Bad header format, no size";
- }
- width = parseInt(match[2]);
- height = parseInt(match[1]);
- if (width < 8 || width > 0x7fff) {
- throw "HDR Bad header format, unsupported size";
- }
- lineIndex += (line.length + 1);
- return {
- height: height,
- width: width,
- dataPosition: lineIndex
- };
- };
- HDRTools.GetCubeMapTextureData = function (buffer, size) {
- var uint8array = new Uint8Array(buffer);
- var hdrInfo = this.RGBE_ReadHeader(uint8array);
- var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
- var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
- return cubeMapData;
- };
- HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
- // Keep for multi format supports.
- return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
- };
- HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
- var num_scanlines = hdrInfo.height;
- var scanline_width = hdrInfo.width;
- var a, b, c, d, count;
- var dataIndex = hdrInfo.dataPosition;
- var index = 0, endIndex = 0, i = 0;
- var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
- var scanLineArray = new Uint8Array(scanLineArrayBuffer);
- // 3 channels of 4 bytes per pixel in float.
- var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
- var resultArray = new Float32Array(resultBuffer);
- // read in each successive scanline
- while (num_scanlines > 0) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- c = uint8array[dataIndex++];
- d = uint8array[dataIndex++];
- if (a != 2 || b != 2 || (c & 0x80)) {
- // this file is not run length encoded
- throw "HDR Bad header format, not RLE";
- }
- if (((c << 8) | d) != scanline_width) {
- throw "HDR Bad header format, wrong scan line width";
- }
- index = 0;
- // read each of the four channels for the scanline into the buffer
- for (i = 0; i < 4; i++) {
- endIndex = (i + 1) * scanline_width;
- while (index < endIndex) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- if (a > 128) {
- // a run of the same value
- count = a - 128;
- if ((count == 0) || (count > endIndex - index)) {
- throw "HDR Bad Format, bad scanline data (run)";
- }
- while (count-- > 0) {
- scanLineArray[index++] = b;
- }
- }
- else {
- // a non-run
- count = a;
- if ((count == 0) || (count > endIndex - index)) {
- throw "HDR Bad Format, bad scanline data (non-run)";
- }
- scanLineArray[index++] = b;
- if (--count > 0) {
- for (var j = 0; j < count; j++) {
- scanLineArray[index++] = uint8array[dataIndex++];
- }
- }
- }
- }
- }
- // now convert data from buffer into floats
- for (i = 0; i < scanline_width; i++) {
- a = scanLineArray[i];
- b = scanLineArray[i + scanline_width];
- c = scanLineArray[i + 2 * scanline_width];
- d = scanLineArray[i + 3 * scanline_width];
- this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
- }
- num_scanlines--;
- }
- return resultArray;
- };
- return HDRTools;
- })();
- Internals.HDRTools = HDRTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var HDRCubeTexture = (function (_super) {
- __extends(HDRCubeTexture, _super);
- function HDRCubeTexture(url, scene, size, noMipmap) {
- _super.call(this, scene);
- this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
- this.sphericalPolynomial = null;
- this.name = url;
- this.url = url;
- this._noMipmap = noMipmap;
- this.hasAlpha = false;
- this._size = size;
- if (!url) {
- return;
- }
- this._texture = this._getFromCache(url, noMipmap);
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this.loadTexture();
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- this.isCube = true;
- this._textureMatrix = BABYLON.Matrix.Identity();
- }
- HDRCubeTexture.prototype.loadTexture = function () {
- var _this = this;
- var callback = function (buffer) {
- var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
- _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
- var mapping = [
- "left",
- "down",
- "front",
- "right",
- "up",
- "back"
- ];
- var results = [];
- for (var j = 0; j < 6; j++) {
- var dataFace = data[mapping[j]];
- // TODO. Support Int Textures...
- // // 3 channels of 1 bytes per pixel in bytes.
- // var byteBuffer = new ArrayBuffer(this._size * this._size * 3);
- // var byteArray = new Uint8Array(byteBuffer);
- //
- // /* now convert data from buffer into bytes */
- // for(var i = 0; i < this._size * this._size; i++) {
- // byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
- // byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
- // byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
- // }
- results.push(dataFace);
- }
- return results;
- };
- this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
- };
- HDRCubeTexture.prototype.clone = function () {
- var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap);
- // Base texture
- newTexture.level = this.level;
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- newTexture.coordinatesIndex = this.coordinatesIndex;
- newTexture.coordinatesMode = this.coordinatesMode;
- return newTexture;
- };
- // Methods
- HDRCubeTexture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap);
- if (!this._texture) {
- this.loadTexture();
- }
- };
- HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
- return this._textureMatrix;
- };
- HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
- var texture = null;
- if (parsedTexture.name && !parsedTexture.isRenderTarget) {
- texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size);
- texture.name = parsedTexture.name;
- texture.hasAlpha = parsedTexture.hasAlpha;
- texture.level = parsedTexture.level;
- texture.coordinatesMode = parsedTexture.coordinatesMode;
- }
- return texture;
- };
- HDRCubeTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.hasAlpha = this.hasAlpha;
- serializationObject.isCube = true;
- serializationObject.level = this.level;
- serializationObject.size = this._size;
- serializationObject.coordinatesMode = this.coordinatesMode;
- return serializationObject;
- };
- return HDRCubeTexture;
- })(BABYLON.BaseTexture);
- BABYLON.HDRCubeTexture = HDRCubeTexture;
- })(BABYLON || (BABYLON = {}));
- BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n#include<bumpFragmentFunctions>\r\n#include<clipPlaneFragmentDeclaration>\r\n#include<logDepthDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#include<logDepthFragment>\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#include<clipPlaneVertexDeclaration>\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#include<logDepthDeclaration>\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n#include<logDepthVertex>\r\n\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#include<fogVertexDeclaration>\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
- BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,c=0,y=0,p=0,l=0,x=0,z=0,w=-1,v=0,d=b.Vector3[0],g=0,T=b.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),y=Math.acos(g)*w,i.Dot(T,a)<0&&(y=Math.PI+y,T=T.scaleInPlace(-1),v++);var R=b.Vector3[2],_=b.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=y},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,E=h*y-a*c,S=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*E-r*S+o*q)*b,t.m[7]=(i*E-r*D+o*V)*b,t.m[11]=-(i*S-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],E=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*E,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*E,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*E,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*E,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0;\n},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,c=new e(0,0,0);n.decompose(u,m,c);var y=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.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,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,c)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var c=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=c;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var d=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),c=m.angle.radians()/e;m.orientation===x.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var f=Math.cos(y)*m.radius+m.centerPoint.x,l=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(f,l),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var c=u.normalize(),y=n-r;return new s(h.x+c.x*y,h.y+c.y*y)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=d;var g=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=g;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var _=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=_;var M=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=M;var F=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=F;var b=function(){function t(){}return t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=b}(BABYLON||(BABYLON={}));";
- BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif","bumpFragmentFunctions":"#ifdef BUMP\r\n\tvarying vec2 vBumpUV;\r\n\tuniform vec2 vBumpInfos;\r\n\tuniform sampler2D bumpSampler;\r\n\r\n\t// Thanks to http://www.thetenthplanet.de/archives/1180\r\n\tmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n\t{\r\n\t\t// get edge vectors of the pixel triangle\r\n\t\tvec3 dp1 = dFdx(p);\r\n\t\tvec3 dp2 = dFdy(p);\r\n\t\tvec2 duv1 = dFdx(uv);\r\n\t\tvec2 duv2 = dFdy(uv);\r\n\r\n\t\t// solve the linear system\r\n\t\tvec3 dp2perp = cross(dp2, normal);\r\n\t\tvec3 dp1perp = cross(normal, dp1);\r\n\t\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\t\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t\t// construct a scale-invariant frame \r\n\t\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\t\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n\t}\r\n\r\n\tvec3 perturbNormal(vec3 viewDir)\r\n\t{\r\n\t\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\t\tmap = map * 255. / 127. - 128. / 127.;\r\n\t\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\t\treturn normalize(TBN * map);\r\n\t}\r\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t{\r\n\t\tdiscard;\r\n\t}\r\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\r\n\tvarying float fClipDistance;\r\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\r\n\tuniform vec4 vClipPlane;\r\n\tvarying float fClipDistance;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\r\n\tuniform float logarithmicDepthConstant;\r\n\tvarying float vFragmentDepth;\r\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
- if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
- module.exports = BABYLON;
- };
|