three.module.js 973 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382
  1. // Polyfills
  2. if ( Number.EPSILON === undefined ) {
  3. Number.EPSILON = Math.pow( 2, - 52 );
  4. }
  5. if ( Number.isInteger === undefined ) {
  6. // Missing in IE
  7. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  8. Number.isInteger = function ( value ) {
  9. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  10. };
  11. }
  12. //
  13. if ( Math.sign === undefined ) {
  14. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  15. Math.sign = function ( x ) {
  16. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  17. };
  18. }
  19. if ( Function.prototype.name === undefined ) {
  20. // Missing in IE
  21. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  22. Object.defineProperty( Function.prototype, 'name', {
  23. get: function () {
  24. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  25. }
  26. } );
  27. }
  28. if ( Object.assign === undefined ) {
  29. // Missing in IE
  30. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  31. ( function () {
  32. Object.assign = function ( target ) {
  33. 'use strict';
  34. if ( target === undefined || target === null ) {
  35. throw new TypeError( 'Cannot convert undefined or null to object' );
  36. }
  37. var output = Object( target );
  38. for ( var index = 1; index < arguments.length; index ++ ) {
  39. var source = arguments[ index ];
  40. if ( source !== undefined && source !== null ) {
  41. for ( var nextKey in source ) {
  42. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  43. output[ nextKey ] = source[ nextKey ];
  44. }
  45. }
  46. }
  47. }
  48. return output;
  49. };
  50. } )();
  51. }
  52. /**
  53. * https://github.com/mrdoob/eventdispatcher.js/
  54. */
  55. function EventDispatcher() {}
  56. Object.assign( EventDispatcher.prototype, {
  57. addEventListener: function ( type, listener ) {
  58. if ( this._listeners === undefined ) this._listeners = {};
  59. var listeners = this._listeners;
  60. if ( listeners[ type ] === undefined ) {
  61. listeners[ type ] = [];
  62. }
  63. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  64. listeners[ type ].push( listener );
  65. }
  66. },
  67. hasEventListener: function ( type, listener ) {
  68. if ( this._listeners === undefined ) return false;
  69. var listeners = this._listeners;
  70. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  71. },
  72. removeEventListener: function ( type, listener ) {
  73. if ( this._listeners === undefined ) return;
  74. var listeners = this._listeners;
  75. var listenerArray = listeners[ type ];
  76. if ( listenerArray !== undefined ) {
  77. var index = listenerArray.indexOf( listener );
  78. if ( index !== - 1 ) {
  79. listenerArray.splice( index, 1 );
  80. }
  81. }
  82. },
  83. dispatchEvent: function ( event ) {
  84. if ( this._listeners === undefined ) return;
  85. var listeners = this._listeners;
  86. var listenerArray = listeners[ event.type ];
  87. if ( listenerArray !== undefined ) {
  88. event.target = this;
  89. var array = [], i = 0;
  90. var length = listenerArray.length;
  91. for ( i = 0; i < length; i ++ ) {
  92. array[ i ] = listenerArray[ i ];
  93. }
  94. for ( i = 0; i < length; i ++ ) {
  95. array[ i ].call( this, event );
  96. }
  97. }
  98. }
  99. } );
  100. var REVISION = '86dev';
  101. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  102. var CullFaceNone = 0;
  103. var CullFaceBack = 1;
  104. var CullFaceFront = 2;
  105. var CullFaceFrontBack = 3;
  106. var FrontFaceDirectionCW = 0;
  107. var FrontFaceDirectionCCW = 1;
  108. var BasicShadowMap = 0;
  109. var PCFShadowMap = 1;
  110. var PCFSoftShadowMap = 2;
  111. var FrontSide = 0;
  112. var BackSide = 1;
  113. var DoubleSide = 2;
  114. var FlatShading = 1;
  115. var SmoothShading = 2;
  116. var NoColors = 0;
  117. var FaceColors = 1;
  118. var VertexColors = 2;
  119. var NoBlending = 0;
  120. var NormalBlending = 1;
  121. var AdditiveBlending = 2;
  122. var SubtractiveBlending = 3;
  123. var MultiplyBlending = 4;
  124. var CustomBlending = 5;
  125. var AddEquation = 100;
  126. var SubtractEquation = 101;
  127. var ReverseSubtractEquation = 102;
  128. var MinEquation = 103;
  129. var MaxEquation = 104;
  130. var ZeroFactor = 200;
  131. var OneFactor = 201;
  132. var SrcColorFactor = 202;
  133. var OneMinusSrcColorFactor = 203;
  134. var SrcAlphaFactor = 204;
  135. var OneMinusSrcAlphaFactor = 205;
  136. var DstAlphaFactor = 206;
  137. var OneMinusDstAlphaFactor = 207;
  138. var DstColorFactor = 208;
  139. var OneMinusDstColorFactor = 209;
  140. var SrcAlphaSaturateFactor = 210;
  141. var NeverDepth = 0;
  142. var AlwaysDepth = 1;
  143. var LessDepth = 2;
  144. var LessEqualDepth = 3;
  145. var EqualDepth = 4;
  146. var GreaterEqualDepth = 5;
  147. var GreaterDepth = 6;
  148. var NotEqualDepth = 7;
  149. var MultiplyOperation = 0;
  150. var MixOperation = 1;
  151. var AddOperation = 2;
  152. var NoToneMapping = 0;
  153. var LinearToneMapping = 1;
  154. var ReinhardToneMapping = 2;
  155. var Uncharted2ToneMapping = 3;
  156. var CineonToneMapping = 4;
  157. var UVMapping = 300;
  158. var CubeReflectionMapping = 301;
  159. var CubeRefractionMapping = 302;
  160. var EquirectangularReflectionMapping = 303;
  161. var EquirectangularRefractionMapping = 304;
  162. var SphericalReflectionMapping = 305;
  163. var CubeUVReflectionMapping = 306;
  164. var CubeUVRefractionMapping = 307;
  165. var RepeatWrapping = 1000;
  166. var ClampToEdgeWrapping = 1001;
  167. var MirroredRepeatWrapping = 1002;
  168. var NearestFilter = 1003;
  169. var NearestMipMapNearestFilter = 1004;
  170. var NearestMipMapLinearFilter = 1005;
  171. var LinearFilter = 1006;
  172. var LinearMipMapNearestFilter = 1007;
  173. var LinearMipMapLinearFilter = 1008;
  174. var UnsignedByteType = 1009;
  175. var ByteType = 1010;
  176. var ShortType = 1011;
  177. var UnsignedShortType = 1012;
  178. var IntType = 1013;
  179. var UnsignedIntType = 1014;
  180. var FloatType = 1015;
  181. var HalfFloatType = 1016;
  182. var UnsignedShort4444Type = 1017;
  183. var UnsignedShort5551Type = 1018;
  184. var UnsignedShort565Type = 1019;
  185. var UnsignedInt248Type = 1020;
  186. var AlphaFormat = 1021;
  187. var RGBFormat = 1022;
  188. var RGBAFormat = 1023;
  189. var LuminanceFormat = 1024;
  190. var LuminanceAlphaFormat = 1025;
  191. var RGBEFormat = RGBAFormat;
  192. var DepthFormat = 1026;
  193. var DepthStencilFormat = 1027;
  194. var RGB_S3TC_DXT1_Format = 2001;
  195. var RGBA_S3TC_DXT1_Format = 2002;
  196. var RGBA_S3TC_DXT3_Format = 2003;
  197. var RGBA_S3TC_DXT5_Format = 2004;
  198. var RGB_PVRTC_4BPPV1_Format = 2100;
  199. var RGB_PVRTC_2BPPV1_Format = 2101;
  200. var RGBA_PVRTC_4BPPV1_Format = 2102;
  201. var RGBA_PVRTC_2BPPV1_Format = 2103;
  202. var RGB_ETC1_Format = 2151;
  203. var LoopOnce = 2200;
  204. var LoopRepeat = 2201;
  205. var LoopPingPong = 2202;
  206. var InterpolateDiscrete = 2300;
  207. var InterpolateLinear = 2301;
  208. var InterpolateSmooth = 2302;
  209. var ZeroCurvatureEnding = 2400;
  210. var ZeroSlopeEnding = 2401;
  211. var WrapAroundEnding = 2402;
  212. var TrianglesDrawMode = 0;
  213. var TriangleStripDrawMode = 1;
  214. var TriangleFanDrawMode = 2;
  215. var LinearEncoding = 3000;
  216. var sRGBEncoding = 3001;
  217. var GammaEncoding = 3007;
  218. var RGBEEncoding = 3002;
  219. var LogLuvEncoding = 3003;
  220. var RGBM7Encoding = 3004;
  221. var RGBM16Encoding = 3005;
  222. var RGBDEncoding = 3006;
  223. var BasicDepthPacking = 3200;
  224. var RGBADepthPacking = 3201;
  225. /**
  226. * @author alteredq / http://alteredqualia.com/
  227. * @author mrdoob / http://mrdoob.com/
  228. */
  229. var _Math = {
  230. DEG2RAD: Math.PI / 180,
  231. RAD2DEG: 180 / Math.PI,
  232. generateUUID: function () {
  233. // http://www.broofa.com/Tools/Math.uuid.htm
  234. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  235. var uuid = new Array( 36 );
  236. var rnd = 0, r;
  237. return function generateUUID() {
  238. for ( var i = 0; i < 36; i ++ ) {
  239. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  240. uuid[ i ] = '-';
  241. } else if ( i === 14 ) {
  242. uuid[ i ] = '4';
  243. } else {
  244. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  245. r = rnd & 0xf;
  246. rnd = rnd >> 4;
  247. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  248. }
  249. }
  250. return uuid.join( '' );
  251. };
  252. }(),
  253. clamp: function ( value, min, max ) {
  254. return Math.max( min, Math.min( max, value ) );
  255. },
  256. // compute euclidian modulo of m % n
  257. // https://en.wikipedia.org/wiki/Modulo_operation
  258. euclideanModulo: function ( n, m ) {
  259. return ( ( n % m ) + m ) % m;
  260. },
  261. // Linear mapping from range <a1, a2> to range <b1, b2>
  262. mapLinear: function ( x, a1, a2, b1, b2 ) {
  263. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  264. },
  265. // https://en.wikipedia.org/wiki/Linear_interpolation
  266. lerp: function ( x, y, t ) {
  267. return ( 1 - t ) * x + t * y;
  268. },
  269. // http://en.wikipedia.org/wiki/Smoothstep
  270. smoothstep: function ( x, min, max ) {
  271. if ( x <= min ) return 0;
  272. if ( x >= max ) return 1;
  273. x = ( x - min ) / ( max - min );
  274. return x * x * ( 3 - 2 * x );
  275. },
  276. smootherstep: function ( x, min, max ) {
  277. if ( x <= min ) return 0;
  278. if ( x >= max ) return 1;
  279. x = ( x - min ) / ( max - min );
  280. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  281. },
  282. // Random integer from <low, high> interval
  283. randInt: function ( low, high ) {
  284. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  285. },
  286. // Random float from <low, high> interval
  287. randFloat: function ( low, high ) {
  288. return low + Math.random() * ( high - low );
  289. },
  290. // Random float from <-range/2, range/2> interval
  291. randFloatSpread: function ( range ) {
  292. return range * ( 0.5 - Math.random() );
  293. },
  294. degToRad: function ( degrees ) {
  295. return degrees * _Math.DEG2RAD;
  296. },
  297. radToDeg: function ( radians ) {
  298. return radians * _Math.RAD2DEG;
  299. },
  300. isPowerOfTwo: function ( value ) {
  301. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  302. },
  303. nearestPowerOfTwo: function ( value ) {
  304. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  305. },
  306. nextPowerOfTwo: function ( value ) {
  307. value --;
  308. value |= value >> 1;
  309. value |= value >> 2;
  310. value |= value >> 4;
  311. value |= value >> 8;
  312. value |= value >> 16;
  313. value ++;
  314. return value;
  315. }
  316. };
  317. /**
  318. * @author mrdoob / http://mrdoob.com/
  319. * @author philogb / http://blog.thejit.org/
  320. * @author egraether / http://egraether.com/
  321. * @author zz85 / http://www.lab4games.net/zz85/blog
  322. */
  323. function Vector2( x, y ) {
  324. this.x = x || 0;
  325. this.y = y || 0;
  326. }
  327. Object.defineProperties( Vector2.prototype, {
  328. "width" : {
  329. get: function () {
  330. return this.x;
  331. },
  332. set: function ( value ) {
  333. this.x = value;
  334. }
  335. },
  336. "height" : {
  337. get: function () {
  338. return this.y;
  339. },
  340. set: function ( value ) {
  341. this.y = value;
  342. }
  343. }
  344. } );
  345. Object.assign( Vector2.prototype, {
  346. isVector2: true,
  347. set: function ( x, y ) {
  348. this.x = x;
  349. this.y = y;
  350. return this;
  351. },
  352. setScalar: function ( scalar ) {
  353. this.x = scalar;
  354. this.y = scalar;
  355. return this;
  356. },
  357. setX: function ( x ) {
  358. this.x = x;
  359. return this;
  360. },
  361. setY: function ( y ) {
  362. this.y = y;
  363. return this;
  364. },
  365. setComponent: function ( index, value ) {
  366. switch ( index ) {
  367. case 0: this.x = value; break;
  368. case 1: this.y = value; break;
  369. default: throw new Error( 'index is out of range: ' + index );
  370. }
  371. return this;
  372. },
  373. getComponent: function ( index ) {
  374. switch ( index ) {
  375. case 0: return this.x;
  376. case 1: return this.y;
  377. default: throw new Error( 'index is out of range: ' + index );
  378. }
  379. },
  380. clone: function () {
  381. return new this.constructor( this.x, this.y );
  382. },
  383. copy: function ( v ) {
  384. this.x = v.x;
  385. this.y = v.y;
  386. return this;
  387. },
  388. add: function ( v, w ) {
  389. if ( w !== undefined ) {
  390. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  391. return this.addVectors( v, w );
  392. }
  393. this.x += v.x;
  394. this.y += v.y;
  395. return this;
  396. },
  397. addScalar: function ( s ) {
  398. this.x += s;
  399. this.y += s;
  400. return this;
  401. },
  402. addVectors: function ( a, b ) {
  403. this.x = a.x + b.x;
  404. this.y = a.y + b.y;
  405. return this;
  406. },
  407. addScaledVector: function ( v, s ) {
  408. this.x += v.x * s;
  409. this.y += v.y * s;
  410. return this;
  411. },
  412. sub: function ( v, w ) {
  413. if ( w !== undefined ) {
  414. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  415. return this.subVectors( v, w );
  416. }
  417. this.x -= v.x;
  418. this.y -= v.y;
  419. return this;
  420. },
  421. subScalar: function ( s ) {
  422. this.x -= s;
  423. this.y -= s;
  424. return this;
  425. },
  426. subVectors: function ( a, b ) {
  427. this.x = a.x - b.x;
  428. this.y = a.y - b.y;
  429. return this;
  430. },
  431. multiply: function ( v ) {
  432. this.x *= v.x;
  433. this.y *= v.y;
  434. return this;
  435. },
  436. multiplyScalar: function ( scalar ) {
  437. this.x *= scalar;
  438. this.y *= scalar;
  439. return this;
  440. },
  441. divide: function ( v ) {
  442. this.x /= v.x;
  443. this.y /= v.y;
  444. return this;
  445. },
  446. divideScalar: function ( scalar ) {
  447. return this.multiplyScalar( 1 / scalar );
  448. },
  449. min: function ( v ) {
  450. this.x = Math.min( this.x, v.x );
  451. this.y = Math.min( this.y, v.y );
  452. return this;
  453. },
  454. max: function ( v ) {
  455. this.x = Math.max( this.x, v.x );
  456. this.y = Math.max( this.y, v.y );
  457. return this;
  458. },
  459. clamp: function ( min, max ) {
  460. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  461. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  462. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  463. return this;
  464. },
  465. clampScalar: function () {
  466. var min, max;
  467. return function clampScalar( minVal, maxVal ) {
  468. if ( min === undefined ) {
  469. min = new Vector2();
  470. max = new Vector2();
  471. }
  472. min.set( minVal, minVal );
  473. max.set( maxVal, maxVal );
  474. return this.clamp( min, max );
  475. };
  476. }(),
  477. clampLength: function ( min, max ) {
  478. var length = this.length();
  479. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  480. },
  481. floor: function () {
  482. this.x = Math.floor( this.x );
  483. this.y = Math.floor( this.y );
  484. return this;
  485. },
  486. ceil: function () {
  487. this.x = Math.ceil( this.x );
  488. this.y = Math.ceil( this.y );
  489. return this;
  490. },
  491. round: function () {
  492. this.x = Math.round( this.x );
  493. this.y = Math.round( this.y );
  494. return this;
  495. },
  496. roundToZero: function () {
  497. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  498. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  499. return this;
  500. },
  501. negate: function () {
  502. this.x = - this.x;
  503. this.y = - this.y;
  504. return this;
  505. },
  506. dot: function ( v ) {
  507. return this.x * v.x + this.y * v.y;
  508. },
  509. lengthSq: function () {
  510. return this.x * this.x + this.y * this.y;
  511. },
  512. length: function () {
  513. return Math.sqrt( this.x * this.x + this.y * this.y );
  514. },
  515. lengthManhattan: function() {
  516. return Math.abs( this.x ) + Math.abs( this.y );
  517. },
  518. normalize: function () {
  519. return this.divideScalar( this.length() );
  520. },
  521. angle: function () {
  522. // computes the angle in radians with respect to the positive x-axis
  523. var angle = Math.atan2( this.y, this.x );
  524. if ( angle < 0 ) angle += 2 * Math.PI;
  525. return angle;
  526. },
  527. distanceTo: function ( v ) {
  528. return Math.sqrt( this.distanceToSquared( v ) );
  529. },
  530. distanceToSquared: function ( v ) {
  531. var dx = this.x - v.x, dy = this.y - v.y;
  532. return dx * dx + dy * dy;
  533. },
  534. distanceToManhattan: function ( v ) {
  535. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  536. },
  537. setLength: function ( length ) {
  538. return this.multiplyScalar( length / this.length() );
  539. },
  540. lerp: function ( v, alpha ) {
  541. this.x += ( v.x - this.x ) * alpha;
  542. this.y += ( v.y - this.y ) * alpha;
  543. return this;
  544. },
  545. lerpVectors: function ( v1, v2, alpha ) {
  546. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  547. },
  548. equals: function ( v ) {
  549. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  550. },
  551. fromArray: function ( array, offset ) {
  552. if ( offset === undefined ) offset = 0;
  553. this.x = array[ offset ];
  554. this.y = array[ offset + 1 ];
  555. return this;
  556. },
  557. toArray: function ( array, offset ) {
  558. if ( array === undefined ) array = [];
  559. if ( offset === undefined ) offset = 0;
  560. array[ offset ] = this.x;
  561. array[ offset + 1 ] = this.y;
  562. return array;
  563. },
  564. fromBufferAttribute: function ( attribute, index, offset ) {
  565. if ( offset !== undefined ) {
  566. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  567. }
  568. this.x = attribute.getX( index );
  569. this.y = attribute.getY( index );
  570. return this;
  571. },
  572. rotateAround: function ( center, angle ) {
  573. var c = Math.cos( angle ), s = Math.sin( angle );
  574. var x = this.x - center.x;
  575. var y = this.y - center.y;
  576. this.x = x * c - y * s + center.x;
  577. this.y = x * s + y * c + center.y;
  578. return this;
  579. }
  580. } );
  581. /**
  582. * @author mrdoob / http://mrdoob.com/
  583. * @author alteredq / http://alteredqualia.com/
  584. * @author szimek / https://github.com/szimek/
  585. */
  586. var textureId = 0;
  587. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  588. Object.defineProperty( this, 'id', { value: textureId ++ } );
  589. this.uuid = _Math.generateUUID();
  590. this.name = '';
  591. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  592. this.mipmaps = [];
  593. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  594. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  595. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  596. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  597. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  598. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  599. this.format = format !== undefined ? format : RGBAFormat;
  600. this.type = type !== undefined ? type : UnsignedByteType;
  601. this.offset = new Vector2( 0, 0 );
  602. this.repeat = new Vector2( 1, 1 );
  603. this.generateMipmaps = true;
  604. this.premultiplyAlpha = false;
  605. this.flipY = true;
  606. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  607. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  608. //
  609. // Also changing the encoding after already used by a Material will not automatically make the Material
  610. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  611. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  612. this.version = 0;
  613. this.onUpdate = null;
  614. }
  615. Texture.DEFAULT_IMAGE = undefined;
  616. Texture.DEFAULT_MAPPING = UVMapping;
  617. Object.defineProperty( Texture.prototype, "needsUpdate", {
  618. set: function ( value ) {
  619. if ( value === true ) this.version ++;
  620. }
  621. } );
  622. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  623. constructor: Texture,
  624. isTexture: true,
  625. clone: function () {
  626. return new this.constructor().copy( this );
  627. },
  628. copy: function ( source ) {
  629. this.name = source.name;
  630. this.image = source.image;
  631. this.mipmaps = source.mipmaps.slice( 0 );
  632. this.mapping = source.mapping;
  633. this.wrapS = source.wrapS;
  634. this.wrapT = source.wrapT;
  635. this.magFilter = source.magFilter;
  636. this.minFilter = source.minFilter;
  637. this.anisotropy = source.anisotropy;
  638. this.format = source.format;
  639. this.type = source.type;
  640. this.offset.copy( source.offset );
  641. this.repeat.copy( source.repeat );
  642. this.generateMipmaps = source.generateMipmaps;
  643. this.premultiplyAlpha = source.premultiplyAlpha;
  644. this.flipY = source.flipY;
  645. this.unpackAlignment = source.unpackAlignment;
  646. this.encoding = source.encoding;
  647. return this;
  648. },
  649. toJSON: function ( meta ) {
  650. if ( meta.textures[ this.uuid ] !== undefined ) {
  651. return meta.textures[ this.uuid ];
  652. }
  653. function getDataURL( image ) {
  654. var canvas;
  655. if ( image.toDataURL !== undefined ) {
  656. canvas = image;
  657. } else {
  658. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  659. canvas.width = image.width;
  660. canvas.height = image.height;
  661. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  662. }
  663. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  664. return canvas.toDataURL( 'image/jpeg', 0.6 );
  665. } else {
  666. return canvas.toDataURL( 'image/png' );
  667. }
  668. }
  669. var output = {
  670. metadata: {
  671. version: 4.5,
  672. type: 'Texture',
  673. generator: 'Texture.toJSON'
  674. },
  675. uuid: this.uuid,
  676. name: this.name,
  677. mapping: this.mapping,
  678. repeat: [ this.repeat.x, this.repeat.y ],
  679. offset: [ this.offset.x, this.offset.y ],
  680. wrap: [ this.wrapS, this.wrapT ],
  681. minFilter: this.minFilter,
  682. magFilter: this.magFilter,
  683. anisotropy: this.anisotropy,
  684. flipY: this.flipY
  685. };
  686. if ( this.image !== undefined ) {
  687. // TODO: Move to THREE.Image
  688. var image = this.image;
  689. if ( image.uuid === undefined ) {
  690. image.uuid = _Math.generateUUID(); // UGH
  691. }
  692. if ( meta.images[ image.uuid ] === undefined ) {
  693. meta.images[ image.uuid ] = {
  694. uuid: image.uuid,
  695. url: getDataURL( image )
  696. };
  697. }
  698. output.image = image.uuid;
  699. }
  700. meta.textures[ this.uuid ] = output;
  701. return output;
  702. },
  703. dispose: function () {
  704. this.dispatchEvent( { type: 'dispose' } );
  705. },
  706. transformUv: function ( uv ) {
  707. if ( this.mapping !== UVMapping ) return;
  708. uv.multiply( this.repeat );
  709. uv.add( this.offset );
  710. if ( uv.x < 0 || uv.x > 1 ) {
  711. switch ( this.wrapS ) {
  712. case RepeatWrapping:
  713. uv.x = uv.x - Math.floor( uv.x );
  714. break;
  715. case ClampToEdgeWrapping:
  716. uv.x = uv.x < 0 ? 0 : 1;
  717. break;
  718. case MirroredRepeatWrapping:
  719. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  720. uv.x = Math.ceil( uv.x ) - uv.x;
  721. } else {
  722. uv.x = uv.x - Math.floor( uv.x );
  723. }
  724. break;
  725. }
  726. }
  727. if ( uv.y < 0 || uv.y > 1 ) {
  728. switch ( this.wrapT ) {
  729. case RepeatWrapping:
  730. uv.y = uv.y - Math.floor( uv.y );
  731. break;
  732. case ClampToEdgeWrapping:
  733. uv.y = uv.y < 0 ? 0 : 1;
  734. break;
  735. case MirroredRepeatWrapping:
  736. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  737. uv.y = Math.ceil( uv.y ) - uv.y;
  738. } else {
  739. uv.y = uv.y - Math.floor( uv.y );
  740. }
  741. break;
  742. }
  743. }
  744. if ( this.flipY ) {
  745. uv.y = 1 - uv.y;
  746. }
  747. }
  748. } );
  749. /**
  750. * @author supereggbert / http://www.paulbrunt.co.uk/
  751. * @author philogb / http://blog.thejit.org/
  752. * @author mikael emtinger / http://gomo.se/
  753. * @author egraether / http://egraether.com/
  754. * @author WestLangley / http://github.com/WestLangley
  755. */
  756. function Vector4( x, y, z, w ) {
  757. this.x = x || 0;
  758. this.y = y || 0;
  759. this.z = z || 0;
  760. this.w = ( w !== undefined ) ? w : 1;
  761. }
  762. Object.assign( Vector4.prototype, {
  763. isVector4: true,
  764. set: function ( x, y, z, w ) {
  765. this.x = x;
  766. this.y = y;
  767. this.z = z;
  768. this.w = w;
  769. return this;
  770. },
  771. setScalar: function ( scalar ) {
  772. this.x = scalar;
  773. this.y = scalar;
  774. this.z = scalar;
  775. this.w = scalar;
  776. return this;
  777. },
  778. setX: function ( x ) {
  779. this.x = x;
  780. return this;
  781. },
  782. setY: function ( y ) {
  783. this.y = y;
  784. return this;
  785. },
  786. setZ: function ( z ) {
  787. this.z = z;
  788. return this;
  789. },
  790. setW: function ( w ) {
  791. this.w = w;
  792. return this;
  793. },
  794. setComponent: function ( index, value ) {
  795. switch ( index ) {
  796. case 0: this.x = value; break;
  797. case 1: this.y = value; break;
  798. case 2: this.z = value; break;
  799. case 3: this.w = value; break;
  800. default: throw new Error( 'index is out of range: ' + index );
  801. }
  802. return this;
  803. },
  804. getComponent: function ( index ) {
  805. switch ( index ) {
  806. case 0: return this.x;
  807. case 1: return this.y;
  808. case 2: return this.z;
  809. case 3: return this.w;
  810. default: throw new Error( 'index is out of range: ' + index );
  811. }
  812. },
  813. clone: function () {
  814. return new this.constructor( this.x, this.y, this.z, this.w );
  815. },
  816. copy: function ( v ) {
  817. this.x = v.x;
  818. this.y = v.y;
  819. this.z = v.z;
  820. this.w = ( v.w !== undefined ) ? v.w : 1;
  821. return this;
  822. },
  823. add: function ( v, w ) {
  824. if ( w !== undefined ) {
  825. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  826. return this.addVectors( v, w );
  827. }
  828. this.x += v.x;
  829. this.y += v.y;
  830. this.z += v.z;
  831. this.w += v.w;
  832. return this;
  833. },
  834. addScalar: function ( s ) {
  835. this.x += s;
  836. this.y += s;
  837. this.z += s;
  838. this.w += s;
  839. return this;
  840. },
  841. addVectors: function ( a, b ) {
  842. this.x = a.x + b.x;
  843. this.y = a.y + b.y;
  844. this.z = a.z + b.z;
  845. this.w = a.w + b.w;
  846. return this;
  847. },
  848. addScaledVector: function ( v, s ) {
  849. this.x += v.x * s;
  850. this.y += v.y * s;
  851. this.z += v.z * s;
  852. this.w += v.w * s;
  853. return this;
  854. },
  855. sub: function ( v, w ) {
  856. if ( w !== undefined ) {
  857. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  858. return this.subVectors( v, w );
  859. }
  860. this.x -= v.x;
  861. this.y -= v.y;
  862. this.z -= v.z;
  863. this.w -= v.w;
  864. return this;
  865. },
  866. subScalar: function ( s ) {
  867. this.x -= s;
  868. this.y -= s;
  869. this.z -= s;
  870. this.w -= s;
  871. return this;
  872. },
  873. subVectors: function ( a, b ) {
  874. this.x = a.x - b.x;
  875. this.y = a.y - b.y;
  876. this.z = a.z - b.z;
  877. this.w = a.w - b.w;
  878. return this;
  879. },
  880. multiplyScalar: function ( scalar ) {
  881. this.x *= scalar;
  882. this.y *= scalar;
  883. this.z *= scalar;
  884. this.w *= scalar;
  885. return this;
  886. },
  887. applyMatrix4: function ( m ) {
  888. var x = this.x, y = this.y, z = this.z, w = this.w;
  889. var e = m.elements;
  890. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  891. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  892. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  893. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  894. return this;
  895. },
  896. divideScalar: function ( scalar ) {
  897. return this.multiplyScalar( 1 / scalar );
  898. },
  899. setAxisAngleFromQuaternion: function ( q ) {
  900. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  901. // q is assumed to be normalized
  902. this.w = 2 * Math.acos( q.w );
  903. var s = Math.sqrt( 1 - q.w * q.w );
  904. if ( s < 0.0001 ) {
  905. this.x = 1;
  906. this.y = 0;
  907. this.z = 0;
  908. } else {
  909. this.x = q.x / s;
  910. this.y = q.y / s;
  911. this.z = q.z / s;
  912. }
  913. return this;
  914. },
  915. setAxisAngleFromRotationMatrix: function ( m ) {
  916. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  917. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  918. var angle, x, y, z, // variables for result
  919. epsilon = 0.01, // margin to allow for rounding errors
  920. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  921. te = m.elements,
  922. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  923. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  924. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  925. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  926. ( Math.abs( m13 - m31 ) < epsilon ) &&
  927. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  928. // singularity found
  929. // first check for identity matrix which must have +1 for all terms
  930. // in leading diagonal and zero in other terms
  931. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  932. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  933. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  934. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  935. // this singularity is identity matrix so angle = 0
  936. this.set( 1, 0, 0, 0 );
  937. return this; // zero angle, arbitrary axis
  938. }
  939. // otherwise this singularity is angle = 180
  940. angle = Math.PI;
  941. var xx = ( m11 + 1 ) / 2;
  942. var yy = ( m22 + 1 ) / 2;
  943. var zz = ( m33 + 1 ) / 2;
  944. var xy = ( m12 + m21 ) / 4;
  945. var xz = ( m13 + m31 ) / 4;
  946. var yz = ( m23 + m32 ) / 4;
  947. if ( ( xx > yy ) && ( xx > zz ) ) {
  948. // m11 is the largest diagonal term
  949. if ( xx < epsilon ) {
  950. x = 0;
  951. y = 0.707106781;
  952. z = 0.707106781;
  953. } else {
  954. x = Math.sqrt( xx );
  955. y = xy / x;
  956. z = xz / x;
  957. }
  958. } else if ( yy > zz ) {
  959. // m22 is the largest diagonal term
  960. if ( yy < epsilon ) {
  961. x = 0.707106781;
  962. y = 0;
  963. z = 0.707106781;
  964. } else {
  965. y = Math.sqrt( yy );
  966. x = xy / y;
  967. z = yz / y;
  968. }
  969. } else {
  970. // m33 is the largest diagonal term so base result on this
  971. if ( zz < epsilon ) {
  972. x = 0.707106781;
  973. y = 0.707106781;
  974. z = 0;
  975. } else {
  976. z = Math.sqrt( zz );
  977. x = xz / z;
  978. y = yz / z;
  979. }
  980. }
  981. this.set( x, y, z, angle );
  982. return this; // return 180 deg rotation
  983. }
  984. // as we have reached here there are no singularities so we can handle normally
  985. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  986. ( m13 - m31 ) * ( m13 - m31 ) +
  987. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  988. if ( Math.abs( s ) < 0.001 ) s = 1;
  989. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  990. // caught by singularity test above, but I've left it in just in case
  991. this.x = ( m32 - m23 ) / s;
  992. this.y = ( m13 - m31 ) / s;
  993. this.z = ( m21 - m12 ) / s;
  994. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  995. return this;
  996. },
  997. min: function ( v ) {
  998. this.x = Math.min( this.x, v.x );
  999. this.y = Math.min( this.y, v.y );
  1000. this.z = Math.min( this.z, v.z );
  1001. this.w = Math.min( this.w, v.w );
  1002. return this;
  1003. },
  1004. max: function ( v ) {
  1005. this.x = Math.max( this.x, v.x );
  1006. this.y = Math.max( this.y, v.y );
  1007. this.z = Math.max( this.z, v.z );
  1008. this.w = Math.max( this.w, v.w );
  1009. return this;
  1010. },
  1011. clamp: function ( min, max ) {
  1012. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1013. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1014. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1015. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1016. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1017. return this;
  1018. },
  1019. clampScalar: function () {
  1020. var min = new Vector4();
  1021. var max = new Vector4();
  1022. return function clampScalar( minVal, maxVal ) {
  1023. min.set( minVal, minVal, minVal, minVal );
  1024. max.set( maxVal, maxVal, maxVal, maxVal );
  1025. return this.clamp( min, max );
  1026. };
  1027. }(),
  1028. floor: function () {
  1029. this.x = Math.floor( this.x );
  1030. this.y = Math.floor( this.y );
  1031. this.z = Math.floor( this.z );
  1032. this.w = Math.floor( this.w );
  1033. return this;
  1034. },
  1035. ceil: function () {
  1036. this.x = Math.ceil( this.x );
  1037. this.y = Math.ceil( this.y );
  1038. this.z = Math.ceil( this.z );
  1039. this.w = Math.ceil( this.w );
  1040. return this;
  1041. },
  1042. round: function () {
  1043. this.x = Math.round( this.x );
  1044. this.y = Math.round( this.y );
  1045. this.z = Math.round( this.z );
  1046. this.w = Math.round( this.w );
  1047. return this;
  1048. },
  1049. roundToZero: function () {
  1050. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1051. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1052. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1053. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1054. return this;
  1055. },
  1056. negate: function () {
  1057. this.x = - this.x;
  1058. this.y = - this.y;
  1059. this.z = - this.z;
  1060. this.w = - this.w;
  1061. return this;
  1062. },
  1063. dot: function ( v ) {
  1064. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1065. },
  1066. lengthSq: function () {
  1067. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1068. },
  1069. length: function () {
  1070. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1071. },
  1072. lengthManhattan: function () {
  1073. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1074. },
  1075. normalize: function () {
  1076. return this.divideScalar( this.length() );
  1077. },
  1078. setLength: function ( length ) {
  1079. return this.multiplyScalar( length / this.length() );
  1080. },
  1081. lerp: function ( v, alpha ) {
  1082. this.x += ( v.x - this.x ) * alpha;
  1083. this.y += ( v.y - this.y ) * alpha;
  1084. this.z += ( v.z - this.z ) * alpha;
  1085. this.w += ( v.w - this.w ) * alpha;
  1086. return this;
  1087. },
  1088. lerpVectors: function ( v1, v2, alpha ) {
  1089. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1090. },
  1091. equals: function ( v ) {
  1092. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1093. },
  1094. fromArray: function ( array, offset ) {
  1095. if ( offset === undefined ) offset = 0;
  1096. this.x = array[ offset ];
  1097. this.y = array[ offset + 1 ];
  1098. this.z = array[ offset + 2 ];
  1099. this.w = array[ offset + 3 ];
  1100. return this;
  1101. },
  1102. toArray: function ( array, offset ) {
  1103. if ( array === undefined ) array = [];
  1104. if ( offset === undefined ) offset = 0;
  1105. array[ offset ] = this.x;
  1106. array[ offset + 1 ] = this.y;
  1107. array[ offset + 2 ] = this.z;
  1108. array[ offset + 3 ] = this.w;
  1109. return array;
  1110. },
  1111. fromBufferAttribute: function ( attribute, index, offset ) {
  1112. if ( offset !== undefined ) {
  1113. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1114. }
  1115. this.x = attribute.getX( index );
  1116. this.y = attribute.getY( index );
  1117. this.z = attribute.getZ( index );
  1118. this.w = attribute.getW( index );
  1119. return this;
  1120. }
  1121. } );
  1122. /**
  1123. * @author szimek / https://github.com/szimek/
  1124. * @author alteredq / http://alteredqualia.com/
  1125. * @author Marius Kintel / https://github.com/kintel
  1126. */
  1127. /*
  1128. In options, we can specify:
  1129. * Texture parameters for an auto-generated target texture
  1130. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1131. */
  1132. function WebGLRenderTarget( width, height, options ) {
  1133. this.uuid = _Math.generateUUID();
  1134. this.width = width;
  1135. this.height = height;
  1136. this.scissor = new Vector4( 0, 0, width, height );
  1137. this.scissorTest = false;
  1138. this.viewport = new Vector4( 0, 0, width, height );
  1139. options = options || {};
  1140. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1141. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1142. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1143. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1144. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1145. }
  1146. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1147. isWebGLRenderTarget: true,
  1148. setSize: function ( width, height ) {
  1149. if ( this.width !== width || this.height !== height ) {
  1150. this.width = width;
  1151. this.height = height;
  1152. this.dispose();
  1153. }
  1154. this.viewport.set( 0, 0, width, height );
  1155. this.scissor.set( 0, 0, width, height );
  1156. },
  1157. clone: function () {
  1158. return new this.constructor().copy( this );
  1159. },
  1160. copy: function ( source ) {
  1161. this.width = source.width;
  1162. this.height = source.height;
  1163. this.viewport.copy( source.viewport );
  1164. this.texture = source.texture.clone();
  1165. this.depthBuffer = source.depthBuffer;
  1166. this.stencilBuffer = source.stencilBuffer;
  1167. this.depthTexture = source.depthTexture;
  1168. return this;
  1169. },
  1170. dispose: function () {
  1171. this.dispatchEvent( { type: 'dispose' } );
  1172. }
  1173. } );
  1174. /**
  1175. * @author alteredq / http://alteredqualia.com
  1176. */
  1177. function WebGLRenderTargetCube( width, height, options ) {
  1178. WebGLRenderTarget.call( this, width, height, options );
  1179. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1180. this.activeMipMapLevel = 0;
  1181. }
  1182. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1183. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1184. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1185. /**
  1186. * @author mikael emtinger / http://gomo.se/
  1187. * @author alteredq / http://alteredqualia.com/
  1188. * @author WestLangley / http://github.com/WestLangley
  1189. * @author bhouston / http://clara.io
  1190. */
  1191. function Quaternion( x, y, z, w ) {
  1192. this._x = x || 0;
  1193. this._y = y || 0;
  1194. this._z = z || 0;
  1195. this._w = ( w !== undefined ) ? w : 1;
  1196. }
  1197. Object.assign( Quaternion, {
  1198. slerp: function ( qa, qb, qm, t ) {
  1199. return qm.copy( qa ).slerp( qb, t );
  1200. },
  1201. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1202. // fuzz-free, array-based Quaternion SLERP operation
  1203. var x0 = src0[ srcOffset0 + 0 ],
  1204. y0 = src0[ srcOffset0 + 1 ],
  1205. z0 = src0[ srcOffset0 + 2 ],
  1206. w0 = src0[ srcOffset0 + 3 ],
  1207. x1 = src1[ srcOffset1 + 0 ],
  1208. y1 = src1[ srcOffset1 + 1 ],
  1209. z1 = src1[ srcOffset1 + 2 ],
  1210. w1 = src1[ srcOffset1 + 3 ];
  1211. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1212. var s = 1 - t,
  1213. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1214. dir = ( cos >= 0 ? 1 : - 1 ),
  1215. sqrSin = 1 - cos * cos;
  1216. // Skip the Slerp for tiny steps to avoid numeric problems:
  1217. if ( sqrSin > Number.EPSILON ) {
  1218. var sin = Math.sqrt( sqrSin ),
  1219. len = Math.atan2( sin, cos * dir );
  1220. s = Math.sin( s * len ) / sin;
  1221. t = Math.sin( t * len ) / sin;
  1222. }
  1223. var tDir = t * dir;
  1224. x0 = x0 * s + x1 * tDir;
  1225. y0 = y0 * s + y1 * tDir;
  1226. z0 = z0 * s + z1 * tDir;
  1227. w0 = w0 * s + w1 * tDir;
  1228. // Normalize in case we just did a lerp:
  1229. if ( s === 1 - t ) {
  1230. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1231. x0 *= f;
  1232. y0 *= f;
  1233. z0 *= f;
  1234. w0 *= f;
  1235. }
  1236. }
  1237. dst[ dstOffset ] = x0;
  1238. dst[ dstOffset + 1 ] = y0;
  1239. dst[ dstOffset + 2 ] = z0;
  1240. dst[ dstOffset + 3 ] = w0;
  1241. }
  1242. } );
  1243. Object.defineProperties( Quaternion.prototype, {
  1244. x: {
  1245. get: function () {
  1246. return this._x;
  1247. },
  1248. set: function ( value ) {
  1249. this._x = value;
  1250. this.onChangeCallback();
  1251. }
  1252. },
  1253. y: {
  1254. get: function () {
  1255. return this._y;
  1256. },
  1257. set: function ( value ) {
  1258. this._y = value;
  1259. this.onChangeCallback();
  1260. }
  1261. },
  1262. z: {
  1263. get: function () {
  1264. return this._z;
  1265. },
  1266. set: function ( value ) {
  1267. this._z = value;
  1268. this.onChangeCallback();
  1269. }
  1270. },
  1271. w: {
  1272. get: function () {
  1273. return this._w;
  1274. },
  1275. set: function ( value ) {
  1276. this._w = value;
  1277. this.onChangeCallback();
  1278. }
  1279. }
  1280. } );
  1281. Object.assign( Quaternion.prototype, {
  1282. set: function ( x, y, z, w ) {
  1283. this._x = x;
  1284. this._y = y;
  1285. this._z = z;
  1286. this._w = w;
  1287. this.onChangeCallback();
  1288. return this;
  1289. },
  1290. clone: function () {
  1291. return new this.constructor( this._x, this._y, this._z, this._w );
  1292. },
  1293. copy: function ( quaternion ) {
  1294. this._x = quaternion.x;
  1295. this._y = quaternion.y;
  1296. this._z = quaternion.z;
  1297. this._w = quaternion.w;
  1298. this.onChangeCallback();
  1299. return this;
  1300. },
  1301. setFromEuler: function ( euler, update ) {
  1302. if ( ( euler && euler.isEuler ) === false ) {
  1303. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1304. }
  1305. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1306. // http://www.mathworks.com/matlabcentral/fileexchange/
  1307. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1308. // content/SpinCalc.m
  1309. var cos = Math.cos;
  1310. var sin = Math.sin;
  1311. var c1 = cos( x / 2 );
  1312. var c2 = cos( y / 2 );
  1313. var c3 = cos( z / 2 );
  1314. var s1 = sin( x / 2 );
  1315. var s2 = sin( y / 2 );
  1316. var s3 = sin( z / 2 );
  1317. if ( order === 'XYZ' ) {
  1318. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1319. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1320. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1321. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1322. } else if ( order === 'YXZ' ) {
  1323. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1324. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1325. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1326. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1327. } else if ( order === 'ZXY' ) {
  1328. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1329. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1330. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1331. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1332. } else if ( order === 'ZYX' ) {
  1333. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1334. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1335. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1336. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1337. } else if ( order === 'YZX' ) {
  1338. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1339. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1340. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1341. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1342. } else if ( order === 'XZY' ) {
  1343. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1344. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1345. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1346. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1347. }
  1348. if ( update !== false ) this.onChangeCallback();
  1349. return this;
  1350. },
  1351. setFromAxisAngle: function ( axis, angle ) {
  1352. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1353. // assumes axis is normalized
  1354. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1355. this._x = axis.x * s;
  1356. this._y = axis.y * s;
  1357. this._z = axis.z * s;
  1358. this._w = Math.cos( halfAngle );
  1359. this.onChangeCallback();
  1360. return this;
  1361. },
  1362. setFromRotationMatrix: function ( m ) {
  1363. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1364. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1365. var te = m.elements,
  1366. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1367. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1368. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1369. trace = m11 + m22 + m33,
  1370. s;
  1371. if ( trace > 0 ) {
  1372. s = 0.5 / Math.sqrt( trace + 1.0 );
  1373. this._w = 0.25 / s;
  1374. this._x = ( m32 - m23 ) * s;
  1375. this._y = ( m13 - m31 ) * s;
  1376. this._z = ( m21 - m12 ) * s;
  1377. } else if ( m11 > m22 && m11 > m33 ) {
  1378. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1379. this._w = ( m32 - m23 ) / s;
  1380. this._x = 0.25 * s;
  1381. this._y = ( m12 + m21 ) / s;
  1382. this._z = ( m13 + m31 ) / s;
  1383. } else if ( m22 > m33 ) {
  1384. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1385. this._w = ( m13 - m31 ) / s;
  1386. this._x = ( m12 + m21 ) / s;
  1387. this._y = 0.25 * s;
  1388. this._z = ( m23 + m32 ) / s;
  1389. } else {
  1390. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1391. this._w = ( m21 - m12 ) / s;
  1392. this._x = ( m13 + m31 ) / s;
  1393. this._y = ( m23 + m32 ) / s;
  1394. this._z = 0.25 * s;
  1395. }
  1396. this.onChangeCallback();
  1397. return this;
  1398. },
  1399. setFromUnitVectors: function () {
  1400. // assumes direction vectors vFrom and vTo are normalized
  1401. var v1, r;
  1402. var EPS = 0.000001;
  1403. return function setFromUnitVectors( vFrom, vTo ) {
  1404. if ( v1 === undefined ) v1 = new Vector3();
  1405. r = vFrom.dot( vTo ) + 1;
  1406. if ( r < EPS ) {
  1407. r = 0;
  1408. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1409. v1.set( - vFrom.y, vFrom.x, 0 );
  1410. } else {
  1411. v1.set( 0, - vFrom.z, vFrom.y );
  1412. }
  1413. } else {
  1414. v1.crossVectors( vFrom, vTo );
  1415. }
  1416. this._x = v1.x;
  1417. this._y = v1.y;
  1418. this._z = v1.z;
  1419. this._w = r;
  1420. return this.normalize();
  1421. };
  1422. }(),
  1423. inverse: function () {
  1424. return this.conjugate().normalize();
  1425. },
  1426. conjugate: function () {
  1427. this._x *= - 1;
  1428. this._y *= - 1;
  1429. this._z *= - 1;
  1430. this.onChangeCallback();
  1431. return this;
  1432. },
  1433. dot: function ( v ) {
  1434. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1435. },
  1436. lengthSq: function () {
  1437. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1438. },
  1439. length: function () {
  1440. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1441. },
  1442. normalize: function () {
  1443. var l = this.length();
  1444. if ( l === 0 ) {
  1445. this._x = 0;
  1446. this._y = 0;
  1447. this._z = 0;
  1448. this._w = 1;
  1449. } else {
  1450. l = 1 / l;
  1451. this._x = this._x * l;
  1452. this._y = this._y * l;
  1453. this._z = this._z * l;
  1454. this._w = this._w * l;
  1455. }
  1456. this.onChangeCallback();
  1457. return this;
  1458. },
  1459. multiply: function ( q, p ) {
  1460. if ( p !== undefined ) {
  1461. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1462. return this.multiplyQuaternions( q, p );
  1463. }
  1464. return this.multiplyQuaternions( this, q );
  1465. },
  1466. premultiply: function ( q ) {
  1467. return this.multiplyQuaternions( q, this );
  1468. },
  1469. multiplyQuaternions: function ( a, b ) {
  1470. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1471. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1472. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1473. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1474. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1475. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1476. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1477. this.onChangeCallback();
  1478. return this;
  1479. },
  1480. slerp: function ( qb, t ) {
  1481. if ( t === 0 ) return this;
  1482. if ( t === 1 ) return this.copy( qb );
  1483. var x = this._x, y = this._y, z = this._z, w = this._w;
  1484. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1485. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1486. if ( cosHalfTheta < 0 ) {
  1487. this._w = - qb._w;
  1488. this._x = - qb._x;
  1489. this._y = - qb._y;
  1490. this._z = - qb._z;
  1491. cosHalfTheta = - cosHalfTheta;
  1492. } else {
  1493. this.copy( qb );
  1494. }
  1495. if ( cosHalfTheta >= 1.0 ) {
  1496. this._w = w;
  1497. this._x = x;
  1498. this._y = y;
  1499. this._z = z;
  1500. return this;
  1501. }
  1502. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1503. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1504. this._w = 0.5 * ( w + this._w );
  1505. this._x = 0.5 * ( x + this._x );
  1506. this._y = 0.5 * ( y + this._y );
  1507. this._z = 0.5 * ( z + this._z );
  1508. return this;
  1509. }
  1510. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1511. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1512. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1513. this._w = ( w * ratioA + this._w * ratioB );
  1514. this._x = ( x * ratioA + this._x * ratioB );
  1515. this._y = ( y * ratioA + this._y * ratioB );
  1516. this._z = ( z * ratioA + this._z * ratioB );
  1517. this.onChangeCallback();
  1518. return this;
  1519. },
  1520. equals: function ( quaternion ) {
  1521. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1522. },
  1523. fromArray: function ( array, offset ) {
  1524. if ( offset === undefined ) offset = 0;
  1525. this._x = array[ offset ];
  1526. this._y = array[ offset + 1 ];
  1527. this._z = array[ offset + 2 ];
  1528. this._w = array[ offset + 3 ];
  1529. this.onChangeCallback();
  1530. return this;
  1531. },
  1532. toArray: function ( array, offset ) {
  1533. if ( array === undefined ) array = [];
  1534. if ( offset === undefined ) offset = 0;
  1535. array[ offset ] = this._x;
  1536. array[ offset + 1 ] = this._y;
  1537. array[ offset + 2 ] = this._z;
  1538. array[ offset + 3 ] = this._w;
  1539. return array;
  1540. },
  1541. onChange: function ( callback ) {
  1542. this.onChangeCallback = callback;
  1543. return this;
  1544. },
  1545. onChangeCallback: function () {}
  1546. } );
  1547. /**
  1548. * @author mrdoob / http://mrdoob.com/
  1549. * @author *kile / http://kile.stravaganza.org/
  1550. * @author philogb / http://blog.thejit.org/
  1551. * @author mikael emtinger / http://gomo.se/
  1552. * @author egraether / http://egraether.com/
  1553. * @author WestLangley / http://github.com/WestLangley
  1554. */
  1555. function Vector3( x, y, z ) {
  1556. this.x = x || 0;
  1557. this.y = y || 0;
  1558. this.z = z || 0;
  1559. }
  1560. Object.assign( Vector3.prototype, {
  1561. isVector3: true,
  1562. set: function ( x, y, z ) {
  1563. this.x = x;
  1564. this.y = y;
  1565. this.z = z;
  1566. return this;
  1567. },
  1568. setScalar: function ( scalar ) {
  1569. this.x = scalar;
  1570. this.y = scalar;
  1571. this.z = scalar;
  1572. return this;
  1573. },
  1574. setX: function ( x ) {
  1575. this.x = x;
  1576. return this;
  1577. },
  1578. setY: function ( y ) {
  1579. this.y = y;
  1580. return this;
  1581. },
  1582. setZ: function ( z ) {
  1583. this.z = z;
  1584. return this;
  1585. },
  1586. setComponent: function ( index, value ) {
  1587. switch ( index ) {
  1588. case 0: this.x = value; break;
  1589. case 1: this.y = value; break;
  1590. case 2: this.z = value; break;
  1591. default: throw new Error( 'index is out of range: ' + index );
  1592. }
  1593. return this;
  1594. },
  1595. getComponent: function ( index ) {
  1596. switch ( index ) {
  1597. case 0: return this.x;
  1598. case 1: return this.y;
  1599. case 2: return this.z;
  1600. default: throw new Error( 'index is out of range: ' + index );
  1601. }
  1602. },
  1603. clone: function () {
  1604. return new this.constructor( this.x, this.y, this.z );
  1605. },
  1606. copy: function ( v ) {
  1607. this.x = v.x;
  1608. this.y = v.y;
  1609. this.z = v.z;
  1610. return this;
  1611. },
  1612. add: function ( v, w ) {
  1613. if ( w !== undefined ) {
  1614. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1615. return this.addVectors( v, w );
  1616. }
  1617. this.x += v.x;
  1618. this.y += v.y;
  1619. this.z += v.z;
  1620. return this;
  1621. },
  1622. addScalar: function ( s ) {
  1623. this.x += s;
  1624. this.y += s;
  1625. this.z += s;
  1626. return this;
  1627. },
  1628. addVectors: function ( a, b ) {
  1629. this.x = a.x + b.x;
  1630. this.y = a.y + b.y;
  1631. this.z = a.z + b.z;
  1632. return this;
  1633. },
  1634. addScaledVector: function ( v, s ) {
  1635. this.x += v.x * s;
  1636. this.y += v.y * s;
  1637. this.z += v.z * s;
  1638. return this;
  1639. },
  1640. sub: function ( v, w ) {
  1641. if ( w !== undefined ) {
  1642. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1643. return this.subVectors( v, w );
  1644. }
  1645. this.x -= v.x;
  1646. this.y -= v.y;
  1647. this.z -= v.z;
  1648. return this;
  1649. },
  1650. subScalar: function ( s ) {
  1651. this.x -= s;
  1652. this.y -= s;
  1653. this.z -= s;
  1654. return this;
  1655. },
  1656. subVectors: function ( a, b ) {
  1657. this.x = a.x - b.x;
  1658. this.y = a.y - b.y;
  1659. this.z = a.z - b.z;
  1660. return this;
  1661. },
  1662. multiply: function ( v, w ) {
  1663. if ( w !== undefined ) {
  1664. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1665. return this.multiplyVectors( v, w );
  1666. }
  1667. this.x *= v.x;
  1668. this.y *= v.y;
  1669. this.z *= v.z;
  1670. return this;
  1671. },
  1672. multiplyScalar: function ( scalar ) {
  1673. this.x *= scalar;
  1674. this.y *= scalar;
  1675. this.z *= scalar;
  1676. return this;
  1677. },
  1678. multiplyVectors: function ( a, b ) {
  1679. this.x = a.x * b.x;
  1680. this.y = a.y * b.y;
  1681. this.z = a.z * b.z;
  1682. return this;
  1683. },
  1684. applyEuler: function () {
  1685. var quaternion;
  1686. return function applyEuler( euler ) {
  1687. if ( ( euler && euler.isEuler ) === false ) {
  1688. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1689. }
  1690. if ( quaternion === undefined ) quaternion = new Quaternion();
  1691. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1692. };
  1693. }(),
  1694. applyAxisAngle: function () {
  1695. var quaternion;
  1696. return function applyAxisAngle( axis, angle ) {
  1697. if ( quaternion === undefined ) quaternion = new Quaternion();
  1698. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1699. };
  1700. }(),
  1701. applyMatrix3: function ( m ) {
  1702. var x = this.x, y = this.y, z = this.z;
  1703. var e = m.elements;
  1704. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1705. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1706. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1707. return this;
  1708. },
  1709. applyMatrix4: function ( m ) {
  1710. var x = this.x, y = this.y, z = this.z;
  1711. var e = m.elements;
  1712. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1713. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1714. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1715. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  1716. return this.divideScalar( w );
  1717. },
  1718. applyQuaternion: function ( q ) {
  1719. var x = this.x, y = this.y, z = this.z;
  1720. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1721. // calculate quat * vector
  1722. var ix = qw * x + qy * z - qz * y;
  1723. var iy = qw * y + qz * x - qx * z;
  1724. var iz = qw * z + qx * y - qy * x;
  1725. var iw = - qx * x - qy * y - qz * z;
  1726. // calculate result * inverse quat
  1727. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1728. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1729. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1730. return this;
  1731. },
  1732. project: function () {
  1733. var matrix;
  1734. return function project( camera ) {
  1735. if ( matrix === undefined ) matrix = new Matrix4();
  1736. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1737. return this.applyMatrix4( matrix );
  1738. };
  1739. }(),
  1740. unproject: function () {
  1741. var matrix;
  1742. return function unproject( camera ) {
  1743. if ( matrix === undefined ) matrix = new Matrix4();
  1744. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1745. return this.applyMatrix4( matrix );
  1746. };
  1747. }(),
  1748. transformDirection: function ( m ) {
  1749. // input: THREE.Matrix4 affine matrix
  1750. // vector interpreted as a direction
  1751. var x = this.x, y = this.y, z = this.z;
  1752. var e = m.elements;
  1753. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1754. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1755. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1756. return this.normalize();
  1757. },
  1758. divide: function ( v ) {
  1759. this.x /= v.x;
  1760. this.y /= v.y;
  1761. this.z /= v.z;
  1762. return this;
  1763. },
  1764. divideScalar: function ( scalar ) {
  1765. return this.multiplyScalar( 1 / scalar );
  1766. },
  1767. min: function ( v ) {
  1768. this.x = Math.min( this.x, v.x );
  1769. this.y = Math.min( this.y, v.y );
  1770. this.z = Math.min( this.z, v.z );
  1771. return this;
  1772. },
  1773. max: function ( v ) {
  1774. this.x = Math.max( this.x, v.x );
  1775. this.y = Math.max( this.y, v.y );
  1776. this.z = Math.max( this.z, v.z );
  1777. return this;
  1778. },
  1779. clamp: function ( min, max ) {
  1780. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1781. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1782. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1783. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1784. return this;
  1785. },
  1786. clampScalar: function () {
  1787. var min, max;
  1788. return function clampScalar( minVal, maxVal ) {
  1789. if ( min === undefined ) {
  1790. min = new Vector3();
  1791. max = new Vector3();
  1792. }
  1793. min.set( minVal, minVal, minVal );
  1794. max.set( maxVal, maxVal, maxVal );
  1795. return this.clamp( min, max );
  1796. };
  1797. }(),
  1798. clampLength: function ( min, max ) {
  1799. var length = this.length();
  1800. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1801. },
  1802. floor: function () {
  1803. this.x = Math.floor( this.x );
  1804. this.y = Math.floor( this.y );
  1805. this.z = Math.floor( this.z );
  1806. return this;
  1807. },
  1808. ceil: function () {
  1809. this.x = Math.ceil( this.x );
  1810. this.y = Math.ceil( this.y );
  1811. this.z = Math.ceil( this.z );
  1812. return this;
  1813. },
  1814. round: function () {
  1815. this.x = Math.round( this.x );
  1816. this.y = Math.round( this.y );
  1817. this.z = Math.round( this.z );
  1818. return this;
  1819. },
  1820. roundToZero: function () {
  1821. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1822. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1823. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1824. return this;
  1825. },
  1826. negate: function () {
  1827. this.x = - this.x;
  1828. this.y = - this.y;
  1829. this.z = - this.z;
  1830. return this;
  1831. },
  1832. dot: function ( v ) {
  1833. return this.x * v.x + this.y * v.y + this.z * v.z;
  1834. },
  1835. // TODO lengthSquared?
  1836. lengthSq: function () {
  1837. return this.x * this.x + this.y * this.y + this.z * this.z;
  1838. },
  1839. length: function () {
  1840. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1841. },
  1842. lengthManhattan: function () {
  1843. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1844. },
  1845. normalize: function () {
  1846. return this.divideScalar( this.length() );
  1847. },
  1848. setLength: function ( length ) {
  1849. return this.multiplyScalar( length / this.length() );
  1850. },
  1851. lerp: function ( v, alpha ) {
  1852. this.x += ( v.x - this.x ) * alpha;
  1853. this.y += ( v.y - this.y ) * alpha;
  1854. this.z += ( v.z - this.z ) * alpha;
  1855. return this;
  1856. },
  1857. lerpVectors: function ( v1, v2, alpha ) {
  1858. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1859. },
  1860. cross: function ( v, w ) {
  1861. if ( w !== undefined ) {
  1862. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1863. return this.crossVectors( v, w );
  1864. }
  1865. var x = this.x, y = this.y, z = this.z;
  1866. this.x = y * v.z - z * v.y;
  1867. this.y = z * v.x - x * v.z;
  1868. this.z = x * v.y - y * v.x;
  1869. return this;
  1870. },
  1871. crossVectors: function ( a, b ) {
  1872. var ax = a.x, ay = a.y, az = a.z;
  1873. var bx = b.x, by = b.y, bz = b.z;
  1874. this.x = ay * bz - az * by;
  1875. this.y = az * bx - ax * bz;
  1876. this.z = ax * by - ay * bx;
  1877. return this;
  1878. },
  1879. projectOnVector: function ( vector ) {
  1880. var scalar = vector.dot( this ) / vector.lengthSq();
  1881. return this.copy( vector ).multiplyScalar( scalar );
  1882. },
  1883. projectOnPlane: function () {
  1884. var v1;
  1885. return function projectOnPlane( planeNormal ) {
  1886. if ( v1 === undefined ) v1 = new Vector3();
  1887. v1.copy( this ).projectOnVector( planeNormal );
  1888. return this.sub( v1 );
  1889. };
  1890. }(),
  1891. reflect: function () {
  1892. // reflect incident vector off plane orthogonal to normal
  1893. // normal is assumed to have unit length
  1894. var v1;
  1895. return function reflect( normal ) {
  1896. if ( v1 === undefined ) v1 = new Vector3();
  1897. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1898. };
  1899. }(),
  1900. angleTo: function ( v ) {
  1901. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1902. // clamp, to handle numerical problems
  1903. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1904. },
  1905. distanceTo: function ( v ) {
  1906. return Math.sqrt( this.distanceToSquared( v ) );
  1907. },
  1908. distanceToSquared: function ( v ) {
  1909. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1910. return dx * dx + dy * dy + dz * dz;
  1911. },
  1912. distanceToManhattan: function ( v ) {
  1913. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1914. },
  1915. setFromSpherical: function ( s ) {
  1916. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1917. this.x = sinPhiRadius * Math.sin( s.theta );
  1918. this.y = Math.cos( s.phi ) * s.radius;
  1919. this.z = sinPhiRadius * Math.cos( s.theta );
  1920. return this;
  1921. },
  1922. setFromCylindrical: function ( c ) {
  1923. this.x = c.radius * Math.sin( c.theta );
  1924. this.y = c.y;
  1925. this.z = c.radius * Math.cos( c.theta );
  1926. return this;
  1927. },
  1928. setFromMatrixPosition: function ( m ) {
  1929. return this.setFromMatrixColumn( m, 3 );
  1930. },
  1931. setFromMatrixScale: function ( m ) {
  1932. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1933. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1934. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1935. this.x = sx;
  1936. this.y = sy;
  1937. this.z = sz;
  1938. return this;
  1939. },
  1940. setFromMatrixColumn: function ( m, index ) {
  1941. return this.fromArray( m.elements, index * 4 );
  1942. },
  1943. equals: function ( v ) {
  1944. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1945. },
  1946. fromArray: function ( array, offset ) {
  1947. if ( offset === undefined ) offset = 0;
  1948. this.x = array[ offset ];
  1949. this.y = array[ offset + 1 ];
  1950. this.z = array[ offset + 2 ];
  1951. return this;
  1952. },
  1953. toArray: function ( array, offset ) {
  1954. if ( array === undefined ) array = [];
  1955. if ( offset === undefined ) offset = 0;
  1956. array[ offset ] = this.x;
  1957. array[ offset + 1 ] = this.y;
  1958. array[ offset + 2 ] = this.z;
  1959. return array;
  1960. },
  1961. fromBufferAttribute: function ( attribute, index, offset ) {
  1962. if ( offset !== undefined ) {
  1963. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1964. }
  1965. this.x = attribute.getX( index );
  1966. this.y = attribute.getY( index );
  1967. this.z = attribute.getZ( index );
  1968. return this;
  1969. }
  1970. } );
  1971. /**
  1972. * @author mrdoob / http://mrdoob.com/
  1973. * @author supereggbert / http://www.paulbrunt.co.uk/
  1974. * @author philogb / http://blog.thejit.org/
  1975. * @author jordi_ros / http://plattsoft.com
  1976. * @author D1plo1d / http://github.com/D1plo1d
  1977. * @author alteredq / http://alteredqualia.com/
  1978. * @author mikael emtinger / http://gomo.se/
  1979. * @author timknip / http://www.floorplanner.com/
  1980. * @author bhouston / http://clara.io
  1981. * @author WestLangley / http://github.com/WestLangley
  1982. */
  1983. function Matrix4() {
  1984. this.elements = [
  1985. 1, 0, 0, 0,
  1986. 0, 1, 0, 0,
  1987. 0, 0, 1, 0,
  1988. 0, 0, 0, 1
  1989. ];
  1990. if ( arguments.length > 0 ) {
  1991. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1992. }
  1993. }
  1994. Object.assign( Matrix4.prototype, {
  1995. isMatrix4: true,
  1996. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1997. var te = this.elements;
  1998. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  1999. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2000. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2001. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2002. return this;
  2003. },
  2004. identity: function () {
  2005. this.set(
  2006. 1, 0, 0, 0,
  2007. 0, 1, 0, 0,
  2008. 0, 0, 1, 0,
  2009. 0, 0, 0, 1
  2010. );
  2011. return this;
  2012. },
  2013. clone: function () {
  2014. return new Matrix4().fromArray( this.elements );
  2015. },
  2016. copy: function ( m ) {
  2017. var te = this.elements;
  2018. var me = m.elements;
  2019. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2020. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2021. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2022. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2023. return this;
  2024. },
  2025. copyPosition: function ( m ) {
  2026. var te = this.elements, me = m.elements;
  2027. te[ 12 ] = me[ 12 ];
  2028. te[ 13 ] = me[ 13 ];
  2029. te[ 14 ] = me[ 14 ];
  2030. return this;
  2031. },
  2032. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2033. xAxis.setFromMatrixColumn( this, 0 );
  2034. yAxis.setFromMatrixColumn( this, 1 );
  2035. zAxis.setFromMatrixColumn( this, 2 );
  2036. return this;
  2037. },
  2038. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2039. this.set(
  2040. xAxis.x, yAxis.x, zAxis.x, 0,
  2041. xAxis.y, yAxis.y, zAxis.y, 0,
  2042. xAxis.z, yAxis.z, zAxis.z, 0,
  2043. 0, 0, 0, 1
  2044. );
  2045. return this;
  2046. },
  2047. extractRotation: function () {
  2048. var v1;
  2049. return function extractRotation( m ) {
  2050. if ( v1 === undefined ) v1 = new Vector3();
  2051. var te = this.elements;
  2052. var me = m.elements;
  2053. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2054. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2055. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2056. te[ 0 ] = me[ 0 ] * scaleX;
  2057. te[ 1 ] = me[ 1 ] * scaleX;
  2058. te[ 2 ] = me[ 2 ] * scaleX;
  2059. te[ 4 ] = me[ 4 ] * scaleY;
  2060. te[ 5 ] = me[ 5 ] * scaleY;
  2061. te[ 6 ] = me[ 6 ] * scaleY;
  2062. te[ 8 ] = me[ 8 ] * scaleZ;
  2063. te[ 9 ] = me[ 9 ] * scaleZ;
  2064. te[ 10 ] = me[ 10 ] * scaleZ;
  2065. return this;
  2066. };
  2067. }(),
  2068. makeRotationFromEuler: function ( euler ) {
  2069. if ( ( euler && euler.isEuler ) === false ) {
  2070. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2071. }
  2072. var te = this.elements;
  2073. var x = euler.x, y = euler.y, z = euler.z;
  2074. var a = Math.cos( x ), b = Math.sin( x );
  2075. var c = Math.cos( y ), d = Math.sin( y );
  2076. var e = Math.cos( z ), f = Math.sin( z );
  2077. if ( euler.order === 'XYZ' ) {
  2078. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2079. te[ 0 ] = c * e;
  2080. te[ 4 ] = - c * f;
  2081. te[ 8 ] = d;
  2082. te[ 1 ] = af + be * d;
  2083. te[ 5 ] = ae - bf * d;
  2084. te[ 9 ] = - b * c;
  2085. te[ 2 ] = bf - ae * d;
  2086. te[ 6 ] = be + af * d;
  2087. te[ 10 ] = a * c;
  2088. } else if ( euler.order === 'YXZ' ) {
  2089. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2090. te[ 0 ] = ce + df * b;
  2091. te[ 4 ] = de * b - cf;
  2092. te[ 8 ] = a * d;
  2093. te[ 1 ] = a * f;
  2094. te[ 5 ] = a * e;
  2095. te[ 9 ] = - b;
  2096. te[ 2 ] = cf * b - de;
  2097. te[ 6 ] = df + ce * b;
  2098. te[ 10 ] = a * c;
  2099. } else if ( euler.order === 'ZXY' ) {
  2100. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2101. te[ 0 ] = ce - df * b;
  2102. te[ 4 ] = - a * f;
  2103. te[ 8 ] = de + cf * b;
  2104. te[ 1 ] = cf + de * b;
  2105. te[ 5 ] = a * e;
  2106. te[ 9 ] = df - ce * b;
  2107. te[ 2 ] = - a * d;
  2108. te[ 6 ] = b;
  2109. te[ 10 ] = a * c;
  2110. } else if ( euler.order === 'ZYX' ) {
  2111. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2112. te[ 0 ] = c * e;
  2113. te[ 4 ] = be * d - af;
  2114. te[ 8 ] = ae * d + bf;
  2115. te[ 1 ] = c * f;
  2116. te[ 5 ] = bf * d + ae;
  2117. te[ 9 ] = af * d - be;
  2118. te[ 2 ] = - d;
  2119. te[ 6 ] = b * c;
  2120. te[ 10 ] = a * c;
  2121. } else if ( euler.order === 'YZX' ) {
  2122. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2123. te[ 0 ] = c * e;
  2124. te[ 4 ] = bd - ac * f;
  2125. te[ 8 ] = bc * f + ad;
  2126. te[ 1 ] = f;
  2127. te[ 5 ] = a * e;
  2128. te[ 9 ] = - b * e;
  2129. te[ 2 ] = - d * e;
  2130. te[ 6 ] = ad * f + bc;
  2131. te[ 10 ] = ac - bd * f;
  2132. } else if ( euler.order === 'XZY' ) {
  2133. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2134. te[ 0 ] = c * e;
  2135. te[ 4 ] = - f;
  2136. te[ 8 ] = d * e;
  2137. te[ 1 ] = ac * f + bd;
  2138. te[ 5 ] = a * e;
  2139. te[ 9 ] = ad * f - bc;
  2140. te[ 2 ] = bc * f - ad;
  2141. te[ 6 ] = b * e;
  2142. te[ 10 ] = bd * f + ac;
  2143. }
  2144. // last column
  2145. te[ 3 ] = 0;
  2146. te[ 7 ] = 0;
  2147. te[ 11 ] = 0;
  2148. // bottom row
  2149. te[ 12 ] = 0;
  2150. te[ 13 ] = 0;
  2151. te[ 14 ] = 0;
  2152. te[ 15 ] = 1;
  2153. return this;
  2154. },
  2155. makeRotationFromQuaternion: function ( q ) {
  2156. var te = this.elements;
  2157. var x = q._x, y = q._y, z = q._z, w = q._w;
  2158. var x2 = x + x, y2 = y + y, z2 = z + z;
  2159. var xx = x * x2, xy = x * y2, xz = x * z2;
  2160. var yy = y * y2, yz = y * z2, zz = z * z2;
  2161. var wx = w * x2, wy = w * y2, wz = w * z2;
  2162. te[ 0 ] = 1 - ( yy + zz );
  2163. te[ 4 ] = xy - wz;
  2164. te[ 8 ] = xz + wy;
  2165. te[ 1 ] = xy + wz;
  2166. te[ 5 ] = 1 - ( xx + zz );
  2167. te[ 9 ] = yz - wx;
  2168. te[ 2 ] = xz - wy;
  2169. te[ 6 ] = yz + wx;
  2170. te[ 10 ] = 1 - ( xx + yy );
  2171. // last column
  2172. te[ 3 ] = 0;
  2173. te[ 7 ] = 0;
  2174. te[ 11 ] = 0;
  2175. // bottom row
  2176. te[ 12 ] = 0;
  2177. te[ 13 ] = 0;
  2178. te[ 14 ] = 0;
  2179. te[ 15 ] = 1;
  2180. return this;
  2181. },
  2182. lookAt: function () {
  2183. var x, y, z;
  2184. return function lookAt( eye, target, up ) {
  2185. if ( x === undefined ) {
  2186. x = new Vector3();
  2187. y = new Vector3();
  2188. z = new Vector3();
  2189. }
  2190. var te = this.elements;
  2191. z.subVectors( eye, target );
  2192. if ( z.lengthSq() === 0 ) {
  2193. // eye and target are in the same position
  2194. z.z = 1;
  2195. }
  2196. z.normalize();
  2197. x.crossVectors( up, z );
  2198. if ( x.lengthSq() === 0 ) {
  2199. // eye and target are in the same vertical
  2200. z.z += 0.0001;
  2201. x.crossVectors( up, z );
  2202. }
  2203. x.normalize();
  2204. y.crossVectors( z, x );
  2205. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2206. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2207. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2208. return this;
  2209. };
  2210. }(),
  2211. multiply: function ( m, n ) {
  2212. if ( n !== undefined ) {
  2213. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2214. return this.multiplyMatrices( m, n );
  2215. }
  2216. return this.multiplyMatrices( this, m );
  2217. },
  2218. premultiply: function ( m ) {
  2219. return this.multiplyMatrices( m, this );
  2220. },
  2221. multiplyMatrices: function ( a, b ) {
  2222. var ae = a.elements;
  2223. var be = b.elements;
  2224. var te = this.elements;
  2225. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2226. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2227. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2228. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2229. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2230. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2231. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2232. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2233. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2234. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2235. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2236. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2237. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2238. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2239. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2240. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2241. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2242. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2243. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2244. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2245. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2246. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2247. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2248. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2249. return this;
  2250. },
  2251. multiplyScalar: function ( s ) {
  2252. var te = this.elements;
  2253. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2254. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2255. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2256. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2257. return this;
  2258. },
  2259. applyToBufferAttribute: function () {
  2260. var v1;
  2261. return function applyToBufferAttribute( attribute ) {
  2262. if ( v1 === undefined ) v1 = new Vector3();
  2263. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2264. v1.x = attribute.getX( i );
  2265. v1.y = attribute.getY( i );
  2266. v1.z = attribute.getZ( i );
  2267. v1.applyMatrix4( this );
  2268. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2269. }
  2270. return attribute;
  2271. };
  2272. }(),
  2273. determinant: function () {
  2274. var te = this.elements;
  2275. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2276. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2277. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2278. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2279. //TODO: make this more efficient
  2280. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2281. return (
  2282. n41 * (
  2283. + n14 * n23 * n32
  2284. - n13 * n24 * n32
  2285. - n14 * n22 * n33
  2286. + n12 * n24 * n33
  2287. + n13 * n22 * n34
  2288. - n12 * n23 * n34
  2289. ) +
  2290. n42 * (
  2291. + n11 * n23 * n34
  2292. - n11 * n24 * n33
  2293. + n14 * n21 * n33
  2294. - n13 * n21 * n34
  2295. + n13 * n24 * n31
  2296. - n14 * n23 * n31
  2297. ) +
  2298. n43 * (
  2299. + n11 * n24 * n32
  2300. - n11 * n22 * n34
  2301. - n14 * n21 * n32
  2302. + n12 * n21 * n34
  2303. + n14 * n22 * n31
  2304. - n12 * n24 * n31
  2305. ) +
  2306. n44 * (
  2307. - n13 * n22 * n31
  2308. - n11 * n23 * n32
  2309. + n11 * n22 * n33
  2310. + n13 * n21 * n32
  2311. - n12 * n21 * n33
  2312. + n12 * n23 * n31
  2313. )
  2314. );
  2315. },
  2316. transpose: function () {
  2317. var te = this.elements;
  2318. var tmp;
  2319. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2320. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2321. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2322. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2323. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2324. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2325. return this;
  2326. },
  2327. setPosition: function ( v ) {
  2328. var te = this.elements;
  2329. te[ 12 ] = v.x;
  2330. te[ 13 ] = v.y;
  2331. te[ 14 ] = v.z;
  2332. return this;
  2333. },
  2334. getInverse: function ( m, throwOnDegenerate ) {
  2335. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2336. var te = this.elements,
  2337. me = m.elements,
  2338. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2339. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2340. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2341. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2342. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2343. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2344. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2345. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2346. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2347. if ( det === 0 ) {
  2348. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2349. if ( throwOnDegenerate === true ) {
  2350. throw new Error( msg );
  2351. } else {
  2352. console.warn( msg );
  2353. }
  2354. return this.identity();
  2355. }
  2356. var detInv = 1 / det;
  2357. te[ 0 ] = t11 * detInv;
  2358. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2359. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2360. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2361. te[ 4 ] = t12 * detInv;
  2362. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2363. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2364. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2365. te[ 8 ] = t13 * detInv;
  2366. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2367. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2368. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2369. te[ 12 ] = t14 * detInv;
  2370. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2371. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2372. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2373. return this;
  2374. },
  2375. scale: function ( v ) {
  2376. var te = this.elements;
  2377. var x = v.x, y = v.y, z = v.z;
  2378. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2379. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2380. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2381. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2382. return this;
  2383. },
  2384. getMaxScaleOnAxis: function () {
  2385. var te = this.elements;
  2386. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2387. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2388. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2389. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2390. },
  2391. makeTranslation: function ( x, y, z ) {
  2392. this.set(
  2393. 1, 0, 0, x,
  2394. 0, 1, 0, y,
  2395. 0, 0, 1, z,
  2396. 0, 0, 0, 1
  2397. );
  2398. return this;
  2399. },
  2400. makeRotationX: function ( theta ) {
  2401. var c = Math.cos( theta ), s = Math.sin( theta );
  2402. this.set(
  2403. 1, 0, 0, 0,
  2404. 0, c, - s, 0,
  2405. 0, s, c, 0,
  2406. 0, 0, 0, 1
  2407. );
  2408. return this;
  2409. },
  2410. makeRotationY: function ( theta ) {
  2411. var c = Math.cos( theta ), s = Math.sin( theta );
  2412. this.set(
  2413. c, 0, s, 0,
  2414. 0, 1, 0, 0,
  2415. - s, 0, c, 0,
  2416. 0, 0, 0, 1
  2417. );
  2418. return this;
  2419. },
  2420. makeRotationZ: function ( theta ) {
  2421. var c = Math.cos( theta ), s = Math.sin( theta );
  2422. this.set(
  2423. c, - s, 0, 0,
  2424. s, c, 0, 0,
  2425. 0, 0, 1, 0,
  2426. 0, 0, 0, 1
  2427. );
  2428. return this;
  2429. },
  2430. makeRotationAxis: function ( axis, angle ) {
  2431. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2432. var c = Math.cos( angle );
  2433. var s = Math.sin( angle );
  2434. var t = 1 - c;
  2435. var x = axis.x, y = axis.y, z = axis.z;
  2436. var tx = t * x, ty = t * y;
  2437. this.set(
  2438. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2439. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2440. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2441. 0, 0, 0, 1
  2442. );
  2443. return this;
  2444. },
  2445. makeScale: function ( x, y, z ) {
  2446. this.set(
  2447. x, 0, 0, 0,
  2448. 0, y, 0, 0,
  2449. 0, 0, z, 0,
  2450. 0, 0, 0, 1
  2451. );
  2452. return this;
  2453. },
  2454. makeShear: function ( x, y, z ) {
  2455. this.set(
  2456. 1, y, z, 0,
  2457. x, 1, z, 0,
  2458. x, y, 1, 0,
  2459. 0, 0, 0, 1
  2460. );
  2461. return this;
  2462. },
  2463. compose: function ( position, quaternion, scale ) {
  2464. this.makeRotationFromQuaternion( quaternion );
  2465. this.scale( scale );
  2466. this.setPosition( position );
  2467. return this;
  2468. },
  2469. decompose: function () {
  2470. var vector, matrix;
  2471. return function decompose( position, quaternion, scale ) {
  2472. if ( vector === undefined ) {
  2473. vector = new Vector3();
  2474. matrix = new Matrix4();
  2475. }
  2476. var te = this.elements;
  2477. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2478. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2479. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2480. // if determine is negative, we need to invert one scale
  2481. var det = this.determinant();
  2482. if ( det < 0 ) sx = - sx;
  2483. position.x = te[ 12 ];
  2484. position.y = te[ 13 ];
  2485. position.z = te[ 14 ];
  2486. // scale the rotation part
  2487. matrix.copy( this );
  2488. var invSX = 1 / sx;
  2489. var invSY = 1 / sy;
  2490. var invSZ = 1 / sz;
  2491. matrix.elements[ 0 ] *= invSX;
  2492. matrix.elements[ 1 ] *= invSX;
  2493. matrix.elements[ 2 ] *= invSX;
  2494. matrix.elements[ 4 ] *= invSY;
  2495. matrix.elements[ 5 ] *= invSY;
  2496. matrix.elements[ 6 ] *= invSY;
  2497. matrix.elements[ 8 ] *= invSZ;
  2498. matrix.elements[ 9 ] *= invSZ;
  2499. matrix.elements[ 10 ] *= invSZ;
  2500. quaternion.setFromRotationMatrix( matrix );
  2501. scale.x = sx;
  2502. scale.y = sy;
  2503. scale.z = sz;
  2504. return this;
  2505. };
  2506. }(),
  2507. makePerspective: function ( left, right, top, bottom, near, far ) {
  2508. if ( far === undefined ) {
  2509. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2510. }
  2511. var te = this.elements;
  2512. var x = 2 * near / ( right - left );
  2513. var y = 2 * near / ( top - bottom );
  2514. var a = ( right + left ) / ( right - left );
  2515. var b = ( top + bottom ) / ( top - bottom );
  2516. var c = - ( far + near ) / ( far - near );
  2517. var d = - 2 * far * near / ( far - near );
  2518. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2519. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2520. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2521. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2522. return this;
  2523. },
  2524. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2525. var te = this.elements;
  2526. var w = 1.0 / ( right - left );
  2527. var h = 1.0 / ( top - bottom );
  2528. var p = 1.0 / ( far - near );
  2529. var x = ( right + left ) * w;
  2530. var y = ( top + bottom ) * h;
  2531. var z = ( far + near ) * p;
  2532. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2533. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2534. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2535. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2536. return this;
  2537. },
  2538. equals: function ( matrix ) {
  2539. var te = this.elements;
  2540. var me = matrix.elements;
  2541. for ( var i = 0; i < 16; i ++ ) {
  2542. if ( te[ i ] !== me[ i ] ) return false;
  2543. }
  2544. return true;
  2545. },
  2546. fromArray: function ( array, offset ) {
  2547. if ( offset === undefined ) offset = 0;
  2548. for ( var i = 0; i < 16; i ++ ) {
  2549. this.elements[ i ] = array[ i + offset ];
  2550. }
  2551. return this;
  2552. },
  2553. toArray: function ( array, offset ) {
  2554. if ( array === undefined ) array = [];
  2555. if ( offset === undefined ) offset = 0;
  2556. var te = this.elements;
  2557. array[ offset ] = te[ 0 ];
  2558. array[ offset + 1 ] = te[ 1 ];
  2559. array[ offset + 2 ] = te[ 2 ];
  2560. array[ offset + 3 ] = te[ 3 ];
  2561. array[ offset + 4 ] = te[ 4 ];
  2562. array[ offset + 5 ] = te[ 5 ];
  2563. array[ offset + 6 ] = te[ 6 ];
  2564. array[ offset + 7 ] = te[ 7 ];
  2565. array[ offset + 8 ] = te[ 8 ];
  2566. array[ offset + 9 ] = te[ 9 ];
  2567. array[ offset + 10 ] = te[ 10 ];
  2568. array[ offset + 11 ] = te[ 11 ];
  2569. array[ offset + 12 ] = te[ 12 ];
  2570. array[ offset + 13 ] = te[ 13 ];
  2571. array[ offset + 14 ] = te[ 14 ];
  2572. array[ offset + 15 ] = te[ 15 ];
  2573. return array;
  2574. }
  2575. } );
  2576. /**
  2577. * @author alteredq / http://alteredqualia.com/
  2578. */
  2579. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2580. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2581. this.image = { data: data, width: width, height: height };
  2582. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2583. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2584. this.generateMipmaps = false;
  2585. this.flipY = false;
  2586. this.unpackAlignment = 1;
  2587. }
  2588. DataTexture.prototype = Object.create( Texture.prototype );
  2589. DataTexture.prototype.constructor = DataTexture;
  2590. DataTexture.prototype.isDataTexture = true;
  2591. /**
  2592. * @author mrdoob / http://mrdoob.com/
  2593. */
  2594. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2595. images = images !== undefined ? images : [];
  2596. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2597. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2598. this.flipY = false;
  2599. }
  2600. CubeTexture.prototype = Object.create( Texture.prototype );
  2601. CubeTexture.prototype.constructor = CubeTexture;
  2602. CubeTexture.prototype.isCubeTexture = true;
  2603. Object.defineProperty( CubeTexture.prototype, 'images', {
  2604. get: function () {
  2605. return this.image;
  2606. },
  2607. set: function ( value ) {
  2608. this.image = value;
  2609. }
  2610. } );
  2611. /**
  2612. * @author tschw
  2613. *
  2614. * Uniforms of a program.
  2615. * Those form a tree structure with a special top-level container for the root,
  2616. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2617. *
  2618. *
  2619. * Properties of inner nodes including the top-level container:
  2620. *
  2621. * .seq - array of nested uniforms
  2622. * .map - nested uniforms by name
  2623. *
  2624. *
  2625. * Methods of all nodes except the top-level container:
  2626. *
  2627. * .setValue( gl, value, [renderer] )
  2628. *
  2629. * uploads a uniform value(s)
  2630. * the 'renderer' parameter is needed for sampler uniforms
  2631. *
  2632. *
  2633. * Static methods of the top-level container (renderer factorizations):
  2634. *
  2635. * .upload( gl, seq, values, renderer )
  2636. *
  2637. * sets uniforms in 'seq' to 'values[id].value'
  2638. *
  2639. * .seqWithValue( seq, values ) : filteredSeq
  2640. *
  2641. * filters 'seq' entries with corresponding entry in values
  2642. *
  2643. *
  2644. * Methods of the top-level container (renderer factorizations):
  2645. *
  2646. * .setValue( gl, name, value )
  2647. *
  2648. * sets uniform with name 'name' to 'value'
  2649. *
  2650. * .set( gl, obj, prop )
  2651. *
  2652. * sets uniform from object and property with same name than uniform
  2653. *
  2654. * .setOptional( gl, obj, prop )
  2655. *
  2656. * like .set for an optional property of the object
  2657. *
  2658. */
  2659. var emptyTexture = new Texture();
  2660. var emptyCubeTexture = new CubeTexture();
  2661. // --- Base for inner nodes (including the root) ---
  2662. function UniformContainer() {
  2663. this.seq = [];
  2664. this.map = {};
  2665. }
  2666. // --- Utilities ---
  2667. // Array Caches (provide typed arrays for temporary by size)
  2668. var arrayCacheF32 = [];
  2669. var arrayCacheI32 = [];
  2670. // Float32Array caches used for uploading Matrix uniforms
  2671. var mat4array = new Float32Array( 16 );
  2672. var mat3array = new Float32Array( 9 );
  2673. // Flattening for arrays of vectors and matrices
  2674. function flatten( array, nBlocks, blockSize ) {
  2675. var firstElem = array[ 0 ];
  2676. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2677. // unoptimized: ! isNaN( firstElem )
  2678. // see http://jacksondunstan.com/articles/983
  2679. var n = nBlocks * blockSize,
  2680. r = arrayCacheF32[ n ];
  2681. if ( r === undefined ) {
  2682. r = new Float32Array( n );
  2683. arrayCacheF32[ n ] = r;
  2684. }
  2685. if ( nBlocks !== 0 ) {
  2686. firstElem.toArray( r, 0 );
  2687. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2688. offset += blockSize;
  2689. array[ i ].toArray( r, offset );
  2690. }
  2691. }
  2692. return r;
  2693. }
  2694. // Texture unit allocation
  2695. function allocTexUnits( renderer, n ) {
  2696. var r = arrayCacheI32[ n ];
  2697. if ( r === undefined ) {
  2698. r = new Int32Array( n );
  2699. arrayCacheI32[ n ] = r;
  2700. }
  2701. for ( var i = 0; i !== n; ++ i )
  2702. r[ i ] = renderer.allocTextureUnit();
  2703. return r;
  2704. }
  2705. // --- Setters ---
  2706. // Note: Defining these methods externally, because they come in a bunch
  2707. // and this way their names minify.
  2708. // Single scalar
  2709. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2710. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2711. // Single float vector (from flat array or THREE.VectorN)
  2712. function setValue2fv( gl, v ) {
  2713. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2714. else gl.uniform2f( this.addr, v.x, v.y );
  2715. }
  2716. function setValue3fv( gl, v ) {
  2717. if ( v.x !== undefined )
  2718. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2719. else if ( v.r !== undefined )
  2720. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2721. else
  2722. gl.uniform3fv( this.addr, v );
  2723. }
  2724. function setValue4fv( gl, v ) {
  2725. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2726. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2727. }
  2728. // Single matrix (from flat array or MatrixN)
  2729. function setValue2fm( gl, v ) {
  2730. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2731. }
  2732. function setValue3fm( gl, v ) {
  2733. if ( v.elements === undefined ) {
  2734. gl.uniformMatrix3fv( this.addr, false, v );
  2735. } else {
  2736. mat3array.set( v.elements );
  2737. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2738. }
  2739. }
  2740. function setValue4fm( gl, v ) {
  2741. if ( v.elements === undefined ) {
  2742. gl.uniformMatrix4fv( this.addr, false, v );
  2743. } else {
  2744. mat4array.set( v.elements );
  2745. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2746. }
  2747. }
  2748. // Single texture (2D / Cube)
  2749. function setValueT1( gl, v, renderer ) {
  2750. var unit = renderer.allocTextureUnit();
  2751. gl.uniform1i( this.addr, unit );
  2752. renderer.setTexture2D( v || emptyTexture, unit );
  2753. }
  2754. function setValueT6( gl, v, renderer ) {
  2755. var unit = renderer.allocTextureUnit();
  2756. gl.uniform1i( this.addr, unit );
  2757. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2758. }
  2759. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2760. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2761. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2762. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2763. // Helper to pick the right setter for the singular case
  2764. function getSingularSetter( type ) {
  2765. switch ( type ) {
  2766. case 0x1406: return setValue1f; // FLOAT
  2767. case 0x8b50: return setValue2fv; // _VEC2
  2768. case 0x8b51: return setValue3fv; // _VEC3
  2769. case 0x8b52: return setValue4fv; // _VEC4
  2770. case 0x8b5a: return setValue2fm; // _MAT2
  2771. case 0x8b5b: return setValue3fm; // _MAT3
  2772. case 0x8b5c: return setValue4fm; // _MAT4
  2773. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2774. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2775. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2776. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2777. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2778. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2779. }
  2780. }
  2781. // Array of scalars
  2782. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2783. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2784. // Array of vectors (flat or from THREE classes)
  2785. function setValueV2a( gl, v ) {
  2786. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2787. }
  2788. function setValueV3a( gl, v ) {
  2789. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2790. }
  2791. function setValueV4a( gl, v ) {
  2792. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2793. }
  2794. // Array of matrices (flat or from THREE clases)
  2795. function setValueM2a( gl, v ) {
  2796. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2797. }
  2798. function setValueM3a( gl, v ) {
  2799. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2800. }
  2801. function setValueM4a( gl, v ) {
  2802. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2803. }
  2804. // Array of textures (2D / Cube)
  2805. function setValueT1a( gl, v, renderer ) {
  2806. var n = v.length,
  2807. units = allocTexUnits( renderer, n );
  2808. gl.uniform1iv( this.addr, units );
  2809. for ( var i = 0; i !== n; ++ i ) {
  2810. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2811. }
  2812. }
  2813. function setValueT6a( gl, v, renderer ) {
  2814. var n = v.length,
  2815. units = allocTexUnits( renderer, n );
  2816. gl.uniform1iv( this.addr, units );
  2817. for ( var i = 0; i !== n; ++ i ) {
  2818. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2819. }
  2820. }
  2821. // Helper to pick the right setter for a pure (bottom-level) array
  2822. function getPureArraySetter( type ) {
  2823. switch ( type ) {
  2824. case 0x1406: return setValue1fv; // FLOAT
  2825. case 0x8b50: return setValueV2a; // _VEC2
  2826. case 0x8b51: return setValueV3a; // _VEC3
  2827. case 0x8b52: return setValueV4a; // _VEC4
  2828. case 0x8b5a: return setValueM2a; // _MAT2
  2829. case 0x8b5b: return setValueM3a; // _MAT3
  2830. case 0x8b5c: return setValueM4a; // _MAT4
  2831. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2832. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2833. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2834. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2835. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2836. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2837. }
  2838. }
  2839. // --- Uniform Classes ---
  2840. function SingleUniform( id, activeInfo, addr ) {
  2841. this.id = id;
  2842. this.addr = addr;
  2843. this.setValue = getSingularSetter( activeInfo.type );
  2844. // this.path = activeInfo.name; // DEBUG
  2845. }
  2846. function PureArrayUniform( id, activeInfo, addr ) {
  2847. this.id = id;
  2848. this.addr = addr;
  2849. this.size = activeInfo.size;
  2850. this.setValue = getPureArraySetter( activeInfo.type );
  2851. // this.path = activeInfo.name; // DEBUG
  2852. }
  2853. function StructuredUniform( id ) {
  2854. this.id = id;
  2855. UniformContainer.call( this ); // mix-in
  2856. }
  2857. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2858. // Note: Don't need an extra 'renderer' parameter, since samplers
  2859. // are not allowed in structured uniforms.
  2860. var seq = this.seq;
  2861. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2862. var u = seq[ i ];
  2863. u.setValue( gl, value[ u.id ] );
  2864. }
  2865. };
  2866. // --- Top-level ---
  2867. // Parser - builds up the property tree from the path strings
  2868. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2869. // extracts
  2870. // - the identifier (member name or array index)
  2871. // - followed by an optional right bracket (found when array index)
  2872. // - followed by an optional left bracket or dot (type of subscript)
  2873. //
  2874. // Note: These portions can be read in a non-overlapping fashion and
  2875. // allow straightforward parsing of the hierarchy that WebGL encodes
  2876. // in the uniform names.
  2877. function addUniform( container, uniformObject ) {
  2878. container.seq.push( uniformObject );
  2879. container.map[ uniformObject.id ] = uniformObject;
  2880. }
  2881. function parseUniform( activeInfo, addr, container ) {
  2882. var path = activeInfo.name,
  2883. pathLength = path.length;
  2884. // reset RegExp object, because of the early exit of a previous run
  2885. RePathPart.lastIndex = 0;
  2886. for ( ; ; ) {
  2887. var match = RePathPart.exec( path ),
  2888. matchEnd = RePathPart.lastIndex,
  2889. id = match[ 1 ],
  2890. idIsIndex = match[ 2 ] === ']',
  2891. subscript = match[ 3 ];
  2892. if ( idIsIndex ) id = id | 0; // convert to integer
  2893. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2894. // bare name or "pure" bottom-level array "[0]" suffix
  2895. addUniform( container, subscript === undefined ?
  2896. new SingleUniform( id, activeInfo, addr ) :
  2897. new PureArrayUniform( id, activeInfo, addr ) );
  2898. break;
  2899. } else {
  2900. // step into inner node / create it in case it doesn't exist
  2901. var map = container.map, next = map[ id ];
  2902. if ( next === undefined ) {
  2903. next = new StructuredUniform( id );
  2904. addUniform( container, next );
  2905. }
  2906. container = next;
  2907. }
  2908. }
  2909. }
  2910. // Root Container
  2911. function WebGLUniforms( gl, program, renderer ) {
  2912. UniformContainer.call( this );
  2913. this.renderer = renderer;
  2914. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2915. for ( var i = 0; i < n; ++ i ) {
  2916. var info = gl.getActiveUniform( program, i ),
  2917. path = info.name,
  2918. addr = gl.getUniformLocation( program, path );
  2919. parseUniform( info, addr, this );
  2920. }
  2921. }
  2922. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2923. var u = this.map[ name ];
  2924. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2925. };
  2926. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2927. var v = object[ name ];
  2928. if ( v !== undefined ) this.setValue( gl, name, v );
  2929. };
  2930. // Static interface
  2931. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2932. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2933. var u = seq[ i ],
  2934. v = values[ u.id ];
  2935. if ( v.needsUpdate !== false ) {
  2936. // note: always updating when .needsUpdate is undefined
  2937. u.setValue( gl, v.value, renderer );
  2938. }
  2939. }
  2940. };
  2941. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2942. var r = [];
  2943. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2944. var u = seq[ i ];
  2945. if ( u.id in values ) r.push( u );
  2946. }
  2947. return r;
  2948. };
  2949. /**
  2950. * @author mrdoob / http://mrdoob.com/
  2951. */
  2952. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2953. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2954. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2955. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2956. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2957. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2958. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2959. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2960. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2961. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2962. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2963. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2964. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2965. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2966. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2967. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2968. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2969. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2970. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2971. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2972. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2973. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2974. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2975. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2976. function Color( r, g, b ) {
  2977. if ( g === undefined && b === undefined ) {
  2978. // r is THREE.Color, hex or string
  2979. return this.set( r );
  2980. }
  2981. return this.setRGB( r, g, b );
  2982. }
  2983. Object.assign( Color.prototype, {
  2984. isColor: true,
  2985. r: 1, g: 1, b: 1,
  2986. set: function ( value ) {
  2987. if ( value && value.isColor ) {
  2988. this.copy( value );
  2989. } else if ( typeof value === 'number' ) {
  2990. this.setHex( value );
  2991. } else if ( typeof value === 'string' ) {
  2992. this.setStyle( value );
  2993. }
  2994. return this;
  2995. },
  2996. setScalar: function ( scalar ) {
  2997. this.r = scalar;
  2998. this.g = scalar;
  2999. this.b = scalar;
  3000. return this;
  3001. },
  3002. setHex: function ( hex ) {
  3003. hex = Math.floor( hex );
  3004. this.r = ( hex >> 16 & 255 ) / 255;
  3005. this.g = ( hex >> 8 & 255 ) / 255;
  3006. this.b = ( hex & 255 ) / 255;
  3007. return this;
  3008. },
  3009. setRGB: function ( r, g, b ) {
  3010. this.r = r;
  3011. this.g = g;
  3012. this.b = b;
  3013. return this;
  3014. },
  3015. setHSL: function () {
  3016. function hue2rgb( p, q, t ) {
  3017. if ( t < 0 ) t += 1;
  3018. if ( t > 1 ) t -= 1;
  3019. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3020. if ( t < 1 / 2 ) return q;
  3021. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3022. return p;
  3023. }
  3024. return function setHSL( h, s, l ) {
  3025. // h,s,l ranges are in 0.0 - 1.0
  3026. h = _Math.euclideanModulo( h, 1 );
  3027. s = _Math.clamp( s, 0, 1 );
  3028. l = _Math.clamp( l, 0, 1 );
  3029. if ( s === 0 ) {
  3030. this.r = this.g = this.b = l;
  3031. } else {
  3032. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3033. var q = ( 2 * l ) - p;
  3034. this.r = hue2rgb( q, p, h + 1 / 3 );
  3035. this.g = hue2rgb( q, p, h );
  3036. this.b = hue2rgb( q, p, h - 1 / 3 );
  3037. }
  3038. return this;
  3039. };
  3040. }(),
  3041. setStyle: function ( style ) {
  3042. function handleAlpha( string ) {
  3043. if ( string === undefined ) return;
  3044. if ( parseFloat( string ) < 1 ) {
  3045. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3046. }
  3047. }
  3048. var m;
  3049. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3050. // rgb / hsl
  3051. var color;
  3052. var name = m[ 1 ];
  3053. var components = m[ 2 ];
  3054. switch ( name ) {
  3055. case 'rgb':
  3056. case 'rgba':
  3057. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3058. // rgb(255,0,0) rgba(255,0,0,0.5)
  3059. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3060. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3061. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3062. handleAlpha( color[ 5 ] );
  3063. return this;
  3064. }
  3065. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3066. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3067. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3068. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3069. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3070. handleAlpha( color[ 5 ] );
  3071. return this;
  3072. }
  3073. break;
  3074. case 'hsl':
  3075. case 'hsla':
  3076. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3077. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3078. var h = parseFloat( color[ 1 ] ) / 360;
  3079. var s = parseInt( color[ 2 ], 10 ) / 100;
  3080. var l = parseInt( color[ 3 ], 10 ) / 100;
  3081. handleAlpha( color[ 5 ] );
  3082. return this.setHSL( h, s, l );
  3083. }
  3084. break;
  3085. }
  3086. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3087. // hex color
  3088. var hex = m[ 1 ];
  3089. var size = hex.length;
  3090. if ( size === 3 ) {
  3091. // #ff0
  3092. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3093. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3094. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3095. return this;
  3096. } else if ( size === 6 ) {
  3097. // #ff0000
  3098. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3099. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3100. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3101. return this;
  3102. }
  3103. }
  3104. if ( style && style.length > 0 ) {
  3105. // color keywords
  3106. var hex = ColorKeywords[ style ];
  3107. if ( hex !== undefined ) {
  3108. // red
  3109. this.setHex( hex );
  3110. } else {
  3111. // unknown color
  3112. console.warn( 'THREE.Color: Unknown color ' + style );
  3113. }
  3114. }
  3115. return this;
  3116. },
  3117. clone: function () {
  3118. return new this.constructor( this.r, this.g, this.b );
  3119. },
  3120. copy: function ( color ) {
  3121. this.r = color.r;
  3122. this.g = color.g;
  3123. this.b = color.b;
  3124. return this;
  3125. },
  3126. copyGammaToLinear: function ( color, gammaFactor ) {
  3127. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3128. this.r = Math.pow( color.r, gammaFactor );
  3129. this.g = Math.pow( color.g, gammaFactor );
  3130. this.b = Math.pow( color.b, gammaFactor );
  3131. return this;
  3132. },
  3133. copyLinearToGamma: function ( color, gammaFactor ) {
  3134. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3135. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3136. this.r = Math.pow( color.r, safeInverse );
  3137. this.g = Math.pow( color.g, safeInverse );
  3138. this.b = Math.pow( color.b, safeInverse );
  3139. return this;
  3140. },
  3141. convertGammaToLinear: function () {
  3142. var r = this.r, g = this.g, b = this.b;
  3143. this.r = r * r;
  3144. this.g = g * g;
  3145. this.b = b * b;
  3146. return this;
  3147. },
  3148. convertLinearToGamma: function () {
  3149. this.r = Math.sqrt( this.r );
  3150. this.g = Math.sqrt( this.g );
  3151. this.b = Math.sqrt( this.b );
  3152. return this;
  3153. },
  3154. getHex: function () {
  3155. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3156. },
  3157. getHexString: function () {
  3158. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3159. },
  3160. getHSL: function ( optionalTarget ) {
  3161. // h,s,l ranges are in 0.0 - 1.0
  3162. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3163. var r = this.r, g = this.g, b = this.b;
  3164. var max = Math.max( r, g, b );
  3165. var min = Math.min( r, g, b );
  3166. var hue, saturation;
  3167. var lightness = ( min + max ) / 2.0;
  3168. if ( min === max ) {
  3169. hue = 0;
  3170. saturation = 0;
  3171. } else {
  3172. var delta = max - min;
  3173. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3174. switch ( max ) {
  3175. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3176. case g: hue = ( b - r ) / delta + 2; break;
  3177. case b: hue = ( r - g ) / delta + 4; break;
  3178. }
  3179. hue /= 6;
  3180. }
  3181. hsl.h = hue;
  3182. hsl.s = saturation;
  3183. hsl.l = lightness;
  3184. return hsl;
  3185. },
  3186. getStyle: function () {
  3187. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3188. },
  3189. offsetHSL: function ( h, s, l ) {
  3190. var hsl = this.getHSL();
  3191. hsl.h += h; hsl.s += s; hsl.l += l;
  3192. this.setHSL( hsl.h, hsl.s, hsl.l );
  3193. return this;
  3194. },
  3195. add: function ( color ) {
  3196. this.r += color.r;
  3197. this.g += color.g;
  3198. this.b += color.b;
  3199. return this;
  3200. },
  3201. addColors: function ( color1, color2 ) {
  3202. this.r = color1.r + color2.r;
  3203. this.g = color1.g + color2.g;
  3204. this.b = color1.b + color2.b;
  3205. return this;
  3206. },
  3207. addScalar: function ( s ) {
  3208. this.r += s;
  3209. this.g += s;
  3210. this.b += s;
  3211. return this;
  3212. },
  3213. sub: function( color ) {
  3214. this.r = Math.max( 0, this.r - color.r );
  3215. this.g = Math.max( 0, this.g - color.g );
  3216. this.b = Math.max( 0, this.b - color.b );
  3217. return this;
  3218. },
  3219. multiply: function ( color ) {
  3220. this.r *= color.r;
  3221. this.g *= color.g;
  3222. this.b *= color.b;
  3223. return this;
  3224. },
  3225. multiplyScalar: function ( s ) {
  3226. this.r *= s;
  3227. this.g *= s;
  3228. this.b *= s;
  3229. return this;
  3230. },
  3231. lerp: function ( color, alpha ) {
  3232. this.r += ( color.r - this.r ) * alpha;
  3233. this.g += ( color.g - this.g ) * alpha;
  3234. this.b += ( color.b - this.b ) * alpha;
  3235. return this;
  3236. },
  3237. equals: function ( c ) {
  3238. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3239. },
  3240. fromArray: function ( array, offset ) {
  3241. if ( offset === undefined ) offset = 0;
  3242. this.r = array[ offset ];
  3243. this.g = array[ offset + 1 ];
  3244. this.b = array[ offset + 2 ];
  3245. return this;
  3246. },
  3247. toArray: function ( array, offset ) {
  3248. if ( array === undefined ) array = [];
  3249. if ( offset === undefined ) offset = 0;
  3250. array[ offset ] = this.r;
  3251. array[ offset + 1 ] = this.g;
  3252. array[ offset + 2 ] = this.b;
  3253. return array;
  3254. },
  3255. toJSON: function () {
  3256. return this.getHex();
  3257. }
  3258. } );
  3259. /**
  3260. * Uniforms library for shared webgl shaders
  3261. */
  3262. var UniformsLib = {
  3263. common: {
  3264. diffuse: { value: new Color( 0xeeeeee ) },
  3265. opacity: { value: 1.0 },
  3266. map: { value: null },
  3267. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3268. specularMap: { value: null },
  3269. alphaMap: { value: null },
  3270. envMap: { value: null },
  3271. flipEnvMap: { value: - 1 },
  3272. reflectivity: { value: 1.0 },
  3273. refractionRatio: { value: 0.98 }
  3274. },
  3275. aomap: {
  3276. aoMap: { value: null },
  3277. aoMapIntensity: { value: 1 }
  3278. },
  3279. lightmap: {
  3280. lightMap: { value: null },
  3281. lightMapIntensity: { value: 1 }
  3282. },
  3283. emissivemap: {
  3284. emissiveMap: { value: null }
  3285. },
  3286. bumpmap: {
  3287. bumpMap: { value: null },
  3288. bumpScale: { value: 1 }
  3289. },
  3290. normalmap: {
  3291. normalMap: { value: null },
  3292. normalScale: { value: new Vector2( 1, 1 ) }
  3293. },
  3294. displacementmap: {
  3295. displacementMap: { value: null },
  3296. displacementScale: { value: 1 },
  3297. displacementBias: { value: 0 }
  3298. },
  3299. roughnessmap: {
  3300. roughnessMap: { value: null }
  3301. },
  3302. metalnessmap: {
  3303. metalnessMap: { value: null }
  3304. },
  3305. gradientmap: {
  3306. gradientMap: { value: null }
  3307. },
  3308. fog: {
  3309. fogDensity: { value: 0.00025 },
  3310. fogNear: { value: 1 },
  3311. fogFar: { value: 2000 },
  3312. fogColor: { value: new Color( 0xffffff ) }
  3313. },
  3314. lights: {
  3315. ambientLightColor: { value: [] },
  3316. directionalLights: { value: [], properties: {
  3317. direction: {},
  3318. color: {},
  3319. shadow: {},
  3320. shadowBias: {},
  3321. shadowRadius: {},
  3322. shadowMapSize: {}
  3323. } },
  3324. directionalShadowMap: { value: [] },
  3325. directionalShadowMatrix: { value: [] },
  3326. spotLights: { value: [], properties: {
  3327. color: {},
  3328. position: {},
  3329. direction: {},
  3330. distance: {},
  3331. coneCos: {},
  3332. penumbraCos: {},
  3333. decay: {},
  3334. shadow: {},
  3335. shadowBias: {},
  3336. shadowRadius: {},
  3337. shadowMapSize: {}
  3338. } },
  3339. spotShadowMap: { value: [] },
  3340. spotShadowMatrix: { value: [] },
  3341. pointLights: { value: [], properties: {
  3342. color: {},
  3343. position: {},
  3344. decay: {},
  3345. distance: {},
  3346. shadow: {},
  3347. shadowBias: {},
  3348. shadowRadius: {},
  3349. shadowMapSize: {}
  3350. } },
  3351. pointShadowMap: { value: [] },
  3352. pointShadowMatrix: { value: [] },
  3353. hemisphereLights: { value: [], properties: {
  3354. direction: {},
  3355. skyColor: {},
  3356. groundColor: {}
  3357. } },
  3358. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3359. rectAreaLights: { value: [], properties: {
  3360. color: {},
  3361. position: {},
  3362. width: {},
  3363. height: {}
  3364. } }
  3365. },
  3366. points: {
  3367. diffuse: { value: new Color( 0xeeeeee ) },
  3368. opacity: { value: 1.0 },
  3369. size: { value: 1.0 },
  3370. scale: { value: 1.0 },
  3371. map: { value: null },
  3372. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3373. }
  3374. };
  3375. /**
  3376. * Uniform Utilities
  3377. */
  3378. var UniformsUtils = {
  3379. merge: function ( uniforms ) {
  3380. var merged = {};
  3381. for ( var u = 0; u < uniforms.length; u ++ ) {
  3382. var tmp = this.clone( uniforms[ u ] );
  3383. for ( var p in tmp ) {
  3384. merged[ p ] = tmp[ p ];
  3385. }
  3386. }
  3387. return merged;
  3388. },
  3389. clone: function ( uniforms_src ) {
  3390. var uniforms_dst = {};
  3391. for ( var u in uniforms_src ) {
  3392. uniforms_dst[ u ] = {};
  3393. for ( var p in uniforms_src[ u ] ) {
  3394. var parameter_src = uniforms_src[ u ][ p ];
  3395. if ( parameter_src && ( parameter_src.isColor ||
  3396. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3397. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3398. parameter_src.isTexture ) ) {
  3399. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3400. } else if ( Array.isArray( parameter_src ) ) {
  3401. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3402. } else {
  3403. uniforms_dst[ u ][ p ] = parameter_src;
  3404. }
  3405. }
  3406. }
  3407. return uniforms_dst;
  3408. }
  3409. };
  3410. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3411. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3412. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3413. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  3414. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3415. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3416. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3417. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  3418. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3419. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  3420. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  3421. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3422. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3423. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3424. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3425. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3426. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3427. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  3428. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  3429. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3430. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3431. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3432. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  3433. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3434. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3435. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3436. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3437. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  3438. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  3439. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  3440. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3441. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3442. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3443. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n";
  3444. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";
  3445. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3446. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3447. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  3448. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  3449. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3450. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3451. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  3452. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  3453. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3454. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3455. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  3456. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  3457. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  3458. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3459. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3460. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  3461. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3462. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3463. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3464. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  3465. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  3466. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  3467. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  3468. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  3469. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3470. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3471. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3472. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3473. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3474. var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n";
  3475. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3476. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3477. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3478. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  3479. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  3480. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3481. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  3482. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  3483. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3484. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  3485. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  3486. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3487. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3488. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3489. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  3490. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  3491. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  3492. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3493. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3494. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3495. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3496. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3497. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3498. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  3499. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3500. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  3501. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  3502. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3503. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3504. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3505. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n";
  3506. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3507. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3508. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3509. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3510. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3511. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3512. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3513. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3514. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3515. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3516. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3517. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3518. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3519. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3520. var ShaderChunk = {
  3521. alphamap_fragment: alphamap_fragment,
  3522. alphamap_pars_fragment: alphamap_pars_fragment,
  3523. alphatest_fragment: alphatest_fragment,
  3524. aomap_fragment: aomap_fragment,
  3525. aomap_pars_fragment: aomap_pars_fragment,
  3526. begin_vertex: begin_vertex,
  3527. beginnormal_vertex: beginnormal_vertex,
  3528. bsdfs: bsdfs,
  3529. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3530. clipping_planes_fragment: clipping_planes_fragment,
  3531. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3532. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3533. clipping_planes_vertex: clipping_planes_vertex,
  3534. color_fragment: color_fragment,
  3535. color_pars_fragment: color_pars_fragment,
  3536. color_pars_vertex: color_pars_vertex,
  3537. color_vertex: color_vertex,
  3538. common: common,
  3539. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3540. defaultnormal_vertex: defaultnormal_vertex,
  3541. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3542. displacementmap_vertex: displacementmap_vertex,
  3543. emissivemap_fragment: emissivemap_fragment,
  3544. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3545. encodings_fragment: encodings_fragment,
  3546. encodings_pars_fragment: encodings_pars_fragment,
  3547. envmap_fragment: envmap_fragment,
  3548. envmap_pars_fragment: envmap_pars_fragment,
  3549. envmap_pars_vertex: envmap_pars_vertex,
  3550. envmap_vertex: envmap_vertex,
  3551. fog_vertex: fog_vertex,
  3552. fog_pars_vertex: fog_pars_vertex,
  3553. fog_fragment: fog_fragment,
  3554. fog_pars_fragment: fog_pars_fragment,
  3555. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3556. lightmap_fragment: lightmap_fragment,
  3557. lightmap_pars_fragment: lightmap_pars_fragment,
  3558. lights_lambert_vertex: lights_lambert_vertex,
  3559. lights_pars: lights_pars,
  3560. lights_phong_fragment: lights_phong_fragment,
  3561. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3562. lights_physical_fragment: lights_physical_fragment,
  3563. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3564. lights_template: lights_template,
  3565. logdepthbuf_fragment: logdepthbuf_fragment,
  3566. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3567. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3568. logdepthbuf_vertex: logdepthbuf_vertex,
  3569. map_fragment: map_fragment,
  3570. map_pars_fragment: map_pars_fragment,
  3571. map_particle_fragment: map_particle_fragment,
  3572. map_particle_pars_fragment: map_particle_pars_fragment,
  3573. metalnessmap_fragment: metalnessmap_fragment,
  3574. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3575. morphnormal_vertex: morphnormal_vertex,
  3576. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3577. morphtarget_vertex: morphtarget_vertex,
  3578. normal_flip: normal_flip,
  3579. normal_fragment: normal_fragment,
  3580. normalmap_pars_fragment: normalmap_pars_fragment,
  3581. packing: packing,
  3582. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3583. project_vertex: project_vertex,
  3584. dithering_fragment: dithering_fragment,
  3585. dithering_pars_fragment: dithering_pars_fragment,
  3586. roughnessmap_fragment: roughnessmap_fragment,
  3587. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3588. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3589. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3590. shadowmap_vertex: shadowmap_vertex,
  3591. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3592. skinbase_vertex: skinbase_vertex,
  3593. skinning_pars_vertex: skinning_pars_vertex,
  3594. skinning_vertex: skinning_vertex,
  3595. skinnormal_vertex: skinnormal_vertex,
  3596. specularmap_fragment: specularmap_fragment,
  3597. specularmap_pars_fragment: specularmap_pars_fragment,
  3598. tonemapping_fragment: tonemapping_fragment,
  3599. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3600. uv_pars_fragment: uv_pars_fragment,
  3601. uv_pars_vertex: uv_pars_vertex,
  3602. uv_vertex: uv_vertex,
  3603. uv2_pars_fragment: uv2_pars_fragment,
  3604. uv2_pars_vertex: uv2_pars_vertex,
  3605. uv2_vertex: uv2_vertex,
  3606. worldpos_vertex: worldpos_vertex,
  3607. cube_frag: cube_frag,
  3608. cube_vert: cube_vert,
  3609. depth_frag: depth_frag,
  3610. depth_vert: depth_vert,
  3611. distanceRGBA_frag: distanceRGBA_frag,
  3612. distanceRGBA_vert: distanceRGBA_vert,
  3613. equirect_frag: equirect_frag,
  3614. equirect_vert: equirect_vert,
  3615. linedashed_frag: linedashed_frag,
  3616. linedashed_vert: linedashed_vert,
  3617. meshbasic_frag: meshbasic_frag,
  3618. meshbasic_vert: meshbasic_vert,
  3619. meshlambert_frag: meshlambert_frag,
  3620. meshlambert_vert: meshlambert_vert,
  3621. meshphong_frag: meshphong_frag,
  3622. meshphong_vert: meshphong_vert,
  3623. meshphysical_frag: meshphysical_frag,
  3624. meshphysical_vert: meshphysical_vert,
  3625. normal_frag: normal_frag,
  3626. normal_vert: normal_vert,
  3627. points_frag: points_frag,
  3628. points_vert: points_vert,
  3629. shadow_frag: shadow_frag,
  3630. shadow_vert: shadow_vert
  3631. };
  3632. /**
  3633. * @author alteredq / http://alteredqualia.com/
  3634. * @author mrdoob / http://mrdoob.com/
  3635. * @author mikael emtinger / http://gomo.se/
  3636. */
  3637. var ShaderLib = {
  3638. basic: {
  3639. uniforms: UniformsUtils.merge( [
  3640. UniformsLib.common,
  3641. UniformsLib.aomap,
  3642. UniformsLib.lightmap,
  3643. UniformsLib.fog
  3644. ] ),
  3645. vertexShader: ShaderChunk.meshbasic_vert,
  3646. fragmentShader: ShaderChunk.meshbasic_frag
  3647. },
  3648. lambert: {
  3649. uniforms: UniformsUtils.merge( [
  3650. UniformsLib.common,
  3651. UniformsLib.aomap,
  3652. UniformsLib.lightmap,
  3653. UniformsLib.emissivemap,
  3654. UniformsLib.fog,
  3655. UniformsLib.lights,
  3656. {
  3657. emissive: { value: new Color( 0x000000 ) }
  3658. }
  3659. ] ),
  3660. vertexShader: ShaderChunk.meshlambert_vert,
  3661. fragmentShader: ShaderChunk.meshlambert_frag
  3662. },
  3663. phong: {
  3664. uniforms: UniformsUtils.merge( [
  3665. UniformsLib.common,
  3666. UniformsLib.aomap,
  3667. UniformsLib.lightmap,
  3668. UniformsLib.emissivemap,
  3669. UniformsLib.bumpmap,
  3670. UniformsLib.normalmap,
  3671. UniformsLib.displacementmap,
  3672. UniformsLib.gradientmap,
  3673. UniformsLib.fog,
  3674. UniformsLib.lights,
  3675. {
  3676. emissive: { value: new Color( 0x000000 ) },
  3677. specular: { value: new Color( 0x111111 ) },
  3678. shininess: { value: 30 }
  3679. }
  3680. ] ),
  3681. vertexShader: ShaderChunk.meshphong_vert,
  3682. fragmentShader: ShaderChunk.meshphong_frag
  3683. },
  3684. standard: {
  3685. uniforms: UniformsUtils.merge( [
  3686. UniformsLib.common,
  3687. UniformsLib.aomap,
  3688. UniformsLib.lightmap,
  3689. UniformsLib.emissivemap,
  3690. UniformsLib.bumpmap,
  3691. UniformsLib.normalmap,
  3692. UniformsLib.displacementmap,
  3693. UniformsLib.roughnessmap,
  3694. UniformsLib.metalnessmap,
  3695. UniformsLib.fog,
  3696. UniformsLib.lights,
  3697. {
  3698. emissive: { value: new Color( 0x000000 ) },
  3699. roughness: { value: 0.5 },
  3700. metalness: { value: 0.5 },
  3701. envMapIntensity: { value: 1 } // temporary
  3702. }
  3703. ] ),
  3704. vertexShader: ShaderChunk.meshphysical_vert,
  3705. fragmentShader: ShaderChunk.meshphysical_frag
  3706. },
  3707. points: {
  3708. uniforms: UniformsUtils.merge( [
  3709. UniformsLib.points,
  3710. UniformsLib.fog
  3711. ] ),
  3712. vertexShader: ShaderChunk.points_vert,
  3713. fragmentShader: ShaderChunk.points_frag
  3714. },
  3715. dashed: {
  3716. uniforms: UniformsUtils.merge( [
  3717. UniformsLib.common,
  3718. UniformsLib.fog,
  3719. {
  3720. scale: { value: 1 },
  3721. dashSize: { value: 1 },
  3722. totalSize: { value: 2 }
  3723. }
  3724. ] ),
  3725. vertexShader: ShaderChunk.linedashed_vert,
  3726. fragmentShader: ShaderChunk.linedashed_frag
  3727. },
  3728. depth: {
  3729. uniforms: UniformsUtils.merge( [
  3730. UniformsLib.common,
  3731. UniformsLib.displacementmap
  3732. ] ),
  3733. vertexShader: ShaderChunk.depth_vert,
  3734. fragmentShader: ShaderChunk.depth_frag
  3735. },
  3736. normal: {
  3737. uniforms: UniformsUtils.merge( [
  3738. UniformsLib.common,
  3739. UniformsLib.bumpmap,
  3740. UniformsLib.normalmap,
  3741. UniformsLib.displacementmap,
  3742. {
  3743. opacity: { value: 1.0 }
  3744. }
  3745. ] ),
  3746. vertexShader: ShaderChunk.normal_vert,
  3747. fragmentShader: ShaderChunk.normal_frag
  3748. },
  3749. /* -------------------------------------------------------------------------
  3750. // Cube map shader
  3751. ------------------------------------------------------------------------- */
  3752. cube: {
  3753. uniforms: {
  3754. tCube: { value: null },
  3755. tFlip: { value: - 1 },
  3756. opacity: { value: 1.0 }
  3757. },
  3758. vertexShader: ShaderChunk.cube_vert,
  3759. fragmentShader: ShaderChunk.cube_frag
  3760. },
  3761. /* -------------------------------------------------------------------------
  3762. // Cube map shader
  3763. ------------------------------------------------------------------------- */
  3764. equirect: {
  3765. uniforms: {
  3766. tEquirect: { value: null },
  3767. tFlip: { value: - 1 }
  3768. },
  3769. vertexShader: ShaderChunk.equirect_vert,
  3770. fragmentShader: ShaderChunk.equirect_frag
  3771. },
  3772. distanceRGBA: {
  3773. uniforms: {
  3774. lightPos: { value: new Vector3() }
  3775. },
  3776. vertexShader: ShaderChunk.distanceRGBA_vert,
  3777. fragmentShader: ShaderChunk.distanceRGBA_frag
  3778. }
  3779. };
  3780. ShaderLib.physical = {
  3781. uniforms: UniformsUtils.merge( [
  3782. ShaderLib.standard.uniforms,
  3783. {
  3784. clearCoat: { value: 0 },
  3785. clearCoatRoughness: { value: 0 }
  3786. }
  3787. ] ),
  3788. vertexShader: ShaderChunk.meshphysical_vert,
  3789. fragmentShader: ShaderChunk.meshphysical_frag
  3790. };
  3791. /**
  3792. * @author bhouston / http://clara.io
  3793. */
  3794. function Box2( min, max ) {
  3795. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3796. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3797. }
  3798. Object.assign( Box2.prototype, {
  3799. set: function ( min, max ) {
  3800. this.min.copy( min );
  3801. this.max.copy( max );
  3802. return this;
  3803. },
  3804. setFromPoints: function ( points ) {
  3805. this.makeEmpty();
  3806. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3807. this.expandByPoint( points[ i ] );
  3808. }
  3809. return this;
  3810. },
  3811. setFromCenterAndSize: function () {
  3812. var v1 = new Vector2();
  3813. return function setFromCenterAndSize( center, size ) {
  3814. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3815. this.min.copy( center ).sub( halfSize );
  3816. this.max.copy( center ).add( halfSize );
  3817. return this;
  3818. };
  3819. }(),
  3820. clone: function () {
  3821. return new this.constructor().copy( this );
  3822. },
  3823. copy: function ( box ) {
  3824. this.min.copy( box.min );
  3825. this.max.copy( box.max );
  3826. return this;
  3827. },
  3828. makeEmpty: function () {
  3829. this.min.x = this.min.y = + Infinity;
  3830. this.max.x = this.max.y = - Infinity;
  3831. return this;
  3832. },
  3833. isEmpty: function () {
  3834. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3835. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3836. },
  3837. getCenter: function ( optionalTarget ) {
  3838. var result = optionalTarget || new Vector2();
  3839. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3840. },
  3841. getSize: function ( optionalTarget ) {
  3842. var result = optionalTarget || new Vector2();
  3843. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3844. },
  3845. expandByPoint: function ( point ) {
  3846. this.min.min( point );
  3847. this.max.max( point );
  3848. return this;
  3849. },
  3850. expandByVector: function ( vector ) {
  3851. this.min.sub( vector );
  3852. this.max.add( vector );
  3853. return this;
  3854. },
  3855. expandByScalar: function ( scalar ) {
  3856. this.min.addScalar( - scalar );
  3857. this.max.addScalar( scalar );
  3858. return this;
  3859. },
  3860. containsPoint: function ( point ) {
  3861. return point.x < this.min.x || point.x > this.max.x ||
  3862. point.y < this.min.y || point.y > this.max.y ? false : true;
  3863. },
  3864. containsBox: function ( box ) {
  3865. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3866. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3867. },
  3868. getParameter: function ( point, optionalTarget ) {
  3869. // This can potentially have a divide by zero if the box
  3870. // has a size dimension of 0.
  3871. var result = optionalTarget || new Vector2();
  3872. return result.set(
  3873. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3874. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3875. );
  3876. },
  3877. intersectsBox: function ( box ) {
  3878. // using 4 splitting planes to rule out intersections
  3879. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3880. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3881. },
  3882. clampPoint: function ( point, optionalTarget ) {
  3883. var result = optionalTarget || new Vector2();
  3884. return result.copy( point ).clamp( this.min, this.max );
  3885. },
  3886. distanceToPoint: function () {
  3887. var v1 = new Vector2();
  3888. return function distanceToPoint( point ) {
  3889. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3890. return clampedPoint.sub( point ).length();
  3891. };
  3892. }(),
  3893. intersect: function ( box ) {
  3894. this.min.max( box.min );
  3895. this.max.min( box.max );
  3896. return this;
  3897. },
  3898. union: function ( box ) {
  3899. this.min.min( box.min );
  3900. this.max.max( box.max );
  3901. return this;
  3902. },
  3903. translate: function ( offset ) {
  3904. this.min.add( offset );
  3905. this.max.add( offset );
  3906. return this;
  3907. },
  3908. equals: function ( box ) {
  3909. return box.min.equals( this.min ) && box.max.equals( this.max );
  3910. }
  3911. } );
  3912. /**
  3913. * @author mikael emtinger / http://gomo.se/
  3914. * @author alteredq / http://alteredqualia.com/
  3915. */
  3916. function LensFlarePlugin( renderer, flares ) {
  3917. var gl = renderer.context;
  3918. var state = renderer.state;
  3919. var vertexBuffer, elementBuffer;
  3920. var shader, program, attributes, uniforms;
  3921. var tempTexture, occlusionTexture;
  3922. function init() {
  3923. var vertices = new Float32Array( [
  3924. - 1, - 1, 0, 0,
  3925. 1, - 1, 1, 0,
  3926. 1, 1, 1, 1,
  3927. - 1, 1, 0, 1
  3928. ] );
  3929. var faces = new Uint16Array( [
  3930. 0, 1, 2,
  3931. 0, 2, 3
  3932. ] );
  3933. // buffers
  3934. vertexBuffer = gl.createBuffer();
  3935. elementBuffer = gl.createBuffer();
  3936. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3937. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3938. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3939. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3940. // textures
  3941. tempTexture = gl.createTexture();
  3942. occlusionTexture = gl.createTexture();
  3943. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3944. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3945. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3946. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3947. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3948. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3949. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3950. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3951. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3952. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3953. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3954. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3955. shader = {
  3956. vertexShader: [
  3957. "uniform lowp int renderType;",
  3958. "uniform vec3 screenPosition;",
  3959. "uniform vec2 scale;",
  3960. "uniform float rotation;",
  3961. "uniform sampler2D occlusionMap;",
  3962. "attribute vec2 position;",
  3963. "attribute vec2 uv;",
  3964. "varying vec2 vUV;",
  3965. "varying float vVisibility;",
  3966. "void main() {",
  3967. "vUV = uv;",
  3968. "vec2 pos = position;",
  3969. "if ( renderType == 2 ) {",
  3970. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3971. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3972. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3973. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3974. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3975. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3976. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3977. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3978. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3979. "vVisibility = visibility.r / 9.0;",
  3980. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3981. "vVisibility *= visibility.b / 9.0;",
  3982. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3983. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3984. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3985. "}",
  3986. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3987. "}"
  3988. ].join( "\n" ),
  3989. fragmentShader: [
  3990. "uniform lowp int renderType;",
  3991. "uniform sampler2D map;",
  3992. "uniform float opacity;",
  3993. "uniform vec3 color;",
  3994. "varying vec2 vUV;",
  3995. "varying float vVisibility;",
  3996. "void main() {",
  3997. // pink square
  3998. "if ( renderType == 0 ) {",
  3999. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4000. // restore
  4001. "} else if ( renderType == 1 ) {",
  4002. "gl_FragColor = texture2D( map, vUV );",
  4003. // flare
  4004. "} else {",
  4005. "vec4 texture = texture2D( map, vUV );",
  4006. "texture.a *= opacity * vVisibility;",
  4007. "gl_FragColor = texture;",
  4008. "gl_FragColor.rgb *= color;",
  4009. "}",
  4010. "}"
  4011. ].join( "\n" )
  4012. };
  4013. program = createProgram( shader );
  4014. attributes = {
  4015. vertex: gl.getAttribLocation ( program, "position" ),
  4016. uv: gl.getAttribLocation ( program, "uv" )
  4017. };
  4018. uniforms = {
  4019. renderType: gl.getUniformLocation( program, "renderType" ),
  4020. map: gl.getUniformLocation( program, "map" ),
  4021. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4022. opacity: gl.getUniformLocation( program, "opacity" ),
  4023. color: gl.getUniformLocation( program, "color" ),
  4024. scale: gl.getUniformLocation( program, "scale" ),
  4025. rotation: gl.getUniformLocation( program, "rotation" ),
  4026. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4027. };
  4028. }
  4029. /*
  4030. * Render lens flares
  4031. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4032. * reads these back and calculates occlusion.
  4033. */
  4034. this.render = function ( scene, camera, viewport ) {
  4035. if ( flares.length === 0 ) return;
  4036. var tempPosition = new Vector3();
  4037. var invAspect = viewport.w / viewport.z,
  4038. halfViewportWidth = viewport.z * 0.5,
  4039. halfViewportHeight = viewport.w * 0.5;
  4040. var size = 16 / viewport.w,
  4041. scale = new Vector2( size * invAspect, size );
  4042. var screenPosition = new Vector3( 1, 1, 0 ),
  4043. screenPositionPixels = new Vector2( 1, 1 );
  4044. var validArea = new Box2();
  4045. validArea.min.set( viewport.x, viewport.y );
  4046. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4047. if ( program === undefined ) {
  4048. init();
  4049. }
  4050. gl.useProgram( program );
  4051. state.initAttributes();
  4052. state.enableAttribute( attributes.vertex );
  4053. state.enableAttribute( attributes.uv );
  4054. state.disableUnusedAttributes();
  4055. // loop through all lens flares to update their occlusion and positions
  4056. // setup gl and common used attribs/uniforms
  4057. gl.uniform1i( uniforms.occlusionMap, 0 );
  4058. gl.uniform1i( uniforms.map, 1 );
  4059. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4060. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4061. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4062. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4063. state.disable( gl.CULL_FACE );
  4064. state.buffers.depth.setMask( false );
  4065. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4066. size = 16 / viewport.w;
  4067. scale.set( size * invAspect, size );
  4068. // calc object screen position
  4069. var flare = flares[ i ];
  4070. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4071. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4072. tempPosition.applyMatrix4( camera.projectionMatrix );
  4073. // setup arrays for gl programs
  4074. screenPosition.copy( tempPosition );
  4075. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4076. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4077. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4078. // screen cull
  4079. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4080. // save current RGB to temp texture
  4081. state.activeTexture( gl.TEXTURE0 );
  4082. state.bindTexture( gl.TEXTURE_2D, null );
  4083. state.activeTexture( gl.TEXTURE1 );
  4084. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4085. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4086. // render pink quad
  4087. gl.uniform1i( uniforms.renderType, 0 );
  4088. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4089. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4090. state.disable( gl.BLEND );
  4091. state.enable( gl.DEPTH_TEST );
  4092. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4093. // copy result to occlusionMap
  4094. state.activeTexture( gl.TEXTURE0 );
  4095. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4096. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4097. // restore graphics
  4098. gl.uniform1i( uniforms.renderType, 1 );
  4099. state.disable( gl.DEPTH_TEST );
  4100. state.activeTexture( gl.TEXTURE1 );
  4101. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4102. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4103. // update object positions
  4104. flare.positionScreen.copy( screenPosition );
  4105. if ( flare.customUpdateCallback ) {
  4106. flare.customUpdateCallback( flare );
  4107. } else {
  4108. flare.updateLensFlares();
  4109. }
  4110. // render flares
  4111. gl.uniform1i( uniforms.renderType, 2 );
  4112. state.enable( gl.BLEND );
  4113. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4114. var sprite = flare.lensFlares[ j ];
  4115. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4116. screenPosition.x = sprite.x;
  4117. screenPosition.y = sprite.y;
  4118. screenPosition.z = sprite.z;
  4119. size = sprite.size * sprite.scale / viewport.w;
  4120. scale.x = size * invAspect;
  4121. scale.y = size;
  4122. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4123. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4124. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4125. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4126. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4127. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4128. renderer.setTexture2D( sprite.texture, 1 );
  4129. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4130. }
  4131. }
  4132. }
  4133. }
  4134. // restore gl
  4135. state.enable( gl.CULL_FACE );
  4136. state.enable( gl.DEPTH_TEST );
  4137. state.buffers.depth.setMask( true );
  4138. renderer.resetGLState();
  4139. };
  4140. function createProgram( shader ) {
  4141. var program = gl.createProgram();
  4142. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4143. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4144. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4145. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4146. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4147. gl.compileShader( fragmentShader );
  4148. gl.compileShader( vertexShader );
  4149. gl.attachShader( program, fragmentShader );
  4150. gl.attachShader( program, vertexShader );
  4151. gl.linkProgram( program );
  4152. return program;
  4153. }
  4154. }
  4155. /**
  4156. * @author mikael emtinger / http://gomo.se/
  4157. * @author alteredq / http://alteredqualia.com/
  4158. */
  4159. function SpritePlugin( renderer, sprites ) {
  4160. var gl = renderer.context;
  4161. var state = renderer.state;
  4162. var vertexBuffer, elementBuffer;
  4163. var program, attributes, uniforms;
  4164. var texture;
  4165. // decompose matrixWorld
  4166. var spritePosition = new Vector3();
  4167. var spriteRotation = new Quaternion();
  4168. var spriteScale = new Vector3();
  4169. function init() {
  4170. var vertices = new Float32Array( [
  4171. - 0.5, - 0.5, 0, 0,
  4172. 0.5, - 0.5, 1, 0,
  4173. 0.5, 0.5, 1, 1,
  4174. - 0.5, 0.5, 0, 1
  4175. ] );
  4176. var faces = new Uint16Array( [
  4177. 0, 1, 2,
  4178. 0, 2, 3
  4179. ] );
  4180. vertexBuffer = gl.createBuffer();
  4181. elementBuffer = gl.createBuffer();
  4182. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4183. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4184. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4185. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4186. program = createProgram();
  4187. attributes = {
  4188. position: gl.getAttribLocation ( program, 'position' ),
  4189. uv: gl.getAttribLocation ( program, 'uv' )
  4190. };
  4191. uniforms = {
  4192. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4193. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4194. rotation: gl.getUniformLocation( program, 'rotation' ),
  4195. scale: gl.getUniformLocation( program, 'scale' ),
  4196. color: gl.getUniformLocation( program, 'color' ),
  4197. map: gl.getUniformLocation( program, 'map' ),
  4198. opacity: gl.getUniformLocation( program, 'opacity' ),
  4199. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4200. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4201. fogType: gl.getUniformLocation( program, 'fogType' ),
  4202. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4203. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4204. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4205. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4206. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4207. };
  4208. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4209. canvas.width = 8;
  4210. canvas.height = 8;
  4211. var context = canvas.getContext( '2d' );
  4212. context.fillStyle = 'white';
  4213. context.fillRect( 0, 0, 8, 8 );
  4214. texture = new Texture( canvas );
  4215. texture.needsUpdate = true;
  4216. }
  4217. this.render = function ( scene, camera ) {
  4218. if ( sprites.length === 0 ) return;
  4219. // setup gl
  4220. if ( program === undefined ) {
  4221. init();
  4222. }
  4223. gl.useProgram( program );
  4224. state.initAttributes();
  4225. state.enableAttribute( attributes.position );
  4226. state.enableAttribute( attributes.uv );
  4227. state.disableUnusedAttributes();
  4228. state.disable( gl.CULL_FACE );
  4229. state.enable( gl.BLEND );
  4230. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4231. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4232. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4233. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4234. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4235. state.activeTexture( gl.TEXTURE0 );
  4236. gl.uniform1i( uniforms.map, 0 );
  4237. var oldFogType = 0;
  4238. var sceneFogType = 0;
  4239. var fog = scene.fog;
  4240. if ( fog ) {
  4241. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4242. if ( fog.isFog ) {
  4243. gl.uniform1f( uniforms.fogNear, fog.near );
  4244. gl.uniform1f( uniforms.fogFar, fog.far );
  4245. gl.uniform1i( uniforms.fogType, 1 );
  4246. oldFogType = 1;
  4247. sceneFogType = 1;
  4248. } else if ( fog.isFogExp2 ) {
  4249. gl.uniform1f( uniforms.fogDensity, fog.density );
  4250. gl.uniform1i( uniforms.fogType, 2 );
  4251. oldFogType = 2;
  4252. sceneFogType = 2;
  4253. }
  4254. } else {
  4255. gl.uniform1i( uniforms.fogType, 0 );
  4256. oldFogType = 0;
  4257. sceneFogType = 0;
  4258. }
  4259. // update positions and sort
  4260. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4261. var sprite = sprites[ i ];
  4262. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4263. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4264. }
  4265. sprites.sort( painterSortStable );
  4266. // render all sprites
  4267. var scale = [];
  4268. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4269. var sprite = sprites[ i ];
  4270. var material = sprite.material;
  4271. if ( material.visible === false ) continue;
  4272. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4273. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4274. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4275. scale[ 0 ] = spriteScale.x;
  4276. scale[ 1 ] = spriteScale.y;
  4277. var fogType = 0;
  4278. if ( scene.fog && material.fog ) {
  4279. fogType = sceneFogType;
  4280. }
  4281. if ( oldFogType !== fogType ) {
  4282. gl.uniform1i( uniforms.fogType, fogType );
  4283. oldFogType = fogType;
  4284. }
  4285. if ( material.map !== null ) {
  4286. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4287. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4288. } else {
  4289. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4290. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4291. }
  4292. gl.uniform1f( uniforms.opacity, material.opacity );
  4293. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4294. gl.uniform1f( uniforms.rotation, material.rotation );
  4295. gl.uniform2fv( uniforms.scale, scale );
  4296. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4297. state.buffers.depth.setTest( material.depthTest );
  4298. state.buffers.depth.setMask( material.depthWrite );
  4299. if ( material.map ) {
  4300. renderer.setTexture2D( material.map, 0 );
  4301. } else {
  4302. renderer.setTexture2D( texture, 0 );
  4303. }
  4304. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4305. }
  4306. // restore gl
  4307. state.enable( gl.CULL_FACE );
  4308. renderer.resetGLState();
  4309. };
  4310. function createProgram() {
  4311. var program = gl.createProgram();
  4312. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4313. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4314. gl.shaderSource( vertexShader, [
  4315. 'precision ' + renderer.getPrecision() + ' float;',
  4316. 'uniform mat4 modelViewMatrix;',
  4317. 'uniform mat4 projectionMatrix;',
  4318. 'uniform float rotation;',
  4319. 'uniform vec2 scale;',
  4320. 'uniform vec2 uvOffset;',
  4321. 'uniform vec2 uvScale;',
  4322. 'attribute vec2 position;',
  4323. 'attribute vec2 uv;',
  4324. 'varying vec2 vUV;',
  4325. 'void main() {',
  4326. 'vUV = uvOffset + uv * uvScale;',
  4327. 'vec2 alignedPosition = position * scale;',
  4328. 'vec2 rotatedPosition;',
  4329. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4330. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4331. 'vec4 finalPosition;',
  4332. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4333. 'finalPosition.xy += rotatedPosition;',
  4334. 'finalPosition = projectionMatrix * finalPosition;',
  4335. 'gl_Position = finalPosition;',
  4336. '}'
  4337. ].join( '\n' ) );
  4338. gl.shaderSource( fragmentShader, [
  4339. 'precision ' + renderer.getPrecision() + ' float;',
  4340. 'uniform vec3 color;',
  4341. 'uniform sampler2D map;',
  4342. 'uniform float opacity;',
  4343. 'uniform int fogType;',
  4344. 'uniform vec3 fogColor;',
  4345. 'uniform float fogDensity;',
  4346. 'uniform float fogNear;',
  4347. 'uniform float fogFar;',
  4348. 'uniform float alphaTest;',
  4349. 'varying vec2 vUV;',
  4350. 'void main() {',
  4351. 'vec4 texture = texture2D( map, vUV );',
  4352. 'if ( texture.a < alphaTest ) discard;',
  4353. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4354. 'if ( fogType > 0 ) {',
  4355. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4356. 'float fogFactor = 0.0;',
  4357. 'if ( fogType == 1 ) {',
  4358. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4359. '} else {',
  4360. 'const float LOG2 = 1.442695;',
  4361. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4362. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4363. '}',
  4364. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4365. '}',
  4366. '}'
  4367. ].join( '\n' ) );
  4368. gl.compileShader( vertexShader );
  4369. gl.compileShader( fragmentShader );
  4370. gl.attachShader( program, vertexShader );
  4371. gl.attachShader( program, fragmentShader );
  4372. gl.linkProgram( program );
  4373. return program;
  4374. }
  4375. function painterSortStable( a, b ) {
  4376. if ( a.renderOrder !== b.renderOrder ) {
  4377. return a.renderOrder - b.renderOrder;
  4378. } else if ( a.z !== b.z ) {
  4379. return b.z - a.z;
  4380. } else {
  4381. return b.id - a.id;
  4382. }
  4383. }
  4384. }
  4385. /**
  4386. * @author mrdoob / http://mrdoob.com/
  4387. * @author alteredq / http://alteredqualia.com/
  4388. */
  4389. var materialId = 0;
  4390. function Material() {
  4391. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4392. this.uuid = _Math.generateUUID();
  4393. this.name = '';
  4394. this.type = 'Material';
  4395. this.fog = true;
  4396. this.lights = true;
  4397. this.blending = NormalBlending;
  4398. this.side = FrontSide;
  4399. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4400. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4401. this.opacity = 1;
  4402. this.transparent = false;
  4403. this.blendSrc = SrcAlphaFactor;
  4404. this.blendDst = OneMinusSrcAlphaFactor;
  4405. this.blendEquation = AddEquation;
  4406. this.blendSrcAlpha = null;
  4407. this.blendDstAlpha = null;
  4408. this.blendEquationAlpha = null;
  4409. this.depthFunc = LessEqualDepth;
  4410. this.depthTest = true;
  4411. this.depthWrite = true;
  4412. this.clippingPlanes = null;
  4413. this.clipIntersection = false;
  4414. this.clipShadows = false;
  4415. this.colorWrite = true;
  4416. this.precision = null; // override the renderer's default precision for this material
  4417. this.polygonOffset = false;
  4418. this.polygonOffsetFactor = 0;
  4419. this.polygonOffsetUnits = 0;
  4420. this.dithering = false;
  4421. this.alphaTest = 0;
  4422. this.premultipliedAlpha = false;
  4423. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4424. this.visible = true;
  4425. this.needsUpdate = true;
  4426. }
  4427. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4428. isMaterial: true,
  4429. setValues: function ( values ) {
  4430. if ( values === undefined ) return;
  4431. for ( var key in values ) {
  4432. var newValue = values[ key ];
  4433. if ( newValue === undefined ) {
  4434. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4435. continue;
  4436. }
  4437. var currentValue = this[ key ];
  4438. if ( currentValue === undefined ) {
  4439. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4440. continue;
  4441. }
  4442. if ( currentValue && currentValue.isColor ) {
  4443. currentValue.set( newValue );
  4444. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4445. currentValue.copy( newValue );
  4446. } else if ( key === 'overdraw' ) {
  4447. // ensure overdraw is backwards-compatible with legacy boolean type
  4448. this[ key ] = Number( newValue );
  4449. } else {
  4450. this[ key ] = newValue;
  4451. }
  4452. }
  4453. },
  4454. toJSON: function ( meta ) {
  4455. var isRoot = meta === undefined;
  4456. if ( isRoot ) {
  4457. meta = {
  4458. textures: {},
  4459. images: {}
  4460. };
  4461. }
  4462. var data = {
  4463. metadata: {
  4464. version: 4.5,
  4465. type: 'Material',
  4466. generator: 'Material.toJSON'
  4467. }
  4468. };
  4469. // standard Material serialization
  4470. data.uuid = this.uuid;
  4471. data.type = this.type;
  4472. if ( this.name !== '' ) data.name = this.name;
  4473. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4474. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4475. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4476. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4477. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4478. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4479. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4480. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4481. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4482. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4483. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4484. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4485. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4486. data.bumpScale = this.bumpScale;
  4487. }
  4488. if ( this.normalMap && this.normalMap.isTexture ) {
  4489. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4490. data.normalScale = this.normalScale.toArray();
  4491. }
  4492. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4493. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4494. data.displacementScale = this.displacementScale;
  4495. data.displacementBias = this.displacementBias;
  4496. }
  4497. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4498. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4499. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4500. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4501. if ( this.envMap && this.envMap.isTexture ) {
  4502. data.envMap = this.envMap.toJSON( meta ).uuid;
  4503. data.reflectivity = this.reflectivity; // Scale behind envMap
  4504. }
  4505. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4506. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4507. }
  4508. if ( this.size !== undefined ) data.size = this.size;
  4509. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4510. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4511. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4512. if ( this.side !== FrontSide ) data.side = this.side;
  4513. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4514. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4515. if ( this.transparent === true ) data.transparent = this.transparent;
  4516. data.depthFunc = this.depthFunc;
  4517. data.depthTest = this.depthTest;
  4518. data.depthWrite = this.depthWrite;
  4519. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4520. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4521. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4522. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4523. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4524. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4525. data.skinning = this.skinning;
  4526. data.morphTargets = this.morphTargets;
  4527. data.dithering = this.dithering;
  4528. // TODO: Copied from Object3D.toJSON
  4529. function extractFromCache( cache ) {
  4530. var values = [];
  4531. for ( var key in cache ) {
  4532. var data = cache[ key ];
  4533. delete data.metadata;
  4534. values.push( data );
  4535. }
  4536. return values;
  4537. }
  4538. if ( isRoot ) {
  4539. var textures = extractFromCache( meta.textures );
  4540. var images = extractFromCache( meta.images );
  4541. if ( textures.length > 0 ) data.textures = textures;
  4542. if ( images.length > 0 ) data.images = images;
  4543. }
  4544. return data;
  4545. },
  4546. clone: function () {
  4547. return new this.constructor().copy( this );
  4548. },
  4549. copy: function ( source ) {
  4550. this.name = source.name;
  4551. this.fog = source.fog;
  4552. this.lights = source.lights;
  4553. this.blending = source.blending;
  4554. this.side = source.side;
  4555. this.shading = source.shading;
  4556. this.vertexColors = source.vertexColors;
  4557. this.opacity = source.opacity;
  4558. this.transparent = source.transparent;
  4559. this.blendSrc = source.blendSrc;
  4560. this.blendDst = source.blendDst;
  4561. this.blendEquation = source.blendEquation;
  4562. this.blendSrcAlpha = source.blendSrcAlpha;
  4563. this.blendDstAlpha = source.blendDstAlpha;
  4564. this.blendEquationAlpha = source.blendEquationAlpha;
  4565. this.depthFunc = source.depthFunc;
  4566. this.depthTest = source.depthTest;
  4567. this.depthWrite = source.depthWrite;
  4568. this.colorWrite = source.colorWrite;
  4569. this.precision = source.precision;
  4570. this.polygonOffset = source.polygonOffset;
  4571. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4572. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4573. this.dithering = source.dithering;
  4574. this.alphaTest = source.alphaTest;
  4575. this.premultipliedAlpha = source.premultipliedAlpha;
  4576. this.overdraw = source.overdraw;
  4577. this.visible = source.visible;
  4578. this.clipShadows = source.clipShadows;
  4579. this.clipIntersection = source.clipIntersection;
  4580. var srcPlanes = source.clippingPlanes,
  4581. dstPlanes = null;
  4582. if ( srcPlanes !== null ) {
  4583. var n = srcPlanes.length;
  4584. dstPlanes = new Array( n );
  4585. for ( var i = 0; i !== n; ++ i )
  4586. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4587. }
  4588. this.clippingPlanes = dstPlanes;
  4589. return this;
  4590. },
  4591. dispose: function () {
  4592. this.dispatchEvent( { type: 'dispose' } );
  4593. }
  4594. } );
  4595. /**
  4596. * @author alteredq / http://alteredqualia.com/
  4597. *
  4598. * parameters = {
  4599. * defines: { "label" : "value" },
  4600. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4601. *
  4602. * fragmentShader: <string>,
  4603. * vertexShader: <string>,
  4604. *
  4605. * wireframe: <boolean>,
  4606. * wireframeLinewidth: <float>,
  4607. *
  4608. * lights: <bool>,
  4609. *
  4610. * skinning: <bool>,
  4611. * morphTargets: <bool>,
  4612. * morphNormals: <bool>
  4613. * }
  4614. */
  4615. function ShaderMaterial( parameters ) {
  4616. Material.call( this );
  4617. this.type = 'ShaderMaterial';
  4618. this.defines = {};
  4619. this.uniforms = {};
  4620. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4621. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4622. this.linewidth = 1;
  4623. this.wireframe = false;
  4624. this.wireframeLinewidth = 1;
  4625. this.fog = false; // set to use scene fog
  4626. this.lights = false; // set to use scene lights
  4627. this.clipping = false; // set to use user-defined clipping planes
  4628. this.skinning = false; // set to use skinning attribute streams
  4629. this.morphTargets = false; // set to use morph targets
  4630. this.morphNormals = false; // set to use morph normals
  4631. this.extensions = {
  4632. derivatives: false, // set to use derivatives
  4633. fragDepth: false, // set to use fragment depth values
  4634. drawBuffers: false, // set to use draw buffers
  4635. shaderTextureLOD: false // set to use shader texture LOD
  4636. };
  4637. // When rendered geometry doesn't include these attributes but the material does,
  4638. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4639. this.defaultAttributeValues = {
  4640. 'color': [ 1, 1, 1 ],
  4641. 'uv': [ 0, 0 ],
  4642. 'uv2': [ 0, 0 ]
  4643. };
  4644. this.index0AttributeName = undefined;
  4645. if ( parameters !== undefined ) {
  4646. if ( parameters.attributes !== undefined ) {
  4647. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4648. }
  4649. this.setValues( parameters );
  4650. }
  4651. }
  4652. ShaderMaterial.prototype = Object.create( Material.prototype );
  4653. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4654. ShaderMaterial.prototype.isShaderMaterial = true;
  4655. ShaderMaterial.prototype.copy = function ( source ) {
  4656. Material.prototype.copy.call( this, source );
  4657. this.fragmentShader = source.fragmentShader;
  4658. this.vertexShader = source.vertexShader;
  4659. this.uniforms = UniformsUtils.clone( source.uniforms );
  4660. this.defines = source.defines;
  4661. this.wireframe = source.wireframe;
  4662. this.wireframeLinewidth = source.wireframeLinewidth;
  4663. this.lights = source.lights;
  4664. this.clipping = source.clipping;
  4665. this.skinning = source.skinning;
  4666. this.morphTargets = source.morphTargets;
  4667. this.morphNormals = source.morphNormals;
  4668. this.extensions = source.extensions;
  4669. return this;
  4670. };
  4671. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4672. var data = Material.prototype.toJSON.call( this, meta );
  4673. data.uniforms = this.uniforms;
  4674. data.vertexShader = this.vertexShader;
  4675. data.fragmentShader = this.fragmentShader;
  4676. return data;
  4677. };
  4678. /**
  4679. * @author mrdoob / http://mrdoob.com/
  4680. * @author alteredq / http://alteredqualia.com/
  4681. * @author bhouston / https://clara.io
  4682. * @author WestLangley / http://github.com/WestLangley
  4683. *
  4684. * parameters = {
  4685. *
  4686. * opacity: <float>,
  4687. *
  4688. * map: new THREE.Texture( <Image> ),
  4689. *
  4690. * alphaMap: new THREE.Texture( <Image> ),
  4691. *
  4692. * displacementMap: new THREE.Texture( <Image> ),
  4693. * displacementScale: <float>,
  4694. * displacementBias: <float>,
  4695. *
  4696. * wireframe: <boolean>,
  4697. * wireframeLinewidth: <float>
  4698. * }
  4699. */
  4700. function MeshDepthMaterial( parameters ) {
  4701. Material.call( this );
  4702. this.type = 'MeshDepthMaterial';
  4703. this.depthPacking = BasicDepthPacking;
  4704. this.skinning = false;
  4705. this.morphTargets = false;
  4706. this.map = null;
  4707. this.alphaMap = null;
  4708. this.displacementMap = null;
  4709. this.displacementScale = 1;
  4710. this.displacementBias = 0;
  4711. this.wireframe = false;
  4712. this.wireframeLinewidth = 1;
  4713. this.fog = false;
  4714. this.lights = false;
  4715. this.setValues( parameters );
  4716. }
  4717. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4718. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4719. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4720. MeshDepthMaterial.prototype.copy = function ( source ) {
  4721. Material.prototype.copy.call( this, source );
  4722. this.depthPacking = source.depthPacking;
  4723. this.skinning = source.skinning;
  4724. this.morphTargets = source.morphTargets;
  4725. this.map = source.map;
  4726. this.alphaMap = source.alphaMap;
  4727. this.displacementMap = source.displacementMap;
  4728. this.displacementScale = source.displacementScale;
  4729. this.displacementBias = source.displacementBias;
  4730. this.wireframe = source.wireframe;
  4731. this.wireframeLinewidth = source.wireframeLinewidth;
  4732. return this;
  4733. };
  4734. /**
  4735. * @author bhouston / http://clara.io
  4736. * @author WestLangley / http://github.com/WestLangley
  4737. */
  4738. function Box3( min, max ) {
  4739. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4740. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4741. }
  4742. Object.assign( Box3.prototype, {
  4743. isBox3: true,
  4744. set: function ( min, max ) {
  4745. this.min.copy( min );
  4746. this.max.copy( max );
  4747. return this;
  4748. },
  4749. setFromArray: function ( array ) {
  4750. var minX = + Infinity;
  4751. var minY = + Infinity;
  4752. var minZ = + Infinity;
  4753. var maxX = - Infinity;
  4754. var maxY = - Infinity;
  4755. var maxZ = - Infinity;
  4756. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4757. var x = array[ i ];
  4758. var y = array[ i + 1 ];
  4759. var z = array[ i + 2 ];
  4760. if ( x < minX ) minX = x;
  4761. if ( y < minY ) minY = y;
  4762. if ( z < minZ ) minZ = z;
  4763. if ( x > maxX ) maxX = x;
  4764. if ( y > maxY ) maxY = y;
  4765. if ( z > maxZ ) maxZ = z;
  4766. }
  4767. this.min.set( minX, minY, minZ );
  4768. this.max.set( maxX, maxY, maxZ );
  4769. return this;
  4770. },
  4771. setFromBufferAttribute: function ( attribute ) {
  4772. var minX = + Infinity;
  4773. var minY = + Infinity;
  4774. var minZ = + Infinity;
  4775. var maxX = - Infinity;
  4776. var maxY = - Infinity;
  4777. var maxZ = - Infinity;
  4778. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4779. var x = attribute.getX( i );
  4780. var y = attribute.getY( i );
  4781. var z = attribute.getZ( i );
  4782. if ( x < minX ) minX = x;
  4783. if ( y < minY ) minY = y;
  4784. if ( z < minZ ) minZ = z;
  4785. if ( x > maxX ) maxX = x;
  4786. if ( y > maxY ) maxY = y;
  4787. if ( z > maxZ ) maxZ = z;
  4788. }
  4789. this.min.set( minX, minY, minZ );
  4790. this.max.set( maxX, maxY, maxZ );
  4791. return this;
  4792. },
  4793. setFromPoints: function ( points ) {
  4794. this.makeEmpty();
  4795. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4796. this.expandByPoint( points[ i ] );
  4797. }
  4798. return this;
  4799. },
  4800. setFromCenterAndSize: function () {
  4801. var v1 = new Vector3();
  4802. return function setFromCenterAndSize( center, size ) {
  4803. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4804. this.min.copy( center ).sub( halfSize );
  4805. this.max.copy( center ).add( halfSize );
  4806. return this;
  4807. };
  4808. }(),
  4809. setFromObject: function ( object ) {
  4810. this.makeEmpty();
  4811. return this.expandByObject( object );
  4812. },
  4813. clone: function () {
  4814. return new this.constructor().copy( this );
  4815. },
  4816. copy: function ( box ) {
  4817. this.min.copy( box.min );
  4818. this.max.copy( box.max );
  4819. return this;
  4820. },
  4821. makeEmpty: function () {
  4822. this.min.x = this.min.y = this.min.z = + Infinity;
  4823. this.max.x = this.max.y = this.max.z = - Infinity;
  4824. return this;
  4825. },
  4826. isEmpty: function () {
  4827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4828. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4829. },
  4830. getCenter: function ( optionalTarget ) {
  4831. var result = optionalTarget || new Vector3();
  4832. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4833. },
  4834. getSize: function ( optionalTarget ) {
  4835. var result = optionalTarget || new Vector3();
  4836. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4837. },
  4838. expandByPoint: function ( point ) {
  4839. this.min.min( point );
  4840. this.max.max( point );
  4841. return this;
  4842. },
  4843. expandByVector: function ( vector ) {
  4844. this.min.sub( vector );
  4845. this.max.add( vector );
  4846. return this;
  4847. },
  4848. expandByScalar: function ( scalar ) {
  4849. this.min.addScalar( - scalar );
  4850. this.max.addScalar( scalar );
  4851. return this;
  4852. },
  4853. expandByObject: function () {
  4854. // Computes the world-axis-aligned bounding box of an object (including its children),
  4855. // accounting for both the object's, and children's, world transforms
  4856. var v1 = new Vector3();
  4857. return function expandByObject( object ) {
  4858. var scope = this;
  4859. object.updateMatrixWorld( true );
  4860. object.traverse( function ( node ) {
  4861. var i, l;
  4862. var geometry = node.geometry;
  4863. if ( geometry !== undefined ) {
  4864. if ( geometry.isGeometry ) {
  4865. var vertices = geometry.vertices;
  4866. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4867. v1.copy( vertices[ i ] );
  4868. v1.applyMatrix4( node.matrixWorld );
  4869. scope.expandByPoint( v1 );
  4870. }
  4871. } else if ( geometry.isBufferGeometry ) {
  4872. var attribute = geometry.attributes.position;
  4873. if ( attribute !== undefined ) {
  4874. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4875. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4876. scope.expandByPoint( v1 );
  4877. }
  4878. }
  4879. }
  4880. }
  4881. } );
  4882. return this;
  4883. };
  4884. }(),
  4885. containsPoint: function ( point ) {
  4886. return point.x < this.min.x || point.x > this.max.x ||
  4887. point.y < this.min.y || point.y > this.max.y ||
  4888. point.z < this.min.z || point.z > this.max.z ? false : true;
  4889. },
  4890. containsBox: function ( box ) {
  4891. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4892. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4893. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4894. },
  4895. getParameter: function ( point, optionalTarget ) {
  4896. // This can potentially have a divide by zero if the box
  4897. // has a size dimension of 0.
  4898. var result = optionalTarget || new Vector3();
  4899. return result.set(
  4900. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4901. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4902. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4903. );
  4904. },
  4905. intersectsBox: function ( box ) {
  4906. // using 6 splitting planes to rule out intersections.
  4907. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4908. box.max.y < this.min.y || box.min.y > this.max.y ||
  4909. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4910. },
  4911. intersectsSphere: ( function () {
  4912. var closestPoint;
  4913. return function intersectsSphere( sphere ) {
  4914. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4915. // Find the point on the AABB closest to the sphere center.
  4916. this.clampPoint( sphere.center, closestPoint );
  4917. // If that point is inside the sphere, the AABB and sphere intersect.
  4918. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4919. };
  4920. } )(),
  4921. intersectsPlane: function ( plane ) {
  4922. // We compute the minimum and maximum dot product values. If those values
  4923. // are on the same side (back or front) of the plane, then there is no intersection.
  4924. var min, max;
  4925. if ( plane.normal.x > 0 ) {
  4926. min = plane.normal.x * this.min.x;
  4927. max = plane.normal.x * this.max.x;
  4928. } else {
  4929. min = plane.normal.x * this.max.x;
  4930. max = plane.normal.x * this.min.x;
  4931. }
  4932. if ( plane.normal.y > 0 ) {
  4933. min += plane.normal.y * this.min.y;
  4934. max += plane.normal.y * this.max.y;
  4935. } else {
  4936. min += plane.normal.y * this.max.y;
  4937. max += plane.normal.y * this.min.y;
  4938. }
  4939. if ( plane.normal.z > 0 ) {
  4940. min += plane.normal.z * this.min.z;
  4941. max += plane.normal.z * this.max.z;
  4942. } else {
  4943. min += plane.normal.z * this.max.z;
  4944. max += plane.normal.z * this.min.z;
  4945. }
  4946. return ( min <= plane.constant && max >= plane.constant );
  4947. },
  4948. clampPoint: function ( point, optionalTarget ) {
  4949. var result = optionalTarget || new Vector3();
  4950. return result.copy( point ).clamp( this.min, this.max );
  4951. },
  4952. distanceToPoint: function () {
  4953. var v1 = new Vector3();
  4954. return function distanceToPoint( point ) {
  4955. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4956. return clampedPoint.sub( point ).length();
  4957. };
  4958. }(),
  4959. getBoundingSphere: function () {
  4960. var v1 = new Vector3();
  4961. return function getBoundingSphere( optionalTarget ) {
  4962. var result = optionalTarget || new Sphere();
  4963. this.getCenter( result.center );
  4964. result.radius = this.getSize( v1 ).length() * 0.5;
  4965. return result;
  4966. };
  4967. }(),
  4968. intersect: function ( box ) {
  4969. this.min.max( box.min );
  4970. this.max.min( box.max );
  4971. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  4972. if( this.isEmpty() ) this.makeEmpty();
  4973. return this;
  4974. },
  4975. union: function ( box ) {
  4976. this.min.min( box.min );
  4977. this.max.max( box.max );
  4978. return this;
  4979. },
  4980. applyMatrix4: function () {
  4981. var points = [
  4982. new Vector3(),
  4983. new Vector3(),
  4984. new Vector3(),
  4985. new Vector3(),
  4986. new Vector3(),
  4987. new Vector3(),
  4988. new Vector3(),
  4989. new Vector3()
  4990. ];
  4991. return function applyMatrix4( matrix ) {
  4992. // transform of empty box is an empty box.
  4993. if( this.isEmpty() ) return this;
  4994. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4995. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4996. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4997. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4998. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4999. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5000. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5001. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5002. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5003. this.setFromPoints( points );
  5004. return this;
  5005. };
  5006. }(),
  5007. translate: function ( offset ) {
  5008. this.min.add( offset );
  5009. this.max.add( offset );
  5010. return this;
  5011. },
  5012. equals: function ( box ) {
  5013. return box.min.equals( this.min ) && box.max.equals( this.max );
  5014. }
  5015. } );
  5016. /**
  5017. * @author bhouston / http://clara.io
  5018. * @author mrdoob / http://mrdoob.com/
  5019. */
  5020. function Sphere( center, radius ) {
  5021. this.center = ( center !== undefined ) ? center : new Vector3();
  5022. this.radius = ( radius !== undefined ) ? radius : 0;
  5023. }
  5024. Object.assign( Sphere.prototype, {
  5025. set: function ( center, radius ) {
  5026. this.center.copy( center );
  5027. this.radius = radius;
  5028. return this;
  5029. },
  5030. setFromPoints: function () {
  5031. var box;
  5032. return function setFromPoints( points, optionalCenter ) {
  5033. if ( box === undefined ) box = new Box3(); // see #10547
  5034. var center = this.center;
  5035. if ( optionalCenter !== undefined ) {
  5036. center.copy( optionalCenter );
  5037. } else {
  5038. box.setFromPoints( points ).getCenter( center );
  5039. }
  5040. var maxRadiusSq = 0;
  5041. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5042. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5043. }
  5044. this.radius = Math.sqrt( maxRadiusSq );
  5045. return this;
  5046. };
  5047. }(),
  5048. clone: function () {
  5049. return new this.constructor().copy( this );
  5050. },
  5051. copy: function ( sphere ) {
  5052. this.center.copy( sphere.center );
  5053. this.radius = sphere.radius;
  5054. return this;
  5055. },
  5056. empty: function () {
  5057. return ( this.radius <= 0 );
  5058. },
  5059. containsPoint: function ( point ) {
  5060. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5061. },
  5062. distanceToPoint: function ( point ) {
  5063. return ( point.distanceTo( this.center ) - this.radius );
  5064. },
  5065. intersectsSphere: function ( sphere ) {
  5066. var radiusSum = this.radius + sphere.radius;
  5067. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5068. },
  5069. intersectsBox: function ( box ) {
  5070. return box.intersectsSphere( this );
  5071. },
  5072. intersectsPlane: function ( plane ) {
  5073. // We use the following equation to compute the signed distance from
  5074. // the center of the sphere to the plane.
  5075. //
  5076. // distance = q * n - d
  5077. //
  5078. // If this distance is greater than the radius of the sphere,
  5079. // then there is no intersection.
  5080. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5081. },
  5082. clampPoint: function ( point, optionalTarget ) {
  5083. var deltaLengthSq = this.center.distanceToSquared( point );
  5084. var result = optionalTarget || new Vector3();
  5085. result.copy( point );
  5086. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5087. result.sub( this.center ).normalize();
  5088. result.multiplyScalar( this.radius ).add( this.center );
  5089. }
  5090. return result;
  5091. },
  5092. getBoundingBox: function ( optionalTarget ) {
  5093. var box = optionalTarget || new Box3();
  5094. box.set( this.center, this.center );
  5095. box.expandByScalar( this.radius );
  5096. return box;
  5097. },
  5098. applyMatrix4: function ( matrix ) {
  5099. this.center.applyMatrix4( matrix );
  5100. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5101. return this;
  5102. },
  5103. translate: function ( offset ) {
  5104. this.center.add( offset );
  5105. return this;
  5106. },
  5107. equals: function ( sphere ) {
  5108. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5109. }
  5110. } );
  5111. /**
  5112. * @author alteredq / http://alteredqualia.com/
  5113. * @author WestLangley / http://github.com/WestLangley
  5114. * @author bhouston / http://clara.io
  5115. * @author tschw
  5116. */
  5117. function Matrix3() {
  5118. this.elements = [
  5119. 1, 0, 0,
  5120. 0, 1, 0,
  5121. 0, 0, 1
  5122. ];
  5123. if ( arguments.length > 0 ) {
  5124. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5125. }
  5126. }
  5127. Object.assign( Matrix3.prototype, {
  5128. isMatrix3: true,
  5129. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5130. var te = this.elements;
  5131. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5132. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5133. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5134. return this;
  5135. },
  5136. identity: function () {
  5137. this.set(
  5138. 1, 0, 0,
  5139. 0, 1, 0,
  5140. 0, 0, 1
  5141. );
  5142. return this;
  5143. },
  5144. clone: function () {
  5145. return new this.constructor().fromArray( this.elements );
  5146. },
  5147. copy: function ( m ) {
  5148. var te = this.elements;
  5149. var me = m.elements;
  5150. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5151. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5152. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5153. return this;
  5154. },
  5155. setFromMatrix4: function ( m ) {
  5156. var me = m.elements;
  5157. this.set(
  5158. me[ 0 ], me[ 4 ], me[ 8 ],
  5159. me[ 1 ], me[ 5 ], me[ 9 ],
  5160. me[ 2 ], me[ 6 ], me[ 10 ]
  5161. );
  5162. return this;
  5163. },
  5164. applyToBufferAttribute: function () {
  5165. var v1;
  5166. return function applyToBufferAttribute( attribute ) {
  5167. if ( v1 === undefined ) v1 = new Vector3();
  5168. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5169. v1.x = attribute.getX( i );
  5170. v1.y = attribute.getY( i );
  5171. v1.z = attribute.getZ( i );
  5172. v1.applyMatrix3( this );
  5173. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5174. }
  5175. return attribute;
  5176. };
  5177. }(),
  5178. multiply: function ( m ) {
  5179. return this.multiplyMatrices( this, m );
  5180. },
  5181. premultiply: function ( m ) {
  5182. return this.multiplyMatrices( m, this );
  5183. },
  5184. multiplyMatrices: function ( a, b ) {
  5185. var ae = a.elements;
  5186. var be = b.elements;
  5187. var te = this.elements;
  5188. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5189. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5190. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5191. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5192. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5193. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5194. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5195. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5196. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5197. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5198. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5199. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5200. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5201. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5202. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5203. return this;
  5204. },
  5205. multiplyScalar: function ( s ) {
  5206. var te = this.elements;
  5207. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5208. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5209. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5210. return this;
  5211. },
  5212. determinant: function () {
  5213. var te = this.elements;
  5214. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5215. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5216. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5217. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5218. },
  5219. getInverse: function ( matrix, throwOnDegenerate ) {
  5220. if ( matrix && matrix.isMatrix4 ) {
  5221. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5222. }
  5223. var me = matrix.elements,
  5224. te = this.elements,
  5225. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5226. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5227. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5228. t11 = n33 * n22 - n32 * n23,
  5229. t12 = n32 * n13 - n33 * n12,
  5230. t13 = n23 * n12 - n22 * n13,
  5231. det = n11 * t11 + n21 * t12 + n31 * t13;
  5232. if ( det === 0 ) {
  5233. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5234. if ( throwOnDegenerate === true ) {
  5235. throw new Error( msg );
  5236. } else {
  5237. console.warn( msg );
  5238. }
  5239. return this.identity();
  5240. }
  5241. var detInv = 1 / det;
  5242. te[ 0 ] = t11 * detInv;
  5243. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5244. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5245. te[ 3 ] = t12 * detInv;
  5246. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5247. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5248. te[ 6 ] = t13 * detInv;
  5249. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5250. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5251. return this;
  5252. },
  5253. transpose: function () {
  5254. var tmp, m = this.elements;
  5255. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5256. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5257. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5258. return this;
  5259. },
  5260. getNormalMatrix: function ( matrix4 ) {
  5261. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5262. },
  5263. transposeIntoArray: function ( r ) {
  5264. var m = this.elements;
  5265. r[ 0 ] = m[ 0 ];
  5266. r[ 1 ] = m[ 3 ];
  5267. r[ 2 ] = m[ 6 ];
  5268. r[ 3 ] = m[ 1 ];
  5269. r[ 4 ] = m[ 4 ];
  5270. r[ 5 ] = m[ 7 ];
  5271. r[ 6 ] = m[ 2 ];
  5272. r[ 7 ] = m[ 5 ];
  5273. r[ 8 ] = m[ 8 ];
  5274. return this;
  5275. },
  5276. equals: function ( matrix ) {
  5277. var te = this.elements;
  5278. var me = matrix.elements;
  5279. for ( var i = 0; i < 9; i ++ ) {
  5280. if ( te[ i ] !== me[ i ] ) return false;
  5281. }
  5282. return true;
  5283. },
  5284. fromArray: function ( array, offset ) {
  5285. if ( offset === undefined ) offset = 0;
  5286. for ( var i = 0; i < 9; i ++ ) {
  5287. this.elements[ i ] = array[ i + offset ];
  5288. }
  5289. return this;
  5290. },
  5291. toArray: function ( array, offset ) {
  5292. if ( array === undefined ) array = [];
  5293. if ( offset === undefined ) offset = 0;
  5294. var te = this.elements;
  5295. array[ offset ] = te[ 0 ];
  5296. array[ offset + 1 ] = te[ 1 ];
  5297. array[ offset + 2 ] = te[ 2 ];
  5298. array[ offset + 3 ] = te[ 3 ];
  5299. array[ offset + 4 ] = te[ 4 ];
  5300. array[ offset + 5 ] = te[ 5 ];
  5301. array[ offset + 6 ] = te[ 6 ];
  5302. array[ offset + 7 ] = te[ 7 ];
  5303. array[ offset + 8 ] = te[ 8 ];
  5304. return array;
  5305. }
  5306. } );
  5307. /**
  5308. * @author bhouston / http://clara.io
  5309. */
  5310. function Plane( normal, constant ) {
  5311. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5312. this.constant = ( constant !== undefined ) ? constant : 0;
  5313. }
  5314. Object.assign( Plane.prototype, {
  5315. set: function ( normal, constant ) {
  5316. this.normal.copy( normal );
  5317. this.constant = constant;
  5318. return this;
  5319. },
  5320. setComponents: function ( x, y, z, w ) {
  5321. this.normal.set( x, y, z );
  5322. this.constant = w;
  5323. return this;
  5324. },
  5325. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5326. this.normal.copy( normal );
  5327. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5328. return this;
  5329. },
  5330. setFromCoplanarPoints: function () {
  5331. var v1 = new Vector3();
  5332. var v2 = new Vector3();
  5333. return function setFromCoplanarPoints( a, b, c ) {
  5334. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5335. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5336. this.setFromNormalAndCoplanarPoint( normal, a );
  5337. return this;
  5338. };
  5339. }(),
  5340. clone: function () {
  5341. return new this.constructor().copy( this );
  5342. },
  5343. copy: function ( plane ) {
  5344. this.normal.copy( plane.normal );
  5345. this.constant = plane.constant;
  5346. return this;
  5347. },
  5348. normalize: function () {
  5349. // Note: will lead to a divide by zero if the plane is invalid.
  5350. var inverseNormalLength = 1.0 / this.normal.length();
  5351. this.normal.multiplyScalar( inverseNormalLength );
  5352. this.constant *= inverseNormalLength;
  5353. return this;
  5354. },
  5355. negate: function () {
  5356. this.constant *= - 1;
  5357. this.normal.negate();
  5358. return this;
  5359. },
  5360. distanceToPoint: function ( point ) {
  5361. return this.normal.dot( point ) + this.constant;
  5362. },
  5363. distanceToSphere: function ( sphere ) {
  5364. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5365. },
  5366. projectPoint: function ( point, optionalTarget ) {
  5367. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5368. },
  5369. orthoPoint: function ( point, optionalTarget ) {
  5370. var perpendicularMagnitude = this.distanceToPoint( point );
  5371. var result = optionalTarget || new Vector3();
  5372. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5373. },
  5374. intersectLine: function () {
  5375. var v1 = new Vector3();
  5376. return function intersectLine( line, optionalTarget ) {
  5377. var result = optionalTarget || new Vector3();
  5378. var direction = line.delta( v1 );
  5379. var denominator = this.normal.dot( direction );
  5380. if ( denominator === 0 ) {
  5381. // line is coplanar, return origin
  5382. if ( this.distanceToPoint( line.start ) === 0 ) {
  5383. return result.copy( line.start );
  5384. }
  5385. // Unsure if this is the correct method to handle this case.
  5386. return undefined;
  5387. }
  5388. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5389. if ( t < 0 || t > 1 ) {
  5390. return undefined;
  5391. }
  5392. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5393. };
  5394. }(),
  5395. intersectsLine: function ( line ) {
  5396. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5397. var startSign = this.distanceToPoint( line.start );
  5398. var endSign = this.distanceToPoint( line.end );
  5399. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5400. },
  5401. intersectsBox: function ( box ) {
  5402. return box.intersectsPlane( this );
  5403. },
  5404. intersectsSphere: function ( sphere ) {
  5405. return sphere.intersectsPlane( this );
  5406. },
  5407. coplanarPoint: function ( optionalTarget ) {
  5408. var result = optionalTarget || new Vector3();
  5409. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5410. },
  5411. applyMatrix4: function () {
  5412. var v1 = new Vector3();
  5413. var m1 = new Matrix3();
  5414. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5415. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5416. // transform normal based on theory here:
  5417. // http://www.songho.ca/opengl/gl_normaltransform.html
  5418. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5419. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5420. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5421. this.constant = - referencePoint.dot( normal );
  5422. return this;
  5423. };
  5424. }(),
  5425. translate: function ( offset ) {
  5426. this.constant = this.constant - offset.dot( this.normal );
  5427. return this;
  5428. },
  5429. equals: function ( plane ) {
  5430. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5431. }
  5432. } );
  5433. /**
  5434. * @author mrdoob / http://mrdoob.com/
  5435. * @author alteredq / http://alteredqualia.com/
  5436. * @author bhouston / http://clara.io
  5437. */
  5438. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5439. this.planes = [
  5440. ( p0 !== undefined ) ? p0 : new Plane(),
  5441. ( p1 !== undefined ) ? p1 : new Plane(),
  5442. ( p2 !== undefined ) ? p2 : new Plane(),
  5443. ( p3 !== undefined ) ? p3 : new Plane(),
  5444. ( p4 !== undefined ) ? p4 : new Plane(),
  5445. ( p5 !== undefined ) ? p5 : new Plane()
  5446. ];
  5447. }
  5448. Object.assign( Frustum.prototype, {
  5449. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5450. var planes = this.planes;
  5451. planes[ 0 ].copy( p0 );
  5452. planes[ 1 ].copy( p1 );
  5453. planes[ 2 ].copy( p2 );
  5454. planes[ 3 ].copy( p3 );
  5455. planes[ 4 ].copy( p4 );
  5456. planes[ 5 ].copy( p5 );
  5457. return this;
  5458. },
  5459. clone: function () {
  5460. return new this.constructor().copy( this );
  5461. },
  5462. copy: function ( frustum ) {
  5463. var planes = this.planes;
  5464. for ( var i = 0; i < 6; i ++ ) {
  5465. planes[ i ].copy( frustum.planes[ i ] );
  5466. }
  5467. return this;
  5468. },
  5469. setFromMatrix: function ( m ) {
  5470. var planes = this.planes;
  5471. var me = m.elements;
  5472. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5473. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5474. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5475. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5476. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5477. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5478. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5479. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5480. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5481. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5482. return this;
  5483. },
  5484. intersectsObject: function () {
  5485. var sphere = new Sphere();
  5486. return function intersectsObject( object ) {
  5487. var geometry = object.geometry;
  5488. if ( geometry.boundingSphere === null )
  5489. geometry.computeBoundingSphere();
  5490. sphere.copy( geometry.boundingSphere )
  5491. .applyMatrix4( object.matrixWorld );
  5492. return this.intersectsSphere( sphere );
  5493. };
  5494. }(),
  5495. intersectsSprite: function () {
  5496. var sphere = new Sphere();
  5497. return function intersectsSprite( sprite ) {
  5498. sphere.center.set( 0, 0, 0 );
  5499. sphere.radius = 0.7071067811865476;
  5500. sphere.applyMatrix4( sprite.matrixWorld );
  5501. return this.intersectsSphere( sphere );
  5502. };
  5503. }(),
  5504. intersectsSphere: function ( sphere ) {
  5505. var planes = this.planes;
  5506. var center = sphere.center;
  5507. var negRadius = - sphere.radius;
  5508. for ( var i = 0; i < 6; i ++ ) {
  5509. var distance = planes[ i ].distanceToPoint( center );
  5510. if ( distance < negRadius ) {
  5511. return false;
  5512. }
  5513. }
  5514. return true;
  5515. },
  5516. intersectsBox: function () {
  5517. var p1 = new Vector3(),
  5518. p2 = new Vector3();
  5519. return function intersectsBox( box ) {
  5520. var planes = this.planes;
  5521. for ( var i = 0; i < 6; i ++ ) {
  5522. var plane = planes[ i ];
  5523. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5524. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5525. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5526. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5527. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5528. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5529. var d1 = plane.distanceToPoint( p1 );
  5530. var d2 = plane.distanceToPoint( p2 );
  5531. // if both outside plane, no intersection
  5532. if ( d1 < 0 && d2 < 0 ) {
  5533. return false;
  5534. }
  5535. }
  5536. return true;
  5537. };
  5538. }(),
  5539. containsPoint: function ( point ) {
  5540. var planes = this.planes;
  5541. for ( var i = 0; i < 6; i ++ ) {
  5542. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5543. return false;
  5544. }
  5545. }
  5546. return true;
  5547. }
  5548. } );
  5549. /**
  5550. * @author alteredq / http://alteredqualia.com/
  5551. * @author mrdoob / http://mrdoob.com/
  5552. */
  5553. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5554. var _gl = _renderer.context,
  5555. _state = _renderer.state,
  5556. _frustum = new Frustum(),
  5557. _projScreenMatrix = new Matrix4(),
  5558. _lightShadows = _lights.shadows,
  5559. _shadowMapSize = new Vector2(),
  5560. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5561. _lookTarget = new Vector3(),
  5562. _lightPositionWorld = new Vector3(),
  5563. _MorphingFlag = 1,
  5564. _SkinningFlag = 2,
  5565. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5566. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5567. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5568. _materialCache = {};
  5569. var cubeDirections = [
  5570. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5571. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5572. ];
  5573. var cubeUps = [
  5574. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5575. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5576. ];
  5577. var cube2DViewPorts = [
  5578. new Vector4(), new Vector4(), new Vector4(),
  5579. new Vector4(), new Vector4(), new Vector4()
  5580. ];
  5581. // init
  5582. var depthMaterialTemplate = new MeshDepthMaterial();
  5583. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5584. depthMaterialTemplate.clipping = true;
  5585. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5586. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5587. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5588. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5589. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5590. var depthMaterial = depthMaterialTemplate.clone();
  5591. depthMaterial.morphTargets = useMorphing;
  5592. depthMaterial.skinning = useSkinning;
  5593. _depthMaterials[ i ] = depthMaterial;
  5594. var distanceMaterial = new ShaderMaterial( {
  5595. defines: {
  5596. 'USE_SHADOWMAP': ''
  5597. },
  5598. uniforms: distanceUniforms,
  5599. vertexShader: distanceShader.vertexShader,
  5600. fragmentShader: distanceShader.fragmentShader,
  5601. morphTargets: useMorphing,
  5602. skinning: useSkinning,
  5603. clipping: true
  5604. } );
  5605. _distanceMaterials[ i ] = distanceMaterial;
  5606. }
  5607. //
  5608. var scope = this;
  5609. this.enabled = false;
  5610. this.autoUpdate = true;
  5611. this.needsUpdate = false;
  5612. this.type = PCFShadowMap;
  5613. this.renderReverseSided = true;
  5614. this.renderSingleSided = true;
  5615. this.render = function ( scene, camera ) {
  5616. if ( scope.enabled === false ) return;
  5617. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5618. if ( _lightShadows.length === 0 ) return;
  5619. // Set GL state for depth map.
  5620. _state.disable( _gl.BLEND );
  5621. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5622. _state.buffers.depth.setTest( true );
  5623. _state.setScissorTest( false );
  5624. // render depth map
  5625. var faceCount, isPointLight;
  5626. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5627. var light = _lightShadows[ i ];
  5628. var shadow = light.shadow;
  5629. if ( shadow === undefined ) {
  5630. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5631. continue;
  5632. }
  5633. if ( shadow.isSpotLightShadow ) {
  5634. shadow.update( light );
  5635. }
  5636. var shadowCamera = shadow.camera;
  5637. var shadowMatrix = shadow.matrix;
  5638. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5639. shadowCamera.position.copy( _lightPositionWorld );
  5640. _shadowMapSize.copy( shadow.mapSize );
  5641. _shadowMapSize.min( _maxShadowMapSize );
  5642. if ( light && light.isPointLight ) {
  5643. faceCount = 6;
  5644. isPointLight = true;
  5645. var vpWidth = _shadowMapSize.x;
  5646. var vpHeight = _shadowMapSize.y;
  5647. // These viewports map a cube-map onto a 2D texture with the
  5648. // following orientation:
  5649. //
  5650. // xzXZ
  5651. // y Y
  5652. //
  5653. // X - Positive x direction
  5654. // x - Negative x direction
  5655. // Y - Positive y direction
  5656. // y - Negative y direction
  5657. // Z - Positive z direction
  5658. // z - Negative z direction
  5659. // positive X
  5660. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5661. // negative X
  5662. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5663. // positive Z
  5664. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5665. // negative Z
  5666. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5667. // positive Y
  5668. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5669. // negative Y
  5670. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5671. _shadowMapSize.x *= 4.0;
  5672. _shadowMapSize.y *= 2.0;
  5673. // for point lights we set the shadow matrix to be a translation-only matrix
  5674. // equal to inverse of the light's position
  5675. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5676. } else {
  5677. faceCount = 1;
  5678. isPointLight = false;
  5679. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5680. shadowCamera.lookAt( _lookTarget );
  5681. shadowCamera.updateMatrixWorld();
  5682. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5683. // compute shadow matrix
  5684. shadowMatrix.set(
  5685. 0.5, 0.0, 0.0, 0.5,
  5686. 0.0, 0.5, 0.0, 0.5,
  5687. 0.0, 0.0, 0.5, 0.5,
  5688. 0.0, 0.0, 0.0, 1.0
  5689. );
  5690. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5691. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5692. }
  5693. if ( shadow.map === null ) {
  5694. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5695. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5696. shadow.map.texture.name = light.name + ".shadowMap";
  5697. shadowCamera.updateProjectionMatrix();
  5698. }
  5699. var shadowMap = shadow.map;
  5700. _renderer.setRenderTarget( shadowMap );
  5701. _renderer.clear();
  5702. // render shadow map for each cube face (if omni-directional) or
  5703. // run a single pass if not
  5704. for ( var face = 0; face < faceCount; face ++ ) {
  5705. if ( isPointLight ) {
  5706. _lookTarget.copy( shadowCamera.position );
  5707. _lookTarget.add( cubeDirections[ face ] );
  5708. shadowCamera.up.copy( cubeUps[ face ] );
  5709. shadowCamera.lookAt( _lookTarget );
  5710. shadowCamera.updateMatrixWorld();
  5711. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5712. var vpDimensions = cube2DViewPorts[ face ];
  5713. _state.viewport( vpDimensions );
  5714. }
  5715. // update camera matrices and frustum
  5716. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5717. _frustum.setFromMatrix( _projScreenMatrix );
  5718. // set object matrices & frustum culling
  5719. renderObject( scene, camera, shadowCamera, isPointLight );
  5720. }
  5721. }
  5722. // Restore GL state.
  5723. var clearColor = _renderer.getClearColor();
  5724. var clearAlpha = _renderer.getClearAlpha();
  5725. _renderer.setClearColor( clearColor, clearAlpha );
  5726. scope.needsUpdate = false;
  5727. };
  5728. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5729. var geometry = object.geometry;
  5730. var result = null;
  5731. var materialVariants = _depthMaterials;
  5732. var customMaterial = object.customDepthMaterial;
  5733. if ( isPointLight ) {
  5734. materialVariants = _distanceMaterials;
  5735. customMaterial = object.customDistanceMaterial;
  5736. }
  5737. if ( ! customMaterial ) {
  5738. var useMorphing = false;
  5739. if ( material.morphTargets ) {
  5740. if ( geometry && geometry.isBufferGeometry ) {
  5741. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5742. } else if ( geometry && geometry.isGeometry ) {
  5743. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5744. }
  5745. }
  5746. if ( object.isSkinnedMesh && material.skinning === false ) {
  5747. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5748. }
  5749. var useSkinning = object.isSkinnedMesh && material.skinning;
  5750. var variantIndex = 0;
  5751. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5752. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5753. result = materialVariants[ variantIndex ];
  5754. } else {
  5755. result = customMaterial;
  5756. }
  5757. if ( _renderer.localClippingEnabled &&
  5758. material.clipShadows === true &&
  5759. material.clippingPlanes.length !== 0 ) {
  5760. // in this case we need a unique material instance reflecting the
  5761. // appropriate state
  5762. var keyA = result.uuid, keyB = material.uuid;
  5763. var materialsForVariant = _materialCache[ keyA ];
  5764. if ( materialsForVariant === undefined ) {
  5765. materialsForVariant = {};
  5766. _materialCache[ keyA ] = materialsForVariant;
  5767. }
  5768. var cachedMaterial = materialsForVariant[ keyB ];
  5769. if ( cachedMaterial === undefined ) {
  5770. cachedMaterial = result.clone();
  5771. materialsForVariant[ keyB ] = cachedMaterial;
  5772. }
  5773. result = cachedMaterial;
  5774. }
  5775. result.visible = material.visible;
  5776. result.wireframe = material.wireframe;
  5777. var side = material.side;
  5778. if ( scope.renderSingleSided && side == DoubleSide ) {
  5779. side = FrontSide;
  5780. }
  5781. if ( scope.renderReverseSided ) {
  5782. if ( side === FrontSide ) side = BackSide;
  5783. else if ( side === BackSide ) side = FrontSide;
  5784. }
  5785. result.side = side;
  5786. result.clipShadows = material.clipShadows;
  5787. result.clippingPlanes = material.clippingPlanes;
  5788. result.wireframeLinewidth = material.wireframeLinewidth;
  5789. result.linewidth = material.linewidth;
  5790. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5791. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5792. }
  5793. return result;
  5794. }
  5795. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5796. if ( object.visible === false ) return;
  5797. var visible = object.layers.test( camera.layers );
  5798. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5799. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5800. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5801. var geometry = _objects.update( object );
  5802. var material = object.material;
  5803. if ( Array.isArray( material ) ) {
  5804. var groups = geometry.groups;
  5805. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5806. var group = groups[ k ];
  5807. var groupMaterial = material[ group.materialIndex ];
  5808. if ( groupMaterial && groupMaterial.visible ) {
  5809. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5810. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5811. }
  5812. }
  5813. } else if ( material.visible ) {
  5814. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5815. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5816. }
  5817. }
  5818. }
  5819. var children = object.children;
  5820. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5821. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5822. }
  5823. }
  5824. }
  5825. /**
  5826. * @author bhouston / http://clara.io
  5827. */
  5828. function Ray( origin, direction ) {
  5829. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5830. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5831. }
  5832. Object.assign( Ray.prototype, {
  5833. set: function ( origin, direction ) {
  5834. this.origin.copy( origin );
  5835. this.direction.copy( direction );
  5836. return this;
  5837. },
  5838. clone: function () {
  5839. return new this.constructor().copy( this );
  5840. },
  5841. copy: function ( ray ) {
  5842. this.origin.copy( ray.origin );
  5843. this.direction.copy( ray.direction );
  5844. return this;
  5845. },
  5846. at: function ( t, optionalTarget ) {
  5847. var result = optionalTarget || new Vector3();
  5848. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5849. },
  5850. lookAt: function ( v ) {
  5851. this.direction.copy( v ).sub( this.origin ).normalize();
  5852. return this;
  5853. },
  5854. recast: function () {
  5855. var v1 = new Vector3();
  5856. return function recast( t ) {
  5857. this.origin.copy( this.at( t, v1 ) );
  5858. return this;
  5859. };
  5860. }(),
  5861. closestPointToPoint: function ( point, optionalTarget ) {
  5862. var result = optionalTarget || new Vector3();
  5863. result.subVectors( point, this.origin );
  5864. var directionDistance = result.dot( this.direction );
  5865. if ( directionDistance < 0 ) {
  5866. return result.copy( this.origin );
  5867. }
  5868. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5869. },
  5870. distanceToPoint: function ( point ) {
  5871. return Math.sqrt( this.distanceSqToPoint( point ) );
  5872. },
  5873. distanceSqToPoint: function () {
  5874. var v1 = new Vector3();
  5875. return function distanceSqToPoint( point ) {
  5876. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5877. // point behind the ray
  5878. if ( directionDistance < 0 ) {
  5879. return this.origin.distanceToSquared( point );
  5880. }
  5881. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5882. return v1.distanceToSquared( point );
  5883. };
  5884. }(),
  5885. distanceSqToSegment: function () {
  5886. var segCenter = new Vector3();
  5887. var segDir = new Vector3();
  5888. var diff = new Vector3();
  5889. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5890. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5891. // It returns the min distance between the ray and the segment
  5892. // defined by v0 and v1
  5893. // It can also set two optional targets :
  5894. // - The closest point on the ray
  5895. // - The closest point on the segment
  5896. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5897. segDir.copy( v1 ).sub( v0 ).normalize();
  5898. diff.copy( this.origin ).sub( segCenter );
  5899. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5900. var a01 = - this.direction.dot( segDir );
  5901. var b0 = diff.dot( this.direction );
  5902. var b1 = - diff.dot( segDir );
  5903. var c = diff.lengthSq();
  5904. var det = Math.abs( 1 - a01 * a01 );
  5905. var s0, s1, sqrDist, extDet;
  5906. if ( det > 0 ) {
  5907. // The ray and segment are not parallel.
  5908. s0 = a01 * b1 - b0;
  5909. s1 = a01 * b0 - b1;
  5910. extDet = segExtent * det;
  5911. if ( s0 >= 0 ) {
  5912. if ( s1 >= - extDet ) {
  5913. if ( s1 <= extDet ) {
  5914. // region 0
  5915. // Minimum at interior points of ray and segment.
  5916. var invDet = 1 / det;
  5917. s0 *= invDet;
  5918. s1 *= invDet;
  5919. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5920. } else {
  5921. // region 1
  5922. s1 = segExtent;
  5923. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5924. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5925. }
  5926. } else {
  5927. // region 5
  5928. s1 = - segExtent;
  5929. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5930. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5931. }
  5932. } else {
  5933. if ( s1 <= - extDet ) {
  5934. // region 4
  5935. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5936. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5937. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5938. } else if ( s1 <= extDet ) {
  5939. // region 3
  5940. s0 = 0;
  5941. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5942. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5943. } else {
  5944. // region 2
  5945. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5946. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5947. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5948. }
  5949. }
  5950. } else {
  5951. // Ray and segment are parallel.
  5952. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  5953. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5954. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5955. }
  5956. if ( optionalPointOnRay ) {
  5957. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  5958. }
  5959. if ( optionalPointOnSegment ) {
  5960. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  5961. }
  5962. return sqrDist;
  5963. };
  5964. }(),
  5965. intersectSphere: function () {
  5966. var v1 = new Vector3();
  5967. return function intersectSphere( sphere, optionalTarget ) {
  5968. v1.subVectors( sphere.center, this.origin );
  5969. var tca = v1.dot( this.direction );
  5970. var d2 = v1.dot( v1 ) - tca * tca;
  5971. var radius2 = sphere.radius * sphere.radius;
  5972. if ( d2 > radius2 ) return null;
  5973. var thc = Math.sqrt( radius2 - d2 );
  5974. // t0 = first intersect point - entrance on front of sphere
  5975. var t0 = tca - thc;
  5976. // t1 = second intersect point - exit point on back of sphere
  5977. var t1 = tca + thc;
  5978. // test to see if both t0 and t1 are behind the ray - if so, return null
  5979. if ( t0 < 0 && t1 < 0 ) return null;
  5980. // test to see if t0 is behind the ray:
  5981. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5982. // in order to always return an intersect point that is in front of the ray.
  5983. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  5984. // else t0 is in front of the ray, so return the first collision point scaled by t0
  5985. return this.at( t0, optionalTarget );
  5986. };
  5987. }(),
  5988. intersectsSphere: function ( sphere ) {
  5989. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  5990. },
  5991. distanceToPlane: function ( plane ) {
  5992. var denominator = plane.normal.dot( this.direction );
  5993. if ( denominator === 0 ) {
  5994. // line is coplanar, return origin
  5995. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  5996. return 0;
  5997. }
  5998. // Null is preferable to undefined since undefined means.... it is undefined
  5999. return null;
  6000. }
  6001. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6002. // Return if the ray never intersects the plane
  6003. return t >= 0 ? t : null;
  6004. },
  6005. intersectPlane: function ( plane, optionalTarget ) {
  6006. var t = this.distanceToPlane( plane );
  6007. if ( t === null ) {
  6008. return null;
  6009. }
  6010. return this.at( t, optionalTarget );
  6011. },
  6012. intersectsPlane: function ( plane ) {
  6013. // check if the ray lies on the plane first
  6014. var distToPoint = plane.distanceToPoint( this.origin );
  6015. if ( distToPoint === 0 ) {
  6016. return true;
  6017. }
  6018. var denominator = plane.normal.dot( this.direction );
  6019. if ( denominator * distToPoint < 0 ) {
  6020. return true;
  6021. }
  6022. // ray origin is behind the plane (and is pointing behind it)
  6023. return false;
  6024. },
  6025. intersectBox: function ( box, optionalTarget ) {
  6026. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6027. var invdirx = 1 / this.direction.x,
  6028. invdiry = 1 / this.direction.y,
  6029. invdirz = 1 / this.direction.z;
  6030. var origin = this.origin;
  6031. if ( invdirx >= 0 ) {
  6032. tmin = ( box.min.x - origin.x ) * invdirx;
  6033. tmax = ( box.max.x - origin.x ) * invdirx;
  6034. } else {
  6035. tmin = ( box.max.x - origin.x ) * invdirx;
  6036. tmax = ( box.min.x - origin.x ) * invdirx;
  6037. }
  6038. if ( invdiry >= 0 ) {
  6039. tymin = ( box.min.y - origin.y ) * invdiry;
  6040. tymax = ( box.max.y - origin.y ) * invdiry;
  6041. } else {
  6042. tymin = ( box.max.y - origin.y ) * invdiry;
  6043. tymax = ( box.min.y - origin.y ) * invdiry;
  6044. }
  6045. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6046. // These lines also handle the case where tmin or tmax is NaN
  6047. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6048. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6049. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6050. if ( invdirz >= 0 ) {
  6051. tzmin = ( box.min.z - origin.z ) * invdirz;
  6052. tzmax = ( box.max.z - origin.z ) * invdirz;
  6053. } else {
  6054. tzmin = ( box.max.z - origin.z ) * invdirz;
  6055. tzmax = ( box.min.z - origin.z ) * invdirz;
  6056. }
  6057. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6058. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6059. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6060. //return point closest to the ray (positive side)
  6061. if ( tmax < 0 ) return null;
  6062. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6063. },
  6064. intersectsBox: ( function () {
  6065. var v = new Vector3();
  6066. return function intersectsBox( box ) {
  6067. return this.intersectBox( box, v ) !== null;
  6068. };
  6069. } )(),
  6070. intersectTriangle: function () {
  6071. // Compute the offset origin, edges, and normal.
  6072. var diff = new Vector3();
  6073. var edge1 = new Vector3();
  6074. var edge2 = new Vector3();
  6075. var normal = new Vector3();
  6076. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6077. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6078. edge1.subVectors( b, a );
  6079. edge2.subVectors( c, a );
  6080. normal.crossVectors( edge1, edge2 );
  6081. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6082. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6083. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6084. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6085. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6086. var DdN = this.direction.dot( normal );
  6087. var sign;
  6088. if ( DdN > 0 ) {
  6089. if ( backfaceCulling ) return null;
  6090. sign = 1;
  6091. } else if ( DdN < 0 ) {
  6092. sign = - 1;
  6093. DdN = - DdN;
  6094. } else {
  6095. return null;
  6096. }
  6097. diff.subVectors( this.origin, a );
  6098. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6099. // b1 < 0, no intersection
  6100. if ( DdQxE2 < 0 ) {
  6101. return null;
  6102. }
  6103. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6104. // b2 < 0, no intersection
  6105. if ( DdE1xQ < 0 ) {
  6106. return null;
  6107. }
  6108. // b1+b2 > 1, no intersection
  6109. if ( DdQxE2 + DdE1xQ > DdN ) {
  6110. return null;
  6111. }
  6112. // Line intersects triangle, check if ray does.
  6113. var QdN = - sign * diff.dot( normal );
  6114. // t < 0, no intersection
  6115. if ( QdN < 0 ) {
  6116. return null;
  6117. }
  6118. // Ray intersects triangle.
  6119. return this.at( QdN / DdN, optionalTarget );
  6120. };
  6121. }(),
  6122. applyMatrix4: function ( matrix4 ) {
  6123. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6124. this.origin.applyMatrix4( matrix4 );
  6125. this.direction.sub( this.origin );
  6126. this.direction.normalize();
  6127. return this;
  6128. },
  6129. equals: function ( ray ) {
  6130. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6131. }
  6132. } );
  6133. /**
  6134. * @author mrdoob / http://mrdoob.com/
  6135. * @author WestLangley / http://github.com/WestLangley
  6136. * @author bhouston / http://clara.io
  6137. */
  6138. function Euler( x, y, z, order ) {
  6139. this._x = x || 0;
  6140. this._y = y || 0;
  6141. this._z = z || 0;
  6142. this._order = order || Euler.DefaultOrder;
  6143. }
  6144. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6145. Euler.DefaultOrder = 'XYZ';
  6146. Object.defineProperties( Euler.prototype, {
  6147. x: {
  6148. get: function () {
  6149. return this._x;
  6150. },
  6151. set: function ( value ) {
  6152. this._x = value;
  6153. this.onChangeCallback();
  6154. }
  6155. },
  6156. y: {
  6157. get: function () {
  6158. return this._y;
  6159. },
  6160. set: function ( value ) {
  6161. this._y = value;
  6162. this.onChangeCallback();
  6163. }
  6164. },
  6165. z: {
  6166. get: function () {
  6167. return this._z;
  6168. },
  6169. set: function ( value ) {
  6170. this._z = value;
  6171. this.onChangeCallback();
  6172. }
  6173. },
  6174. order: {
  6175. get: function () {
  6176. return this._order;
  6177. },
  6178. set: function ( value ) {
  6179. this._order = value;
  6180. this.onChangeCallback();
  6181. }
  6182. }
  6183. } );
  6184. Object.assign( Euler.prototype, {
  6185. isEuler: true,
  6186. set: function ( x, y, z, order ) {
  6187. this._x = x;
  6188. this._y = y;
  6189. this._z = z;
  6190. this._order = order || this._order;
  6191. this.onChangeCallback();
  6192. return this;
  6193. },
  6194. clone: function () {
  6195. return new this.constructor( this._x, this._y, this._z, this._order );
  6196. },
  6197. copy: function ( euler ) {
  6198. this._x = euler._x;
  6199. this._y = euler._y;
  6200. this._z = euler._z;
  6201. this._order = euler._order;
  6202. this.onChangeCallback();
  6203. return this;
  6204. },
  6205. setFromRotationMatrix: function ( m, order, update ) {
  6206. var clamp = _Math.clamp;
  6207. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6208. var te = m.elements;
  6209. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6210. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6211. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6212. order = order || this._order;
  6213. if ( order === 'XYZ' ) {
  6214. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6215. if ( Math.abs( m13 ) < 0.99999 ) {
  6216. this._x = Math.atan2( - m23, m33 );
  6217. this._z = Math.atan2( - m12, m11 );
  6218. } else {
  6219. this._x = Math.atan2( m32, m22 );
  6220. this._z = 0;
  6221. }
  6222. } else if ( order === 'YXZ' ) {
  6223. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6224. if ( Math.abs( m23 ) < 0.99999 ) {
  6225. this._y = Math.atan2( m13, m33 );
  6226. this._z = Math.atan2( m21, m22 );
  6227. } else {
  6228. this._y = Math.atan2( - m31, m11 );
  6229. this._z = 0;
  6230. }
  6231. } else if ( order === 'ZXY' ) {
  6232. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6233. if ( Math.abs( m32 ) < 0.99999 ) {
  6234. this._y = Math.atan2( - m31, m33 );
  6235. this._z = Math.atan2( - m12, m22 );
  6236. } else {
  6237. this._y = 0;
  6238. this._z = Math.atan2( m21, m11 );
  6239. }
  6240. } else if ( order === 'ZYX' ) {
  6241. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6242. if ( Math.abs( m31 ) < 0.99999 ) {
  6243. this._x = Math.atan2( m32, m33 );
  6244. this._z = Math.atan2( m21, m11 );
  6245. } else {
  6246. this._x = 0;
  6247. this._z = Math.atan2( - m12, m22 );
  6248. }
  6249. } else if ( order === 'YZX' ) {
  6250. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6251. if ( Math.abs( m21 ) < 0.99999 ) {
  6252. this._x = Math.atan2( - m23, m22 );
  6253. this._y = Math.atan2( - m31, m11 );
  6254. } else {
  6255. this._x = 0;
  6256. this._y = Math.atan2( m13, m33 );
  6257. }
  6258. } else if ( order === 'XZY' ) {
  6259. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6260. if ( Math.abs( m12 ) < 0.99999 ) {
  6261. this._x = Math.atan2( m32, m22 );
  6262. this._y = Math.atan2( m13, m11 );
  6263. } else {
  6264. this._x = Math.atan2( - m23, m33 );
  6265. this._y = 0;
  6266. }
  6267. } else {
  6268. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6269. }
  6270. this._order = order;
  6271. if ( update !== false ) this.onChangeCallback();
  6272. return this;
  6273. },
  6274. setFromQuaternion: function () {
  6275. var matrix;
  6276. return function setFromQuaternion( q, order, update ) {
  6277. if ( matrix === undefined ) matrix = new Matrix4();
  6278. matrix.makeRotationFromQuaternion( q );
  6279. return this.setFromRotationMatrix( matrix, order, update );
  6280. };
  6281. }(),
  6282. setFromVector3: function ( v, order ) {
  6283. return this.set( v.x, v.y, v.z, order || this._order );
  6284. },
  6285. reorder: function () {
  6286. // WARNING: this discards revolution information -bhouston
  6287. var q = new Quaternion();
  6288. return function reorder( newOrder ) {
  6289. q.setFromEuler( this );
  6290. return this.setFromQuaternion( q, newOrder );
  6291. };
  6292. }(),
  6293. equals: function ( euler ) {
  6294. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6295. },
  6296. fromArray: function ( array ) {
  6297. this._x = array[ 0 ];
  6298. this._y = array[ 1 ];
  6299. this._z = array[ 2 ];
  6300. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6301. this.onChangeCallback();
  6302. return this;
  6303. },
  6304. toArray: function ( array, offset ) {
  6305. if ( array === undefined ) array = [];
  6306. if ( offset === undefined ) offset = 0;
  6307. array[ offset ] = this._x;
  6308. array[ offset + 1 ] = this._y;
  6309. array[ offset + 2 ] = this._z;
  6310. array[ offset + 3 ] = this._order;
  6311. return array;
  6312. },
  6313. toVector3: function ( optionalResult ) {
  6314. if ( optionalResult ) {
  6315. return optionalResult.set( this._x, this._y, this._z );
  6316. } else {
  6317. return new Vector3( this._x, this._y, this._z );
  6318. }
  6319. },
  6320. onChange: function ( callback ) {
  6321. this.onChangeCallback = callback;
  6322. return this;
  6323. },
  6324. onChangeCallback: function () {}
  6325. } );
  6326. /**
  6327. * @author mrdoob / http://mrdoob.com/
  6328. */
  6329. function Layers() {
  6330. this.mask = 1 | 0;
  6331. }
  6332. Object.assign( Layers.prototype, {
  6333. set: function ( channel ) {
  6334. this.mask = 1 << channel | 0;
  6335. },
  6336. enable: function ( channel ) {
  6337. this.mask |= 1 << channel | 0;
  6338. },
  6339. toggle: function ( channel ) {
  6340. this.mask ^= 1 << channel | 0;
  6341. },
  6342. disable: function ( channel ) {
  6343. this.mask &= ~ ( 1 << channel | 0 );
  6344. },
  6345. test: function ( layers ) {
  6346. return ( this.mask & layers.mask ) !== 0;
  6347. }
  6348. } );
  6349. /**
  6350. * @author mrdoob / http://mrdoob.com/
  6351. * @author mikael emtinger / http://gomo.se/
  6352. * @author alteredq / http://alteredqualia.com/
  6353. * @author WestLangley / http://github.com/WestLangley
  6354. * @author elephantatwork / www.elephantatwork.ch
  6355. */
  6356. var object3DId = 0;
  6357. function Object3D() {
  6358. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6359. this.uuid = _Math.generateUUID();
  6360. this.name = '';
  6361. this.type = 'Object3D';
  6362. this.parent = null;
  6363. this.children = [];
  6364. this.up = Object3D.DefaultUp.clone();
  6365. var position = new Vector3();
  6366. var rotation = new Euler();
  6367. var quaternion = new Quaternion();
  6368. var scale = new Vector3( 1, 1, 1 );
  6369. function onRotationChange() {
  6370. quaternion.setFromEuler( rotation, false );
  6371. }
  6372. function onQuaternionChange() {
  6373. rotation.setFromQuaternion( quaternion, undefined, false );
  6374. }
  6375. rotation.onChange( onRotationChange );
  6376. quaternion.onChange( onQuaternionChange );
  6377. Object.defineProperties( this, {
  6378. position: {
  6379. enumerable: true,
  6380. value: position
  6381. },
  6382. rotation: {
  6383. enumerable: true,
  6384. value: rotation
  6385. },
  6386. quaternion: {
  6387. enumerable: true,
  6388. value: quaternion
  6389. },
  6390. scale: {
  6391. enumerable: true,
  6392. value: scale
  6393. },
  6394. modelViewMatrix: {
  6395. value: new Matrix4()
  6396. },
  6397. normalMatrix: {
  6398. value: new Matrix3()
  6399. }
  6400. } );
  6401. this.matrix = new Matrix4();
  6402. this.matrixWorld = new Matrix4();
  6403. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6404. this.matrixWorldNeedsUpdate = false;
  6405. this.layers = new Layers();
  6406. this.visible = true;
  6407. this.castShadow = false;
  6408. this.receiveShadow = false;
  6409. this.frustumCulled = true;
  6410. this.renderOrder = 0;
  6411. this.userData = {};
  6412. this.onBeforeRender = function () {};
  6413. this.onAfterRender = function () {};
  6414. }
  6415. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6416. Object3D.DefaultMatrixAutoUpdate = true;
  6417. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6418. isObject3D: true,
  6419. applyMatrix: function ( matrix ) {
  6420. this.matrix.multiplyMatrices( matrix, this.matrix );
  6421. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6422. },
  6423. setRotationFromAxisAngle: function ( axis, angle ) {
  6424. // assumes axis is normalized
  6425. this.quaternion.setFromAxisAngle( axis, angle );
  6426. },
  6427. setRotationFromEuler: function ( euler ) {
  6428. this.quaternion.setFromEuler( euler, true );
  6429. },
  6430. setRotationFromMatrix: function ( m ) {
  6431. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6432. this.quaternion.setFromRotationMatrix( m );
  6433. },
  6434. setRotationFromQuaternion: function ( q ) {
  6435. // assumes q is normalized
  6436. this.quaternion.copy( q );
  6437. },
  6438. rotateOnAxis: function () {
  6439. // rotate object on axis in object space
  6440. // axis is assumed to be normalized
  6441. var q1 = new Quaternion();
  6442. return function rotateOnAxis( axis, angle ) {
  6443. q1.setFromAxisAngle( axis, angle );
  6444. this.quaternion.multiply( q1 );
  6445. return this;
  6446. };
  6447. }(),
  6448. rotateX: function () {
  6449. var v1 = new Vector3( 1, 0, 0 );
  6450. return function rotateX( angle ) {
  6451. return this.rotateOnAxis( v1, angle );
  6452. };
  6453. }(),
  6454. rotateY: function () {
  6455. var v1 = new Vector3( 0, 1, 0 );
  6456. return function rotateY( angle ) {
  6457. return this.rotateOnAxis( v1, angle );
  6458. };
  6459. }(),
  6460. rotateZ: function () {
  6461. var v1 = new Vector3( 0, 0, 1 );
  6462. return function rotateZ( angle ) {
  6463. return this.rotateOnAxis( v1, angle );
  6464. };
  6465. }(),
  6466. translateOnAxis: function () {
  6467. // translate object by distance along axis in object space
  6468. // axis is assumed to be normalized
  6469. var v1 = new Vector3();
  6470. return function translateOnAxis( axis, distance ) {
  6471. v1.copy( axis ).applyQuaternion( this.quaternion );
  6472. this.position.add( v1.multiplyScalar( distance ) );
  6473. return this;
  6474. };
  6475. }(),
  6476. translateX: function () {
  6477. var v1 = new Vector3( 1, 0, 0 );
  6478. return function translateX( distance ) {
  6479. return this.translateOnAxis( v1, distance );
  6480. };
  6481. }(),
  6482. translateY: function () {
  6483. var v1 = new Vector3( 0, 1, 0 );
  6484. return function translateY( distance ) {
  6485. return this.translateOnAxis( v1, distance );
  6486. };
  6487. }(),
  6488. translateZ: function () {
  6489. var v1 = new Vector3( 0, 0, 1 );
  6490. return function translateZ( distance ) {
  6491. return this.translateOnAxis( v1, distance );
  6492. };
  6493. }(),
  6494. localToWorld: function ( vector ) {
  6495. return vector.applyMatrix4( this.matrixWorld );
  6496. },
  6497. worldToLocal: function () {
  6498. var m1 = new Matrix4();
  6499. return function worldToLocal( vector ) {
  6500. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6501. };
  6502. }(),
  6503. lookAt: function () {
  6504. // This routine does not support objects with rotated and/or translated parent(s)
  6505. var m1 = new Matrix4();
  6506. return function lookAt( vector ) {
  6507. if ( this.isCamera ) {
  6508. m1.lookAt( this.position, vector, this.up );
  6509. } else {
  6510. m1.lookAt( vector, this.position, this.up );
  6511. }
  6512. this.quaternion.setFromRotationMatrix( m1 );
  6513. };
  6514. }(),
  6515. add: function ( object ) {
  6516. if ( arguments.length > 1 ) {
  6517. for ( var i = 0; i < arguments.length; i ++ ) {
  6518. this.add( arguments[ i ] );
  6519. }
  6520. return this;
  6521. }
  6522. if ( object === this ) {
  6523. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6524. return this;
  6525. }
  6526. if ( ( object && object.isObject3D ) ) {
  6527. if ( object.parent !== null ) {
  6528. object.parent.remove( object );
  6529. }
  6530. object.parent = this;
  6531. object.dispatchEvent( { type: 'added' } );
  6532. this.children.push( object );
  6533. } else {
  6534. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6535. }
  6536. return this;
  6537. },
  6538. remove: function ( object ) {
  6539. if ( arguments.length > 1 ) {
  6540. for ( var i = 0; i < arguments.length; i ++ ) {
  6541. this.remove( arguments[ i ] );
  6542. }
  6543. }
  6544. var index = this.children.indexOf( object );
  6545. if ( index !== - 1 ) {
  6546. object.parent = null;
  6547. object.dispatchEvent( { type: 'removed' } );
  6548. this.children.splice( index, 1 );
  6549. }
  6550. },
  6551. getObjectById: function ( id ) {
  6552. return this.getObjectByProperty( 'id', id );
  6553. },
  6554. getObjectByName: function ( name ) {
  6555. return this.getObjectByProperty( 'name', name );
  6556. },
  6557. getObjectByProperty: function ( name, value ) {
  6558. if ( this[ name ] === value ) return this;
  6559. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6560. var child = this.children[ i ];
  6561. var object = child.getObjectByProperty( name, value );
  6562. if ( object !== undefined ) {
  6563. return object;
  6564. }
  6565. }
  6566. return undefined;
  6567. },
  6568. getWorldPosition: function ( optionalTarget ) {
  6569. var result = optionalTarget || new Vector3();
  6570. this.updateMatrixWorld( true );
  6571. return result.setFromMatrixPosition( this.matrixWorld );
  6572. },
  6573. getWorldQuaternion: function () {
  6574. var position = new Vector3();
  6575. var scale = new Vector3();
  6576. return function getWorldQuaternion( optionalTarget ) {
  6577. var result = optionalTarget || new Quaternion();
  6578. this.updateMatrixWorld( true );
  6579. this.matrixWorld.decompose( position, result, scale );
  6580. return result;
  6581. };
  6582. }(),
  6583. getWorldRotation: function () {
  6584. var quaternion = new Quaternion();
  6585. return function getWorldRotation( optionalTarget ) {
  6586. var result = optionalTarget || new Euler();
  6587. this.getWorldQuaternion( quaternion );
  6588. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6589. };
  6590. }(),
  6591. getWorldScale: function () {
  6592. var position = new Vector3();
  6593. var quaternion = new Quaternion();
  6594. return function getWorldScale( optionalTarget ) {
  6595. var result = optionalTarget || new Vector3();
  6596. this.updateMatrixWorld( true );
  6597. this.matrixWorld.decompose( position, quaternion, result );
  6598. return result;
  6599. };
  6600. }(),
  6601. getWorldDirection: function () {
  6602. var quaternion = new Quaternion();
  6603. return function getWorldDirection( optionalTarget ) {
  6604. var result = optionalTarget || new Vector3();
  6605. this.getWorldQuaternion( quaternion );
  6606. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6607. };
  6608. }(),
  6609. raycast: function () {},
  6610. traverse: function ( callback ) {
  6611. callback( this );
  6612. var children = this.children;
  6613. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6614. children[ i ].traverse( callback );
  6615. }
  6616. },
  6617. traverseVisible: function ( callback ) {
  6618. if ( this.visible === false ) return;
  6619. callback( this );
  6620. var children = this.children;
  6621. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6622. children[ i ].traverseVisible( callback );
  6623. }
  6624. },
  6625. traverseAncestors: function ( callback ) {
  6626. var parent = this.parent;
  6627. if ( parent !== null ) {
  6628. callback( parent );
  6629. parent.traverseAncestors( callback );
  6630. }
  6631. },
  6632. updateMatrix: function () {
  6633. this.matrix.compose( this.position, this.quaternion, this.scale );
  6634. this.matrixWorldNeedsUpdate = true;
  6635. },
  6636. updateMatrixWorld: function ( force ) {
  6637. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6638. if ( this.matrixWorldNeedsUpdate || force ) {
  6639. if ( this.parent === null ) {
  6640. this.matrixWorld.copy( this.matrix );
  6641. } else {
  6642. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6643. }
  6644. this.matrixWorldNeedsUpdate = false;
  6645. force = true;
  6646. }
  6647. // update children
  6648. var children = this.children;
  6649. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6650. children[ i ].updateMatrixWorld( force );
  6651. }
  6652. },
  6653. toJSON: function ( meta ) {
  6654. // meta is '' when called from JSON.stringify
  6655. var isRootObject = ( meta === undefined || meta === '' );
  6656. var output = {};
  6657. // meta is a hash used to collect geometries, materials.
  6658. // not providing it implies that this is the root object
  6659. // being serialized.
  6660. if ( isRootObject ) {
  6661. // initialize meta obj
  6662. meta = {
  6663. geometries: {},
  6664. materials: {},
  6665. textures: {},
  6666. images: {}
  6667. };
  6668. output.metadata = {
  6669. version: 4.5,
  6670. type: 'Object',
  6671. generator: 'Object3D.toJSON'
  6672. };
  6673. }
  6674. // standard Object3D serialization
  6675. var object = {};
  6676. object.uuid = this.uuid;
  6677. object.type = this.type;
  6678. if ( this.name !== '' ) object.name = this.name;
  6679. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6680. if ( this.castShadow === true ) object.castShadow = true;
  6681. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6682. if ( this.visible === false ) object.visible = false;
  6683. object.matrix = this.matrix.toArray();
  6684. //
  6685. function serialize( library, element ) {
  6686. if ( library[ element.uuid ] === undefined ) {
  6687. library[ element.uuid ] = element.toJSON( meta );
  6688. }
  6689. return element.uuid;
  6690. }
  6691. if ( this.geometry !== undefined ) {
  6692. object.geometry = serialize( meta.geometries, this.geometry );
  6693. }
  6694. if ( this.material !== undefined ) {
  6695. if ( Array.isArray( this.material ) ) {
  6696. var uuids = [];
  6697. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6698. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6699. }
  6700. object.material = uuids;
  6701. } else {
  6702. object.material = serialize( meta.materials, this.material );
  6703. }
  6704. }
  6705. //
  6706. if ( this.children.length > 0 ) {
  6707. object.children = [];
  6708. for ( var i = 0; i < this.children.length; i ++ ) {
  6709. object.children.push( this.children[ i ].toJSON( meta ).object );
  6710. }
  6711. }
  6712. if ( isRootObject ) {
  6713. var geometries = extractFromCache( meta.geometries );
  6714. var materials = extractFromCache( meta.materials );
  6715. var textures = extractFromCache( meta.textures );
  6716. var images = extractFromCache( meta.images );
  6717. if ( geometries.length > 0 ) output.geometries = geometries;
  6718. if ( materials.length > 0 ) output.materials = materials;
  6719. if ( textures.length > 0 ) output.textures = textures;
  6720. if ( images.length > 0 ) output.images = images;
  6721. }
  6722. output.object = object;
  6723. return output;
  6724. // extract data from the cache hash
  6725. // remove metadata on each item
  6726. // and return as array
  6727. function extractFromCache( cache ) {
  6728. var values = [];
  6729. for ( var key in cache ) {
  6730. var data = cache[ key ];
  6731. delete data.metadata;
  6732. values.push( data );
  6733. }
  6734. return values;
  6735. }
  6736. },
  6737. clone: function ( recursive ) {
  6738. return new this.constructor().copy( this, recursive );
  6739. },
  6740. copy: function ( source, recursive ) {
  6741. if ( recursive === undefined ) recursive = true;
  6742. this.name = source.name;
  6743. this.up.copy( source.up );
  6744. this.position.copy( source.position );
  6745. this.quaternion.copy( source.quaternion );
  6746. this.scale.copy( source.scale );
  6747. this.matrix.copy( source.matrix );
  6748. this.matrixWorld.copy( source.matrixWorld );
  6749. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6750. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6751. this.layers.mask = source.layers.mask;
  6752. this.visible = source.visible;
  6753. this.castShadow = source.castShadow;
  6754. this.receiveShadow = source.receiveShadow;
  6755. this.frustumCulled = source.frustumCulled;
  6756. this.renderOrder = source.renderOrder;
  6757. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6758. if ( recursive === true ) {
  6759. for ( var i = 0; i < source.children.length; i ++ ) {
  6760. var child = source.children[ i ];
  6761. this.add( child.clone() );
  6762. }
  6763. }
  6764. return this;
  6765. }
  6766. } );
  6767. /**
  6768. * @author bhouston / http://clara.io
  6769. */
  6770. function Line3( start, end ) {
  6771. this.start = ( start !== undefined ) ? start : new Vector3();
  6772. this.end = ( end !== undefined ) ? end : new Vector3();
  6773. }
  6774. Object.assign( Line3.prototype, {
  6775. set: function ( start, end ) {
  6776. this.start.copy( start );
  6777. this.end.copy( end );
  6778. return this;
  6779. },
  6780. clone: function () {
  6781. return new this.constructor().copy( this );
  6782. },
  6783. copy: function ( line ) {
  6784. this.start.copy( line.start );
  6785. this.end.copy( line.end );
  6786. return this;
  6787. },
  6788. getCenter: function ( optionalTarget ) {
  6789. var result = optionalTarget || new Vector3();
  6790. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6791. },
  6792. delta: function ( optionalTarget ) {
  6793. var result = optionalTarget || new Vector3();
  6794. return result.subVectors( this.end, this.start );
  6795. },
  6796. distanceSq: function () {
  6797. return this.start.distanceToSquared( this.end );
  6798. },
  6799. distance: function () {
  6800. return this.start.distanceTo( this.end );
  6801. },
  6802. at: function ( t, optionalTarget ) {
  6803. var result = optionalTarget || new Vector3();
  6804. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6805. },
  6806. closestPointToPointParameter: function () {
  6807. var startP = new Vector3();
  6808. var startEnd = new Vector3();
  6809. return function closestPointToPointParameter( point, clampToLine ) {
  6810. startP.subVectors( point, this.start );
  6811. startEnd.subVectors( this.end, this.start );
  6812. var startEnd2 = startEnd.dot( startEnd );
  6813. var startEnd_startP = startEnd.dot( startP );
  6814. var t = startEnd_startP / startEnd2;
  6815. if ( clampToLine ) {
  6816. t = _Math.clamp( t, 0, 1 );
  6817. }
  6818. return t;
  6819. };
  6820. }(),
  6821. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6822. var t = this.closestPointToPointParameter( point, clampToLine );
  6823. var result = optionalTarget || new Vector3();
  6824. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6825. },
  6826. applyMatrix4: function ( matrix ) {
  6827. this.start.applyMatrix4( matrix );
  6828. this.end.applyMatrix4( matrix );
  6829. return this;
  6830. },
  6831. equals: function ( line ) {
  6832. return line.start.equals( this.start ) && line.end.equals( this.end );
  6833. }
  6834. } );
  6835. /**
  6836. * @author bhouston / http://clara.io
  6837. * @author mrdoob / http://mrdoob.com/
  6838. */
  6839. function Triangle( a, b, c ) {
  6840. this.a = ( a !== undefined ) ? a : new Vector3();
  6841. this.b = ( b !== undefined ) ? b : new Vector3();
  6842. this.c = ( c !== undefined ) ? c : new Vector3();
  6843. }
  6844. Object.assign( Triangle, {
  6845. normal: function () {
  6846. var v0 = new Vector3();
  6847. return function normal( a, b, c, optionalTarget ) {
  6848. var result = optionalTarget || new Vector3();
  6849. result.subVectors( c, b );
  6850. v0.subVectors( a, b );
  6851. result.cross( v0 );
  6852. var resultLengthSq = result.lengthSq();
  6853. if ( resultLengthSq > 0 ) {
  6854. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6855. }
  6856. return result.set( 0, 0, 0 );
  6857. };
  6858. }(),
  6859. // static/instance method to calculate barycentric coordinates
  6860. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6861. barycoordFromPoint: function () {
  6862. var v0 = new Vector3();
  6863. var v1 = new Vector3();
  6864. var v2 = new Vector3();
  6865. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6866. v0.subVectors( c, a );
  6867. v1.subVectors( b, a );
  6868. v2.subVectors( point, a );
  6869. var dot00 = v0.dot( v0 );
  6870. var dot01 = v0.dot( v1 );
  6871. var dot02 = v0.dot( v2 );
  6872. var dot11 = v1.dot( v1 );
  6873. var dot12 = v1.dot( v2 );
  6874. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6875. var result = optionalTarget || new Vector3();
  6876. // collinear or singular triangle
  6877. if ( denom === 0 ) {
  6878. // arbitrary location outside of triangle?
  6879. // not sure if this is the best idea, maybe should be returning undefined
  6880. return result.set( - 2, - 1, - 1 );
  6881. }
  6882. var invDenom = 1 / denom;
  6883. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6884. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6885. // barycentric coordinates must always sum to 1
  6886. return result.set( 1 - u - v, v, u );
  6887. };
  6888. }(),
  6889. containsPoint: function () {
  6890. var v1 = new Vector3();
  6891. return function containsPoint( point, a, b, c ) {
  6892. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6893. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6894. };
  6895. }()
  6896. } );
  6897. Object.assign( Triangle.prototype, {
  6898. set: function ( a, b, c ) {
  6899. this.a.copy( a );
  6900. this.b.copy( b );
  6901. this.c.copy( c );
  6902. return this;
  6903. },
  6904. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6905. this.a.copy( points[ i0 ] );
  6906. this.b.copy( points[ i1 ] );
  6907. this.c.copy( points[ i2 ] );
  6908. return this;
  6909. },
  6910. clone: function () {
  6911. return new this.constructor().copy( this );
  6912. },
  6913. copy: function ( triangle ) {
  6914. this.a.copy( triangle.a );
  6915. this.b.copy( triangle.b );
  6916. this.c.copy( triangle.c );
  6917. return this;
  6918. },
  6919. area: function () {
  6920. var v0 = new Vector3();
  6921. var v1 = new Vector3();
  6922. return function area() {
  6923. v0.subVectors( this.c, this.b );
  6924. v1.subVectors( this.a, this.b );
  6925. return v0.cross( v1 ).length() * 0.5;
  6926. };
  6927. }(),
  6928. midpoint: function ( optionalTarget ) {
  6929. var result = optionalTarget || new Vector3();
  6930. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6931. },
  6932. normal: function ( optionalTarget ) {
  6933. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6934. },
  6935. plane: function ( optionalTarget ) {
  6936. var result = optionalTarget || new Plane();
  6937. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6938. },
  6939. barycoordFromPoint: function ( point, optionalTarget ) {
  6940. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6941. },
  6942. containsPoint: function ( point ) {
  6943. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6944. },
  6945. closestPointToPoint: function () {
  6946. var plane, edgeList, projectedPoint, closestPoint;
  6947. return function closestPointToPoint( point, optionalTarget ) {
  6948. if ( plane === undefined ) {
  6949. plane = new Plane();
  6950. edgeList = [ new Line3(), new Line3(), new Line3() ];
  6951. projectedPoint = new Vector3();
  6952. closestPoint = new Vector3();
  6953. }
  6954. var result = optionalTarget || new Vector3();
  6955. var minDistance = Infinity;
  6956. // project the point onto the plane of the triangle
  6957. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6958. plane.projectPoint( point, projectedPoint );
  6959. // check if the projection lies within the triangle
  6960. if( this.containsPoint( projectedPoint ) === true ) {
  6961. // if so, this is the closest point
  6962. result.copy( projectedPoint );
  6963. } else {
  6964. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6965. edgeList[ 0 ].set( this.a, this.b );
  6966. edgeList[ 1 ].set( this.b, this.c );
  6967. edgeList[ 2 ].set( this.c, this.a );
  6968. for( var i = 0; i < edgeList.length; i ++ ) {
  6969. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6970. var distance = projectedPoint.distanceToSquared( closestPoint );
  6971. if( distance < minDistance ) {
  6972. minDistance = distance;
  6973. result.copy( closestPoint );
  6974. }
  6975. }
  6976. }
  6977. return result;
  6978. };
  6979. }(),
  6980. equals: function ( triangle ) {
  6981. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6982. }
  6983. } );
  6984. /**
  6985. * @author mrdoob / http://mrdoob.com/
  6986. * @author alteredq / http://alteredqualia.com/
  6987. */
  6988. function Face3( a, b, c, normal, color, materialIndex ) {
  6989. this.a = a;
  6990. this.b = b;
  6991. this.c = c;
  6992. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6993. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6994. this.color = ( color && color.isColor ) ? color : new Color();
  6995. this.vertexColors = Array.isArray( color ) ? color : [];
  6996. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6997. }
  6998. Object.assign( Face3.prototype, {
  6999. clone: function () {
  7000. return new this.constructor().copy( this );
  7001. },
  7002. copy: function ( source ) {
  7003. this.a = source.a;
  7004. this.b = source.b;
  7005. this.c = source.c;
  7006. this.normal.copy( source.normal );
  7007. this.color.copy( source.color );
  7008. this.materialIndex = source.materialIndex;
  7009. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7010. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7011. }
  7012. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7013. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7014. }
  7015. return this;
  7016. }
  7017. } );
  7018. /**
  7019. * @author mrdoob / http://mrdoob.com/
  7020. * @author alteredq / http://alteredqualia.com/
  7021. *
  7022. * parameters = {
  7023. * color: <hex>,
  7024. * opacity: <float>,
  7025. * map: new THREE.Texture( <Image> ),
  7026. *
  7027. * lightMap: new THREE.Texture( <Image> ),
  7028. * lightMapIntensity: <float>
  7029. *
  7030. * aoMap: new THREE.Texture( <Image> ),
  7031. * aoMapIntensity: <float>
  7032. *
  7033. * specularMap: new THREE.Texture( <Image> ),
  7034. *
  7035. * alphaMap: new THREE.Texture( <Image> ),
  7036. *
  7037. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7038. * combine: THREE.Multiply,
  7039. * reflectivity: <float>,
  7040. * refractionRatio: <float>,
  7041. *
  7042. * shading: THREE.SmoothShading,
  7043. * depthTest: <bool>,
  7044. * depthWrite: <bool>,
  7045. *
  7046. * wireframe: <boolean>,
  7047. * wireframeLinewidth: <float>,
  7048. *
  7049. * skinning: <bool>,
  7050. * morphTargets: <bool>
  7051. * }
  7052. */
  7053. function MeshBasicMaterial( parameters ) {
  7054. Material.call( this );
  7055. this.type = 'MeshBasicMaterial';
  7056. this.color = new Color( 0xffffff ); // emissive
  7057. this.map = null;
  7058. this.lightMap = null;
  7059. this.lightMapIntensity = 1.0;
  7060. this.aoMap = null;
  7061. this.aoMapIntensity = 1.0;
  7062. this.specularMap = null;
  7063. this.alphaMap = null;
  7064. this.envMap = null;
  7065. this.combine = MultiplyOperation;
  7066. this.reflectivity = 1;
  7067. this.refractionRatio = 0.98;
  7068. this.wireframe = false;
  7069. this.wireframeLinewidth = 1;
  7070. this.wireframeLinecap = 'round';
  7071. this.wireframeLinejoin = 'round';
  7072. this.skinning = false;
  7073. this.morphTargets = false;
  7074. this.lights = false;
  7075. this.setValues( parameters );
  7076. }
  7077. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7078. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7079. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7080. MeshBasicMaterial.prototype.copy = function ( source ) {
  7081. Material.prototype.copy.call( this, source );
  7082. this.color.copy( source.color );
  7083. this.map = source.map;
  7084. this.lightMap = source.lightMap;
  7085. this.lightMapIntensity = source.lightMapIntensity;
  7086. this.aoMap = source.aoMap;
  7087. this.aoMapIntensity = source.aoMapIntensity;
  7088. this.specularMap = source.specularMap;
  7089. this.alphaMap = source.alphaMap;
  7090. this.envMap = source.envMap;
  7091. this.combine = source.combine;
  7092. this.reflectivity = source.reflectivity;
  7093. this.refractionRatio = source.refractionRatio;
  7094. this.wireframe = source.wireframe;
  7095. this.wireframeLinewidth = source.wireframeLinewidth;
  7096. this.wireframeLinecap = source.wireframeLinecap;
  7097. this.wireframeLinejoin = source.wireframeLinejoin;
  7098. this.skinning = source.skinning;
  7099. this.morphTargets = source.morphTargets;
  7100. return this;
  7101. };
  7102. /**
  7103. * @author mrdoob / http://mrdoob.com/
  7104. */
  7105. function BufferAttribute( array, itemSize, normalized ) {
  7106. if ( Array.isArray( array ) ) {
  7107. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7108. }
  7109. this.uuid = _Math.generateUUID();
  7110. this.array = array;
  7111. this.itemSize = itemSize;
  7112. this.count = array !== undefined ? array.length / itemSize : 0;
  7113. this.normalized = normalized === true;
  7114. this.dynamic = false;
  7115. this.updateRange = { offset: 0, count: - 1 };
  7116. this.onUploadCallback = function () {};
  7117. this.version = 0;
  7118. }
  7119. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7120. set: function ( value ) {
  7121. if ( value === true ) this.version ++;
  7122. }
  7123. } );
  7124. Object.assign( BufferAttribute.prototype, {
  7125. isBufferAttribute: true,
  7126. setArray: function ( array ) {
  7127. if ( Array.isArray( array ) ) {
  7128. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7129. }
  7130. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7131. this.array = array;
  7132. },
  7133. setDynamic: function ( value ) {
  7134. this.dynamic = value;
  7135. return this;
  7136. },
  7137. copy: function ( source ) {
  7138. this.array = new source.array.constructor( source.array );
  7139. this.itemSize = source.itemSize;
  7140. this.count = source.count;
  7141. this.normalized = source.normalized;
  7142. this.dynamic = source.dynamic;
  7143. return this;
  7144. },
  7145. copyAt: function ( index1, attribute, index2 ) {
  7146. index1 *= this.itemSize;
  7147. index2 *= attribute.itemSize;
  7148. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7149. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7150. }
  7151. return this;
  7152. },
  7153. copyArray: function ( array ) {
  7154. this.array.set( array );
  7155. return this;
  7156. },
  7157. copyColorsArray: function ( colors ) {
  7158. var array = this.array, offset = 0;
  7159. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7160. var color = colors[ i ];
  7161. if ( color === undefined ) {
  7162. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7163. color = new Color();
  7164. }
  7165. array[ offset ++ ] = color.r;
  7166. array[ offset ++ ] = color.g;
  7167. array[ offset ++ ] = color.b;
  7168. }
  7169. return this;
  7170. },
  7171. copyIndicesArray: function ( indices ) {
  7172. var array = this.array, offset = 0;
  7173. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7174. var index = indices[ i ];
  7175. array[ offset ++ ] = index.a;
  7176. array[ offset ++ ] = index.b;
  7177. array[ offset ++ ] = index.c;
  7178. }
  7179. return this;
  7180. },
  7181. copyVector2sArray: function ( vectors ) {
  7182. var array = this.array, offset = 0;
  7183. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7184. var vector = vectors[ i ];
  7185. if ( vector === undefined ) {
  7186. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7187. vector = new Vector2();
  7188. }
  7189. array[ offset ++ ] = vector.x;
  7190. array[ offset ++ ] = vector.y;
  7191. }
  7192. return this;
  7193. },
  7194. copyVector3sArray: function ( vectors ) {
  7195. var array = this.array, offset = 0;
  7196. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7197. var vector = vectors[ i ];
  7198. if ( vector === undefined ) {
  7199. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7200. vector = new Vector3();
  7201. }
  7202. array[ offset ++ ] = vector.x;
  7203. array[ offset ++ ] = vector.y;
  7204. array[ offset ++ ] = vector.z;
  7205. }
  7206. return this;
  7207. },
  7208. copyVector4sArray: function ( vectors ) {
  7209. var array = this.array, offset = 0;
  7210. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7211. var vector = vectors[ i ];
  7212. if ( vector === undefined ) {
  7213. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7214. vector = new Vector4();
  7215. }
  7216. array[ offset ++ ] = vector.x;
  7217. array[ offset ++ ] = vector.y;
  7218. array[ offset ++ ] = vector.z;
  7219. array[ offset ++ ] = vector.w;
  7220. }
  7221. return this;
  7222. },
  7223. set: function ( value, offset ) {
  7224. if ( offset === undefined ) offset = 0;
  7225. this.array.set( value, offset );
  7226. return this;
  7227. },
  7228. getX: function ( index ) {
  7229. return this.array[ index * this.itemSize ];
  7230. },
  7231. setX: function ( index, x ) {
  7232. this.array[ index * this.itemSize ] = x;
  7233. return this;
  7234. },
  7235. getY: function ( index ) {
  7236. return this.array[ index * this.itemSize + 1 ];
  7237. },
  7238. setY: function ( index, y ) {
  7239. this.array[ index * this.itemSize + 1 ] = y;
  7240. return this;
  7241. },
  7242. getZ: function ( index ) {
  7243. return this.array[ index * this.itemSize + 2 ];
  7244. },
  7245. setZ: function ( index, z ) {
  7246. this.array[ index * this.itemSize + 2 ] = z;
  7247. return this;
  7248. },
  7249. getW: function ( index ) {
  7250. return this.array[ index * this.itemSize + 3 ];
  7251. },
  7252. setW: function ( index, w ) {
  7253. this.array[ index * this.itemSize + 3 ] = w;
  7254. return this;
  7255. },
  7256. setXY: function ( index, x, y ) {
  7257. index *= this.itemSize;
  7258. this.array[ index + 0 ] = x;
  7259. this.array[ index + 1 ] = y;
  7260. return this;
  7261. },
  7262. setXYZ: function ( index, x, y, z ) {
  7263. index *= this.itemSize;
  7264. this.array[ index + 0 ] = x;
  7265. this.array[ index + 1 ] = y;
  7266. this.array[ index + 2 ] = z;
  7267. return this;
  7268. },
  7269. setXYZW: function ( index, x, y, z, w ) {
  7270. index *= this.itemSize;
  7271. this.array[ index + 0 ] = x;
  7272. this.array[ index + 1 ] = y;
  7273. this.array[ index + 2 ] = z;
  7274. this.array[ index + 3 ] = w;
  7275. return this;
  7276. },
  7277. onUpload: function ( callback ) {
  7278. this.onUploadCallback = callback;
  7279. return this;
  7280. },
  7281. clone: function () {
  7282. return new this.constructor( this.array, this.itemSize ).copy( this );
  7283. }
  7284. } );
  7285. //
  7286. function Int8BufferAttribute( array, itemSize ) {
  7287. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7288. }
  7289. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7290. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7291. function Uint8BufferAttribute( array, itemSize ) {
  7292. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7293. }
  7294. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7295. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7296. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7297. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7298. }
  7299. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7300. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7301. function Int16BufferAttribute( array, itemSize ) {
  7302. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7303. }
  7304. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7305. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7306. function Uint16BufferAttribute( array, itemSize ) {
  7307. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7308. }
  7309. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7310. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7311. function Int32BufferAttribute( array, itemSize ) {
  7312. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7313. }
  7314. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7315. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7316. function Uint32BufferAttribute( array, itemSize ) {
  7317. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7318. }
  7319. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7320. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7321. function Float32BufferAttribute( array, itemSize ) {
  7322. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7323. }
  7324. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7325. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7326. function Float64BufferAttribute( array, itemSize ) {
  7327. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7328. }
  7329. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7330. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7331. /**
  7332. * @author mrdoob / http://mrdoob.com/
  7333. */
  7334. function DirectGeometry() {
  7335. this.indices = [];
  7336. this.vertices = [];
  7337. this.normals = [];
  7338. this.colors = [];
  7339. this.uvs = [];
  7340. this.uvs2 = [];
  7341. this.groups = [];
  7342. this.morphTargets = {};
  7343. this.skinWeights = [];
  7344. this.skinIndices = [];
  7345. // this.lineDistances = [];
  7346. this.boundingBox = null;
  7347. this.boundingSphere = null;
  7348. // update flags
  7349. this.verticesNeedUpdate = false;
  7350. this.normalsNeedUpdate = false;
  7351. this.colorsNeedUpdate = false;
  7352. this.uvsNeedUpdate = false;
  7353. this.groupsNeedUpdate = false;
  7354. }
  7355. Object.assign( DirectGeometry.prototype, {
  7356. computeGroups: function ( geometry ) {
  7357. var group;
  7358. var groups = [];
  7359. var materialIndex = undefined;
  7360. var faces = geometry.faces;
  7361. for ( var i = 0; i < faces.length; i ++ ) {
  7362. var face = faces[ i ];
  7363. // materials
  7364. if ( face.materialIndex !== materialIndex ) {
  7365. materialIndex = face.materialIndex;
  7366. if ( group !== undefined ) {
  7367. group.count = ( i * 3 ) - group.start;
  7368. groups.push( group );
  7369. }
  7370. group = {
  7371. start: i * 3,
  7372. materialIndex: materialIndex
  7373. };
  7374. }
  7375. }
  7376. if ( group !== undefined ) {
  7377. group.count = ( i * 3 ) - group.start;
  7378. groups.push( group );
  7379. }
  7380. this.groups = groups;
  7381. },
  7382. fromGeometry: function ( geometry ) {
  7383. var faces = geometry.faces;
  7384. var vertices = geometry.vertices;
  7385. var faceVertexUvs = geometry.faceVertexUvs;
  7386. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7387. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7388. // morphs
  7389. var morphTargets = geometry.morphTargets;
  7390. var morphTargetsLength = morphTargets.length;
  7391. var morphTargetsPosition;
  7392. if ( morphTargetsLength > 0 ) {
  7393. morphTargetsPosition = [];
  7394. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7395. morphTargetsPosition[ i ] = [];
  7396. }
  7397. this.morphTargets.position = morphTargetsPosition;
  7398. }
  7399. var morphNormals = geometry.morphNormals;
  7400. var morphNormalsLength = morphNormals.length;
  7401. var morphTargetsNormal;
  7402. if ( morphNormalsLength > 0 ) {
  7403. morphTargetsNormal = [];
  7404. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7405. morphTargetsNormal[ i ] = [];
  7406. }
  7407. this.morphTargets.normal = morphTargetsNormal;
  7408. }
  7409. // skins
  7410. var skinIndices = geometry.skinIndices;
  7411. var skinWeights = geometry.skinWeights;
  7412. var hasSkinIndices = skinIndices.length === vertices.length;
  7413. var hasSkinWeights = skinWeights.length === vertices.length;
  7414. //
  7415. for ( var i = 0; i < faces.length; i ++ ) {
  7416. var face = faces[ i ];
  7417. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7418. var vertexNormals = face.vertexNormals;
  7419. if ( vertexNormals.length === 3 ) {
  7420. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7421. } else {
  7422. var normal = face.normal;
  7423. this.normals.push( normal, normal, normal );
  7424. }
  7425. var vertexColors = face.vertexColors;
  7426. if ( vertexColors.length === 3 ) {
  7427. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7428. } else {
  7429. var color = face.color;
  7430. this.colors.push( color, color, color );
  7431. }
  7432. if ( hasFaceVertexUv === true ) {
  7433. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7434. if ( vertexUvs !== undefined ) {
  7435. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7436. } else {
  7437. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7438. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7439. }
  7440. }
  7441. if ( hasFaceVertexUv2 === true ) {
  7442. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7443. if ( vertexUvs !== undefined ) {
  7444. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7445. } else {
  7446. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7447. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7448. }
  7449. }
  7450. // morphs
  7451. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7452. var morphTarget = morphTargets[ j ].vertices;
  7453. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7454. }
  7455. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7456. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7457. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7458. }
  7459. // skins
  7460. if ( hasSkinIndices ) {
  7461. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7462. }
  7463. if ( hasSkinWeights ) {
  7464. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7465. }
  7466. }
  7467. this.computeGroups( geometry );
  7468. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7469. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7470. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7471. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7472. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7473. return this;
  7474. }
  7475. } );
  7476. function arrayMax( array ) {
  7477. if ( array.length === 0 ) return - Infinity;
  7478. var max = array[ 0 ];
  7479. for ( var i = 1, l = array.length; i < l; ++ i ) {
  7480. if ( array[ i ] > max ) max = array[ i ];
  7481. }
  7482. return max;
  7483. }
  7484. /**
  7485. * @author mrdoob / http://mrdoob.com/
  7486. * @author kile / http://kile.stravaganza.org/
  7487. * @author alteredq / http://alteredqualia.com/
  7488. * @author mikael emtinger / http://gomo.se/
  7489. * @author zz85 / http://www.lab4games.net/zz85/blog
  7490. * @author bhouston / http://clara.io
  7491. */
  7492. var count = 0;
  7493. function GeometryIdCount() { return count++; }
  7494. function Geometry() {
  7495. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7496. this.uuid = _Math.generateUUID();
  7497. this.name = '';
  7498. this.type = 'Geometry';
  7499. this.vertices = [];
  7500. this.colors = [];
  7501. this.faces = [];
  7502. this.faceVertexUvs = [[]];
  7503. this.morphTargets = [];
  7504. this.morphNormals = [];
  7505. this.skinWeights = [];
  7506. this.skinIndices = [];
  7507. this.lineDistances = [];
  7508. this.boundingBox = null;
  7509. this.boundingSphere = null;
  7510. // update flags
  7511. this.elementsNeedUpdate = false;
  7512. this.verticesNeedUpdate = false;
  7513. this.uvsNeedUpdate = false;
  7514. this.normalsNeedUpdate = false;
  7515. this.colorsNeedUpdate = false;
  7516. this.lineDistancesNeedUpdate = false;
  7517. this.groupsNeedUpdate = false;
  7518. }
  7519. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7520. isGeometry: true,
  7521. applyMatrix: function ( matrix ) {
  7522. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7523. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7524. var vertex = this.vertices[ i ];
  7525. vertex.applyMatrix4( matrix );
  7526. }
  7527. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7528. var face = this.faces[ i ];
  7529. face.normal.applyMatrix3( normalMatrix ).normalize();
  7530. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7531. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7532. }
  7533. }
  7534. if ( this.boundingBox !== null ) {
  7535. this.computeBoundingBox();
  7536. }
  7537. if ( this.boundingSphere !== null ) {
  7538. this.computeBoundingSphere();
  7539. }
  7540. this.verticesNeedUpdate = true;
  7541. this.normalsNeedUpdate = true;
  7542. return this;
  7543. },
  7544. rotateX: function () {
  7545. // rotate geometry around world x-axis
  7546. var m1;
  7547. return function rotateX( angle ) {
  7548. if ( m1 === undefined ) m1 = new Matrix4();
  7549. m1.makeRotationX( angle );
  7550. this.applyMatrix( m1 );
  7551. return this;
  7552. };
  7553. }(),
  7554. rotateY: function () {
  7555. // rotate geometry around world y-axis
  7556. var m1;
  7557. return function rotateY( angle ) {
  7558. if ( m1 === undefined ) m1 = new Matrix4();
  7559. m1.makeRotationY( angle );
  7560. this.applyMatrix( m1 );
  7561. return this;
  7562. };
  7563. }(),
  7564. rotateZ: function () {
  7565. // rotate geometry around world z-axis
  7566. var m1;
  7567. return function rotateZ( angle ) {
  7568. if ( m1 === undefined ) m1 = new Matrix4();
  7569. m1.makeRotationZ( angle );
  7570. this.applyMatrix( m1 );
  7571. return this;
  7572. };
  7573. }(),
  7574. translate: function () {
  7575. // translate geometry
  7576. var m1;
  7577. return function translate( x, y, z ) {
  7578. if ( m1 === undefined ) m1 = new Matrix4();
  7579. m1.makeTranslation( x, y, z );
  7580. this.applyMatrix( m1 );
  7581. return this;
  7582. };
  7583. }(),
  7584. scale: function () {
  7585. // scale geometry
  7586. var m1;
  7587. return function scale( x, y, z ) {
  7588. if ( m1 === undefined ) m1 = new Matrix4();
  7589. m1.makeScale( x, y, z );
  7590. this.applyMatrix( m1 );
  7591. return this;
  7592. };
  7593. }(),
  7594. lookAt: function () {
  7595. var obj;
  7596. return function lookAt( vector ) {
  7597. if ( obj === undefined ) obj = new Object3D();
  7598. obj.lookAt( vector );
  7599. obj.updateMatrix();
  7600. this.applyMatrix( obj.matrix );
  7601. };
  7602. }(),
  7603. fromBufferGeometry: function ( geometry ) {
  7604. var scope = this;
  7605. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7606. var attributes = geometry.attributes;
  7607. var positions = attributes.position.array;
  7608. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7609. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7610. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7611. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7612. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7613. var tempNormals = [];
  7614. var tempUVs = [];
  7615. var tempUVs2 = [];
  7616. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7617. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7618. if ( normals !== undefined ) {
  7619. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7620. }
  7621. if ( colors !== undefined ) {
  7622. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7623. }
  7624. if ( uvs !== undefined ) {
  7625. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7626. }
  7627. if ( uvs2 !== undefined ) {
  7628. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7629. }
  7630. }
  7631. function addFace( a, b, c, materialIndex ) {
  7632. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7633. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7634. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7635. scope.faces.push( face );
  7636. if ( uvs !== undefined ) {
  7637. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7638. }
  7639. if ( uvs2 !== undefined ) {
  7640. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7641. }
  7642. }
  7643. var groups = geometry.groups;
  7644. if ( groups.length > 0 ) {
  7645. for ( var i = 0; i < groups.length; i ++ ) {
  7646. var group = groups[ i ];
  7647. var start = group.start;
  7648. var count = group.count;
  7649. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7650. if ( indices !== undefined ) {
  7651. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7652. } else {
  7653. addFace( j, j + 1, j + 2, group.materialIndex );
  7654. }
  7655. }
  7656. }
  7657. } else {
  7658. if ( indices !== undefined ) {
  7659. for ( var i = 0; i < indices.length; i += 3 ) {
  7660. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7661. }
  7662. } else {
  7663. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7664. addFace( i, i + 1, i + 2 );
  7665. }
  7666. }
  7667. }
  7668. this.computeFaceNormals();
  7669. if ( geometry.boundingBox !== null ) {
  7670. this.boundingBox = geometry.boundingBox.clone();
  7671. }
  7672. if ( geometry.boundingSphere !== null ) {
  7673. this.boundingSphere = geometry.boundingSphere.clone();
  7674. }
  7675. return this;
  7676. },
  7677. center: function () {
  7678. this.computeBoundingBox();
  7679. var offset = this.boundingBox.getCenter().negate();
  7680. this.translate( offset.x, offset.y, offset.z );
  7681. return offset;
  7682. },
  7683. normalize: function () {
  7684. this.computeBoundingSphere();
  7685. var center = this.boundingSphere.center;
  7686. var radius = this.boundingSphere.radius;
  7687. var s = radius === 0 ? 1 : 1.0 / radius;
  7688. var matrix = new Matrix4();
  7689. matrix.set(
  7690. s, 0, 0, - s * center.x,
  7691. 0, s, 0, - s * center.y,
  7692. 0, 0, s, - s * center.z,
  7693. 0, 0, 0, 1
  7694. );
  7695. this.applyMatrix( matrix );
  7696. return this;
  7697. },
  7698. computeFaceNormals: function () {
  7699. var cb = new Vector3(), ab = new Vector3();
  7700. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7701. var face = this.faces[ f ];
  7702. var vA = this.vertices[ face.a ];
  7703. var vB = this.vertices[ face.b ];
  7704. var vC = this.vertices[ face.c ];
  7705. cb.subVectors( vC, vB );
  7706. ab.subVectors( vA, vB );
  7707. cb.cross( ab );
  7708. cb.normalize();
  7709. face.normal.copy( cb );
  7710. }
  7711. },
  7712. computeVertexNormals: function ( areaWeighted ) {
  7713. if ( areaWeighted === undefined ) areaWeighted = true;
  7714. var v, vl, f, fl, face, vertices;
  7715. vertices = new Array( this.vertices.length );
  7716. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7717. vertices[ v ] = new Vector3();
  7718. }
  7719. if ( areaWeighted ) {
  7720. // vertex normals weighted by triangle areas
  7721. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7722. var vA, vB, vC;
  7723. var cb = new Vector3(), ab = new Vector3();
  7724. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7725. face = this.faces[ f ];
  7726. vA = this.vertices[ face.a ];
  7727. vB = this.vertices[ face.b ];
  7728. vC = this.vertices[ face.c ];
  7729. cb.subVectors( vC, vB );
  7730. ab.subVectors( vA, vB );
  7731. cb.cross( ab );
  7732. vertices[ face.a ].add( cb );
  7733. vertices[ face.b ].add( cb );
  7734. vertices[ face.c ].add( cb );
  7735. }
  7736. } else {
  7737. this.computeFaceNormals();
  7738. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7739. face = this.faces[ f ];
  7740. vertices[ face.a ].add( face.normal );
  7741. vertices[ face.b ].add( face.normal );
  7742. vertices[ face.c ].add( face.normal );
  7743. }
  7744. }
  7745. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7746. vertices[ v ].normalize();
  7747. }
  7748. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7749. face = this.faces[ f ];
  7750. var vertexNormals = face.vertexNormals;
  7751. if ( vertexNormals.length === 3 ) {
  7752. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7753. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7754. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7755. } else {
  7756. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7757. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7758. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7759. }
  7760. }
  7761. if ( this.faces.length > 0 ) {
  7762. this.normalsNeedUpdate = true;
  7763. }
  7764. },
  7765. computeFlatVertexNormals: function () {
  7766. var f, fl, face;
  7767. this.computeFaceNormals();
  7768. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7769. face = this.faces[ f ];
  7770. var vertexNormals = face.vertexNormals;
  7771. if ( vertexNormals.length === 3 ) {
  7772. vertexNormals[ 0 ].copy( face.normal );
  7773. vertexNormals[ 1 ].copy( face.normal );
  7774. vertexNormals[ 2 ].copy( face.normal );
  7775. } else {
  7776. vertexNormals[ 0 ] = face.normal.clone();
  7777. vertexNormals[ 1 ] = face.normal.clone();
  7778. vertexNormals[ 2 ] = face.normal.clone();
  7779. }
  7780. }
  7781. if ( this.faces.length > 0 ) {
  7782. this.normalsNeedUpdate = true;
  7783. }
  7784. },
  7785. computeMorphNormals: function () {
  7786. var i, il, f, fl, face;
  7787. // save original normals
  7788. // - create temp variables on first access
  7789. // otherwise just copy (for faster repeated calls)
  7790. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7791. face = this.faces[ f ];
  7792. if ( ! face.__originalFaceNormal ) {
  7793. face.__originalFaceNormal = face.normal.clone();
  7794. } else {
  7795. face.__originalFaceNormal.copy( face.normal );
  7796. }
  7797. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7798. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7799. if ( ! face.__originalVertexNormals[ i ] ) {
  7800. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7801. } else {
  7802. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7803. }
  7804. }
  7805. }
  7806. // use temp geometry to compute face and vertex normals for each morph
  7807. var tmpGeo = new Geometry();
  7808. tmpGeo.faces = this.faces;
  7809. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7810. // create on first access
  7811. if ( ! this.morphNormals[ i ] ) {
  7812. this.morphNormals[ i ] = {};
  7813. this.morphNormals[ i ].faceNormals = [];
  7814. this.morphNormals[ i ].vertexNormals = [];
  7815. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7816. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7817. var faceNormal, vertexNormals;
  7818. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7819. faceNormal = new Vector3();
  7820. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7821. dstNormalsFace.push( faceNormal );
  7822. dstNormalsVertex.push( vertexNormals );
  7823. }
  7824. }
  7825. var morphNormals = this.morphNormals[ i ];
  7826. // set vertices to morph target
  7827. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7828. // compute morph normals
  7829. tmpGeo.computeFaceNormals();
  7830. tmpGeo.computeVertexNormals();
  7831. // store morph normals
  7832. var faceNormal, vertexNormals;
  7833. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7834. face = this.faces[ f ];
  7835. faceNormal = morphNormals.faceNormals[ f ];
  7836. vertexNormals = morphNormals.vertexNormals[ f ];
  7837. faceNormal.copy( face.normal );
  7838. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7839. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7840. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7841. }
  7842. }
  7843. // restore original normals
  7844. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7845. face = this.faces[ f ];
  7846. face.normal = face.__originalFaceNormal;
  7847. face.vertexNormals = face.__originalVertexNormals;
  7848. }
  7849. },
  7850. computeLineDistances: function () {
  7851. var d = 0;
  7852. var vertices = this.vertices;
  7853. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7854. if ( i > 0 ) {
  7855. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7856. }
  7857. this.lineDistances[ i ] = d;
  7858. }
  7859. },
  7860. computeBoundingBox: function () {
  7861. if ( this.boundingBox === null ) {
  7862. this.boundingBox = new Box3();
  7863. }
  7864. this.boundingBox.setFromPoints( this.vertices );
  7865. },
  7866. computeBoundingSphere: function () {
  7867. if ( this.boundingSphere === null ) {
  7868. this.boundingSphere = new Sphere();
  7869. }
  7870. this.boundingSphere.setFromPoints( this.vertices );
  7871. },
  7872. merge: function ( geometry, matrix, materialIndexOffset ) {
  7873. if ( ( geometry && geometry.isGeometry ) === false ) {
  7874. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7875. return;
  7876. }
  7877. var normalMatrix,
  7878. vertexOffset = this.vertices.length,
  7879. vertices1 = this.vertices,
  7880. vertices2 = geometry.vertices,
  7881. faces1 = this.faces,
  7882. faces2 = geometry.faces,
  7883. uvs1 = this.faceVertexUvs[ 0 ],
  7884. uvs2 = geometry.faceVertexUvs[ 0 ],
  7885. colors1 = this.colors,
  7886. colors2 = geometry.colors;
  7887. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7888. if ( matrix !== undefined ) {
  7889. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7890. }
  7891. // vertices
  7892. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7893. var vertex = vertices2[ i ];
  7894. var vertexCopy = vertex.clone();
  7895. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7896. vertices1.push( vertexCopy );
  7897. }
  7898. // colors
  7899. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7900. colors1.push( colors2[ i ].clone() );
  7901. }
  7902. // faces
  7903. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7904. var face = faces2[ i ], faceCopy, normal, color,
  7905. faceVertexNormals = face.vertexNormals,
  7906. faceVertexColors = face.vertexColors;
  7907. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7908. faceCopy.normal.copy( face.normal );
  7909. if ( normalMatrix !== undefined ) {
  7910. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7911. }
  7912. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7913. normal = faceVertexNormals[ j ].clone();
  7914. if ( normalMatrix !== undefined ) {
  7915. normal.applyMatrix3( normalMatrix ).normalize();
  7916. }
  7917. faceCopy.vertexNormals.push( normal );
  7918. }
  7919. faceCopy.color.copy( face.color );
  7920. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7921. color = faceVertexColors[ j ];
  7922. faceCopy.vertexColors.push( color.clone() );
  7923. }
  7924. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7925. faces1.push( faceCopy );
  7926. }
  7927. // uvs
  7928. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7929. var uv = uvs2[ i ], uvCopy = [];
  7930. if ( uv === undefined ) {
  7931. continue;
  7932. }
  7933. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7934. uvCopy.push( uv[ j ].clone() );
  7935. }
  7936. uvs1.push( uvCopy );
  7937. }
  7938. },
  7939. mergeMesh: function ( mesh ) {
  7940. if ( ( mesh && mesh.isMesh ) === false ) {
  7941. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7942. return;
  7943. }
  7944. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7945. this.merge( mesh.geometry, mesh.matrix );
  7946. },
  7947. /*
  7948. * Checks for duplicate vertices with hashmap.
  7949. * Duplicated vertices are removed
  7950. * and faces' vertices are updated.
  7951. */
  7952. mergeVertices: function () {
  7953. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7954. var unique = [], changes = [];
  7955. var v, key;
  7956. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7957. var precision = Math.pow( 10, precisionPoints );
  7958. var i, il, face;
  7959. var indices, j, jl;
  7960. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7961. v = this.vertices[ i ];
  7962. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7963. if ( verticesMap[ key ] === undefined ) {
  7964. verticesMap[ key ] = i;
  7965. unique.push( this.vertices[ i ] );
  7966. changes[ i ] = unique.length - 1;
  7967. } else {
  7968. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7969. changes[ i ] = changes[ verticesMap[ key ] ];
  7970. }
  7971. }
  7972. // if faces are completely degenerate after merging vertices, we
  7973. // have to remove them from the geometry.
  7974. var faceIndicesToRemove = [];
  7975. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7976. face = this.faces[ i ];
  7977. face.a = changes[ face.a ];
  7978. face.b = changes[ face.b ];
  7979. face.c = changes[ face.c ];
  7980. indices = [ face.a, face.b, face.c ];
  7981. // if any duplicate vertices are found in a Face3
  7982. // we have to remove the face as nothing can be saved
  7983. for ( var n = 0; n < 3; n ++ ) {
  7984. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7985. faceIndicesToRemove.push( i );
  7986. break;
  7987. }
  7988. }
  7989. }
  7990. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7991. var idx = faceIndicesToRemove[ i ];
  7992. this.faces.splice( idx, 1 );
  7993. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7994. this.faceVertexUvs[ j ].splice( idx, 1 );
  7995. }
  7996. }
  7997. // Use unique set of vertices
  7998. var diff = this.vertices.length - unique.length;
  7999. this.vertices = unique;
  8000. return diff;
  8001. },
  8002. sortFacesByMaterialIndex: function () {
  8003. var faces = this.faces;
  8004. var length = faces.length;
  8005. // tag faces
  8006. for ( var i = 0; i < length; i ++ ) {
  8007. faces[ i ]._id = i;
  8008. }
  8009. // sort faces
  8010. function materialIndexSort( a, b ) {
  8011. return a.materialIndex - b.materialIndex;
  8012. }
  8013. faces.sort( materialIndexSort );
  8014. // sort uvs
  8015. var uvs1 = this.faceVertexUvs[ 0 ];
  8016. var uvs2 = this.faceVertexUvs[ 1 ];
  8017. var newUvs1, newUvs2;
  8018. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8019. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8020. for ( var i = 0; i < length; i ++ ) {
  8021. var id = faces[ i ]._id;
  8022. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8023. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8024. }
  8025. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8026. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8027. },
  8028. toJSON: function () {
  8029. var data = {
  8030. metadata: {
  8031. version: 4.5,
  8032. type: 'Geometry',
  8033. generator: 'Geometry.toJSON'
  8034. }
  8035. };
  8036. // standard Geometry serialization
  8037. data.uuid = this.uuid;
  8038. data.type = this.type;
  8039. if ( this.name !== '' ) data.name = this.name;
  8040. if ( this.parameters !== undefined ) {
  8041. var parameters = this.parameters;
  8042. for ( var key in parameters ) {
  8043. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8044. }
  8045. return data;
  8046. }
  8047. var vertices = [];
  8048. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8049. var vertex = this.vertices[ i ];
  8050. vertices.push( vertex.x, vertex.y, vertex.z );
  8051. }
  8052. var faces = [];
  8053. var normals = [];
  8054. var normalsHash = {};
  8055. var colors = [];
  8056. var colorsHash = {};
  8057. var uvs = [];
  8058. var uvsHash = {};
  8059. for ( var i = 0; i < this.faces.length; i ++ ) {
  8060. var face = this.faces[ i ];
  8061. var hasMaterial = true;
  8062. var hasFaceUv = false; // deprecated
  8063. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8064. var hasFaceNormal = face.normal.length() > 0;
  8065. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8066. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8067. var hasFaceVertexColor = face.vertexColors.length > 0;
  8068. var faceType = 0;
  8069. faceType = setBit( faceType, 0, 0 ); // isQuad
  8070. faceType = setBit( faceType, 1, hasMaterial );
  8071. faceType = setBit( faceType, 2, hasFaceUv );
  8072. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8073. faceType = setBit( faceType, 4, hasFaceNormal );
  8074. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8075. faceType = setBit( faceType, 6, hasFaceColor );
  8076. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8077. faces.push( faceType );
  8078. faces.push( face.a, face.b, face.c );
  8079. faces.push( face.materialIndex );
  8080. if ( hasFaceVertexUv ) {
  8081. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8082. faces.push(
  8083. getUvIndex( faceVertexUvs[ 0 ] ),
  8084. getUvIndex( faceVertexUvs[ 1 ] ),
  8085. getUvIndex( faceVertexUvs[ 2 ] )
  8086. );
  8087. }
  8088. if ( hasFaceNormal ) {
  8089. faces.push( getNormalIndex( face.normal ) );
  8090. }
  8091. if ( hasFaceVertexNormal ) {
  8092. var vertexNormals = face.vertexNormals;
  8093. faces.push(
  8094. getNormalIndex( vertexNormals[ 0 ] ),
  8095. getNormalIndex( vertexNormals[ 1 ] ),
  8096. getNormalIndex( vertexNormals[ 2 ] )
  8097. );
  8098. }
  8099. if ( hasFaceColor ) {
  8100. faces.push( getColorIndex( face.color ) );
  8101. }
  8102. if ( hasFaceVertexColor ) {
  8103. var vertexColors = face.vertexColors;
  8104. faces.push(
  8105. getColorIndex( vertexColors[ 0 ] ),
  8106. getColorIndex( vertexColors[ 1 ] ),
  8107. getColorIndex( vertexColors[ 2 ] )
  8108. );
  8109. }
  8110. }
  8111. function setBit( value, position, enabled ) {
  8112. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8113. }
  8114. function getNormalIndex( normal ) {
  8115. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8116. if ( normalsHash[ hash ] !== undefined ) {
  8117. return normalsHash[ hash ];
  8118. }
  8119. normalsHash[ hash ] = normals.length / 3;
  8120. normals.push( normal.x, normal.y, normal.z );
  8121. return normalsHash[ hash ];
  8122. }
  8123. function getColorIndex( color ) {
  8124. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8125. if ( colorsHash[ hash ] !== undefined ) {
  8126. return colorsHash[ hash ];
  8127. }
  8128. colorsHash[ hash ] = colors.length;
  8129. colors.push( color.getHex() );
  8130. return colorsHash[ hash ];
  8131. }
  8132. function getUvIndex( uv ) {
  8133. var hash = uv.x.toString() + uv.y.toString();
  8134. if ( uvsHash[ hash ] !== undefined ) {
  8135. return uvsHash[ hash ];
  8136. }
  8137. uvsHash[ hash ] = uvs.length / 2;
  8138. uvs.push( uv.x, uv.y );
  8139. return uvsHash[ hash ];
  8140. }
  8141. data.data = {};
  8142. data.data.vertices = vertices;
  8143. data.data.normals = normals;
  8144. if ( colors.length > 0 ) data.data.colors = colors;
  8145. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8146. data.data.faces = faces;
  8147. return data;
  8148. },
  8149. clone: function () {
  8150. /*
  8151. // Handle primitives
  8152. var parameters = this.parameters;
  8153. if ( parameters !== undefined ) {
  8154. var values = [];
  8155. for ( var key in parameters ) {
  8156. values.push( parameters[ key ] );
  8157. }
  8158. var geometry = Object.create( this.constructor.prototype );
  8159. this.constructor.apply( geometry, values );
  8160. return geometry;
  8161. }
  8162. return new this.constructor().copy( this );
  8163. */
  8164. return new Geometry().copy( this );
  8165. },
  8166. copy: function ( source ) {
  8167. var i, il, j, jl, k, kl;
  8168. // reset
  8169. this.vertices = [];
  8170. this.colors = [];
  8171. this.faces = [];
  8172. this.faceVertexUvs = [[]];
  8173. this.morphTargets = [];
  8174. this.morphNormals = [];
  8175. this.skinWeights = [];
  8176. this.skinIndices = [];
  8177. this.lineDistances = [];
  8178. this.boundingBox = null;
  8179. this.boundingSphere = null;
  8180. // name
  8181. this.name = source.name;
  8182. // vertices
  8183. var vertices = source.vertices;
  8184. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  8185. this.vertices.push( vertices[ i ].clone() );
  8186. }
  8187. // colors
  8188. var colors = source.colors;
  8189. for ( i = 0, il = colors.length; i < il; i ++ ) {
  8190. this.colors.push( colors[ i ].clone() );
  8191. }
  8192. // faces
  8193. var faces = source.faces;
  8194. for ( i = 0, il = faces.length; i < il; i ++ ) {
  8195. this.faces.push( faces[ i ].clone() );
  8196. }
  8197. // face vertex uvs
  8198. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8199. var faceVertexUvs = source.faceVertexUvs[ i ];
  8200. if ( this.faceVertexUvs[ i ] === undefined ) {
  8201. this.faceVertexUvs[ i ] = [];
  8202. }
  8203. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8204. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8205. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  8206. var uv = uvs[ k ];
  8207. uvsCopy.push( uv.clone() );
  8208. }
  8209. this.faceVertexUvs[ i ].push( uvsCopy );
  8210. }
  8211. }
  8212. // morph targets
  8213. var morphTargets = source.morphTargets;
  8214. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  8215. var morphTarget = {};
  8216. morphTarget.name = morphTargets[ i ].name;
  8217. // vertices
  8218. if ( morphTargets[ i ].vertices !== undefined ) {
  8219. morphTarget.vertices = [];
  8220. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  8221. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  8222. }
  8223. }
  8224. // normals
  8225. if ( morphTargets[ i ].normals !== undefined ) {
  8226. morphTarget.normals = [];
  8227. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  8228. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  8229. }
  8230. }
  8231. this.morphTargets.push( morphTarget );
  8232. }
  8233. // morph normals
  8234. var morphNormals = source.morphNormals;
  8235. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  8236. var morphNormal = {};
  8237. // vertex normals
  8238. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  8239. morphNormal.vertexNormals = [];
  8240. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  8241. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  8242. var destVertexNormal = {};
  8243. destVertexNormal.a = srcVertexNormal.a.clone();
  8244. destVertexNormal.b = srcVertexNormal.b.clone();
  8245. destVertexNormal.c = srcVertexNormal.c.clone();
  8246. morphNormal.vertexNormals.push( destVertexNormal );
  8247. }
  8248. }
  8249. // face normals
  8250. if ( morphNormals[ i ].faceNormals !== undefined ) {
  8251. morphNormal.faceNormals = [];
  8252. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  8253. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  8254. }
  8255. }
  8256. this.morphNormals.push( morphNormal );
  8257. }
  8258. // skin weights
  8259. var skinWeights = source.skinWeights;
  8260. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  8261. this.skinWeights.push( skinWeights[ i ].clone() );
  8262. }
  8263. // skin indices
  8264. var skinIndices = source.skinIndices;
  8265. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  8266. this.skinIndices.push( skinIndices[ i ].clone() );
  8267. }
  8268. // line distances
  8269. var lineDistances = source.lineDistances;
  8270. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  8271. this.lineDistances.push( lineDistances[ i ] );
  8272. }
  8273. // bounding box
  8274. var boundingBox = source.boundingBox;
  8275. if ( boundingBox !== null ) {
  8276. this.boundingBox = boundingBox.clone();
  8277. }
  8278. // bounding sphere
  8279. var boundingSphere = source.boundingSphere;
  8280. if ( boundingSphere !== null ) {
  8281. this.boundingSphere = boundingSphere.clone();
  8282. }
  8283. // update flags
  8284. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8285. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8286. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8287. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8288. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8289. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8290. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8291. return this;
  8292. },
  8293. dispose: function () {
  8294. this.dispatchEvent( { type: 'dispose' } );
  8295. }
  8296. } );
  8297. /**
  8298. * @author alteredq / http://alteredqualia.com/
  8299. * @author mrdoob / http://mrdoob.com/
  8300. */
  8301. function BufferGeometry() {
  8302. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8303. this.uuid = _Math.generateUUID();
  8304. this.name = '';
  8305. this.type = 'BufferGeometry';
  8306. this.index = null;
  8307. this.attributes = {};
  8308. this.morphAttributes = {};
  8309. this.groups = [];
  8310. this.boundingBox = null;
  8311. this.boundingSphere = null;
  8312. this.drawRange = { start: 0, count: Infinity };
  8313. }
  8314. BufferGeometry.MaxIndex = 65535;
  8315. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8316. isBufferGeometry: true,
  8317. getIndex: function () {
  8318. return this.index;
  8319. },
  8320. setIndex: function ( index ) {
  8321. if ( Array.isArray( index ) ) {
  8322. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8323. } else {
  8324. this.index = index;
  8325. }
  8326. },
  8327. addAttribute: function ( name, attribute ) {
  8328. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8329. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8330. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8331. return;
  8332. }
  8333. if ( name === 'index' ) {
  8334. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8335. this.setIndex( attribute );
  8336. return;
  8337. }
  8338. this.attributes[ name ] = attribute;
  8339. return this;
  8340. },
  8341. getAttribute: function ( name ) {
  8342. return this.attributes[ name ];
  8343. },
  8344. removeAttribute: function ( name ) {
  8345. delete this.attributes[ name ];
  8346. return this;
  8347. },
  8348. addGroup: function ( start, count, materialIndex ) {
  8349. this.groups.push( {
  8350. start: start,
  8351. count: count,
  8352. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8353. } );
  8354. },
  8355. clearGroups: function () {
  8356. this.groups = [];
  8357. },
  8358. setDrawRange: function ( start, count ) {
  8359. this.drawRange.start = start;
  8360. this.drawRange.count = count;
  8361. },
  8362. applyMatrix: function ( matrix ) {
  8363. var position = this.attributes.position;
  8364. if ( position !== undefined ) {
  8365. matrix.applyToBufferAttribute( position );
  8366. position.needsUpdate = true;
  8367. }
  8368. var normal = this.attributes.normal;
  8369. if ( normal !== undefined ) {
  8370. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8371. normalMatrix.applyToBufferAttribute( normal );
  8372. normal.needsUpdate = true;
  8373. }
  8374. if ( this.boundingBox !== null ) {
  8375. this.computeBoundingBox();
  8376. }
  8377. if ( this.boundingSphere !== null ) {
  8378. this.computeBoundingSphere();
  8379. }
  8380. return this;
  8381. },
  8382. rotateX: function () {
  8383. // rotate geometry around world x-axis
  8384. var m1;
  8385. return function rotateX( angle ) {
  8386. if ( m1 === undefined ) m1 = new Matrix4();
  8387. m1.makeRotationX( angle );
  8388. this.applyMatrix( m1 );
  8389. return this;
  8390. };
  8391. }(),
  8392. rotateY: function () {
  8393. // rotate geometry around world y-axis
  8394. var m1;
  8395. return function rotateY( angle ) {
  8396. if ( m1 === undefined ) m1 = new Matrix4();
  8397. m1.makeRotationY( angle );
  8398. this.applyMatrix( m1 );
  8399. return this;
  8400. };
  8401. }(),
  8402. rotateZ: function () {
  8403. // rotate geometry around world z-axis
  8404. var m1;
  8405. return function rotateZ( angle ) {
  8406. if ( m1 === undefined ) m1 = new Matrix4();
  8407. m1.makeRotationZ( angle );
  8408. this.applyMatrix( m1 );
  8409. return this;
  8410. };
  8411. }(),
  8412. translate: function () {
  8413. // translate geometry
  8414. var m1;
  8415. return function translate( x, y, z ) {
  8416. if ( m1 === undefined ) m1 = new Matrix4();
  8417. m1.makeTranslation( x, y, z );
  8418. this.applyMatrix( m1 );
  8419. return this;
  8420. };
  8421. }(),
  8422. scale: function () {
  8423. // scale geometry
  8424. var m1;
  8425. return function scale( x, y, z ) {
  8426. if ( m1 === undefined ) m1 = new Matrix4();
  8427. m1.makeScale( x, y, z );
  8428. this.applyMatrix( m1 );
  8429. return this;
  8430. };
  8431. }(),
  8432. lookAt: function () {
  8433. var obj;
  8434. return function lookAt( vector ) {
  8435. if ( obj === undefined ) obj = new Object3D();
  8436. obj.lookAt( vector );
  8437. obj.updateMatrix();
  8438. this.applyMatrix( obj.matrix );
  8439. };
  8440. }(),
  8441. center: function () {
  8442. this.computeBoundingBox();
  8443. var offset = this.boundingBox.getCenter().negate();
  8444. this.translate( offset.x, offset.y, offset.z );
  8445. return offset;
  8446. },
  8447. setFromObject: function ( object ) {
  8448. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8449. var geometry = object.geometry;
  8450. if ( object.isPoints || object.isLine ) {
  8451. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8452. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8453. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8454. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8455. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8456. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8457. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8458. }
  8459. if ( geometry.boundingSphere !== null ) {
  8460. this.boundingSphere = geometry.boundingSphere.clone();
  8461. }
  8462. if ( geometry.boundingBox !== null ) {
  8463. this.boundingBox = geometry.boundingBox.clone();
  8464. }
  8465. } else if ( object.isMesh ) {
  8466. if ( geometry && geometry.isGeometry ) {
  8467. this.fromGeometry( geometry );
  8468. }
  8469. }
  8470. return this;
  8471. },
  8472. updateFromObject: function ( object ) {
  8473. var geometry = object.geometry;
  8474. if ( object.isMesh ) {
  8475. var direct = geometry.__directGeometry;
  8476. if ( geometry.elementsNeedUpdate === true ) {
  8477. direct = undefined;
  8478. geometry.elementsNeedUpdate = false;
  8479. }
  8480. if ( direct === undefined ) {
  8481. return this.fromGeometry( geometry );
  8482. }
  8483. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8484. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8485. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8486. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8487. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8488. geometry.verticesNeedUpdate = false;
  8489. geometry.normalsNeedUpdate = false;
  8490. geometry.colorsNeedUpdate = false;
  8491. geometry.uvsNeedUpdate = false;
  8492. geometry.groupsNeedUpdate = false;
  8493. geometry = direct;
  8494. }
  8495. var attribute;
  8496. if ( geometry.verticesNeedUpdate === true ) {
  8497. attribute = this.attributes.position;
  8498. if ( attribute !== undefined ) {
  8499. attribute.copyVector3sArray( geometry.vertices );
  8500. attribute.needsUpdate = true;
  8501. }
  8502. geometry.verticesNeedUpdate = false;
  8503. }
  8504. if ( geometry.normalsNeedUpdate === true ) {
  8505. attribute = this.attributes.normal;
  8506. if ( attribute !== undefined ) {
  8507. attribute.copyVector3sArray( geometry.normals );
  8508. attribute.needsUpdate = true;
  8509. }
  8510. geometry.normalsNeedUpdate = false;
  8511. }
  8512. if ( geometry.colorsNeedUpdate === true ) {
  8513. attribute = this.attributes.color;
  8514. if ( attribute !== undefined ) {
  8515. attribute.copyColorsArray( geometry.colors );
  8516. attribute.needsUpdate = true;
  8517. }
  8518. geometry.colorsNeedUpdate = false;
  8519. }
  8520. if ( geometry.uvsNeedUpdate ) {
  8521. attribute = this.attributes.uv;
  8522. if ( attribute !== undefined ) {
  8523. attribute.copyVector2sArray( geometry.uvs );
  8524. attribute.needsUpdate = true;
  8525. }
  8526. geometry.uvsNeedUpdate = false;
  8527. }
  8528. if ( geometry.lineDistancesNeedUpdate ) {
  8529. attribute = this.attributes.lineDistance;
  8530. if ( attribute !== undefined ) {
  8531. attribute.copyArray( geometry.lineDistances );
  8532. attribute.needsUpdate = true;
  8533. }
  8534. geometry.lineDistancesNeedUpdate = false;
  8535. }
  8536. if ( geometry.groupsNeedUpdate ) {
  8537. geometry.computeGroups( object.geometry );
  8538. this.groups = geometry.groups;
  8539. geometry.groupsNeedUpdate = false;
  8540. }
  8541. return this;
  8542. },
  8543. fromGeometry: function ( geometry ) {
  8544. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8545. return this.fromDirectGeometry( geometry.__directGeometry );
  8546. },
  8547. fromDirectGeometry: function ( geometry ) {
  8548. var positions = new Float32Array( geometry.vertices.length * 3 );
  8549. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8550. if ( geometry.normals.length > 0 ) {
  8551. var normals = new Float32Array( geometry.normals.length * 3 );
  8552. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8553. }
  8554. if ( geometry.colors.length > 0 ) {
  8555. var colors = new Float32Array( geometry.colors.length * 3 );
  8556. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8557. }
  8558. if ( geometry.uvs.length > 0 ) {
  8559. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8560. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8561. }
  8562. if ( geometry.uvs2.length > 0 ) {
  8563. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8564. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8565. }
  8566. if ( geometry.indices.length > 0 ) {
  8567. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8568. var indices = new TypeArray( geometry.indices.length * 3 );
  8569. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8570. }
  8571. // groups
  8572. this.groups = geometry.groups;
  8573. // morphs
  8574. for ( var name in geometry.morphTargets ) {
  8575. var array = [];
  8576. var morphTargets = geometry.morphTargets[ name ];
  8577. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8578. var morphTarget = morphTargets[ i ];
  8579. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8580. array.push( attribute.copyVector3sArray( morphTarget ) );
  8581. }
  8582. this.morphAttributes[ name ] = array;
  8583. }
  8584. // skinning
  8585. if ( geometry.skinIndices.length > 0 ) {
  8586. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8587. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8588. }
  8589. if ( geometry.skinWeights.length > 0 ) {
  8590. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8591. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8592. }
  8593. //
  8594. if ( geometry.boundingSphere !== null ) {
  8595. this.boundingSphere = geometry.boundingSphere.clone();
  8596. }
  8597. if ( geometry.boundingBox !== null ) {
  8598. this.boundingBox = geometry.boundingBox.clone();
  8599. }
  8600. return this;
  8601. },
  8602. computeBoundingBox: function () {
  8603. if ( this.boundingBox === null ) {
  8604. this.boundingBox = new Box3();
  8605. }
  8606. var position = this.attributes.position;
  8607. if ( position !== undefined ) {
  8608. this.boundingBox.setFromBufferAttribute( position );
  8609. } else {
  8610. this.boundingBox.makeEmpty();
  8611. }
  8612. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8613. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8614. }
  8615. },
  8616. computeBoundingSphere: function () {
  8617. var box = new Box3();
  8618. var vector = new Vector3();
  8619. return function computeBoundingSphere() {
  8620. if ( this.boundingSphere === null ) {
  8621. this.boundingSphere = new Sphere();
  8622. }
  8623. var position = this.attributes.position;
  8624. if ( position ) {
  8625. var center = this.boundingSphere.center;
  8626. box.setFromBufferAttribute( position );
  8627. box.getCenter( center );
  8628. // hoping to find a boundingSphere with a radius smaller than the
  8629. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8630. var maxRadiusSq = 0;
  8631. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8632. vector.x = position.getX( i );
  8633. vector.y = position.getY( i );
  8634. vector.z = position.getZ( i );
  8635. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8636. }
  8637. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8638. if ( isNaN( this.boundingSphere.radius ) ) {
  8639. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8640. }
  8641. }
  8642. };
  8643. }(),
  8644. computeFaceNormals: function () {
  8645. // backwards compatibility
  8646. },
  8647. computeVertexNormals: function () {
  8648. var index = this.index;
  8649. var attributes = this.attributes;
  8650. var groups = this.groups;
  8651. if ( attributes.position ) {
  8652. var positions = attributes.position.array;
  8653. if ( attributes.normal === undefined ) {
  8654. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8655. } else {
  8656. // reset existing normals to zero
  8657. var array = attributes.normal.array;
  8658. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8659. array[ i ] = 0;
  8660. }
  8661. }
  8662. var normals = attributes.normal.array;
  8663. var vA, vB, vC;
  8664. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8665. var cb = new Vector3(), ab = new Vector3();
  8666. // indexed elements
  8667. if ( index ) {
  8668. var indices = index.array;
  8669. if ( groups.length === 0 ) {
  8670. this.addGroup( 0, indices.length );
  8671. }
  8672. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8673. var group = groups[ j ];
  8674. var start = group.start;
  8675. var count = group.count;
  8676. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8677. vA = indices[ i + 0 ] * 3;
  8678. vB = indices[ i + 1 ] * 3;
  8679. vC = indices[ i + 2 ] * 3;
  8680. pA.fromArray( positions, vA );
  8681. pB.fromArray( positions, vB );
  8682. pC.fromArray( positions, vC );
  8683. cb.subVectors( pC, pB );
  8684. ab.subVectors( pA, pB );
  8685. cb.cross( ab );
  8686. normals[ vA ] += cb.x;
  8687. normals[ vA + 1 ] += cb.y;
  8688. normals[ vA + 2 ] += cb.z;
  8689. normals[ vB ] += cb.x;
  8690. normals[ vB + 1 ] += cb.y;
  8691. normals[ vB + 2 ] += cb.z;
  8692. normals[ vC ] += cb.x;
  8693. normals[ vC + 1 ] += cb.y;
  8694. normals[ vC + 2 ] += cb.z;
  8695. }
  8696. }
  8697. } else {
  8698. // non-indexed elements (unconnected triangle soup)
  8699. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8700. pA.fromArray( positions, i );
  8701. pB.fromArray( positions, i + 3 );
  8702. pC.fromArray( positions, i + 6 );
  8703. cb.subVectors( pC, pB );
  8704. ab.subVectors( pA, pB );
  8705. cb.cross( ab );
  8706. normals[ i ] = cb.x;
  8707. normals[ i + 1 ] = cb.y;
  8708. normals[ i + 2 ] = cb.z;
  8709. normals[ i + 3 ] = cb.x;
  8710. normals[ i + 4 ] = cb.y;
  8711. normals[ i + 5 ] = cb.z;
  8712. normals[ i + 6 ] = cb.x;
  8713. normals[ i + 7 ] = cb.y;
  8714. normals[ i + 8 ] = cb.z;
  8715. }
  8716. }
  8717. this.normalizeNormals();
  8718. attributes.normal.needsUpdate = true;
  8719. }
  8720. },
  8721. merge: function ( geometry, offset ) {
  8722. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8723. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8724. return;
  8725. }
  8726. if ( offset === undefined ) offset = 0;
  8727. var attributes = this.attributes;
  8728. for ( var key in attributes ) {
  8729. if ( geometry.attributes[ key ] === undefined ) continue;
  8730. var attribute1 = attributes[ key ];
  8731. var attributeArray1 = attribute1.array;
  8732. var attribute2 = geometry.attributes[ key ];
  8733. var attributeArray2 = attribute2.array;
  8734. var attributeSize = attribute2.itemSize;
  8735. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8736. attributeArray1[ j ] = attributeArray2[ i ];
  8737. }
  8738. }
  8739. return this;
  8740. },
  8741. normalizeNormals: function () {
  8742. var normals = this.attributes.normal;
  8743. var x, y, z, n;
  8744. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8745. x = normals.getX( i );
  8746. y = normals.getY( i );
  8747. z = normals.getZ( i );
  8748. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8749. normals.setXYZ( i, x * n, y * n, z * n );
  8750. }
  8751. },
  8752. toNonIndexed: function () {
  8753. if ( this.index === null ) {
  8754. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8755. return this;
  8756. }
  8757. var geometry2 = new BufferGeometry();
  8758. var indices = this.index.array;
  8759. var attributes = this.attributes;
  8760. for ( var name in attributes ) {
  8761. var attribute = attributes[ name ];
  8762. var array = attribute.array;
  8763. var itemSize = attribute.itemSize;
  8764. var array2 = new array.constructor( indices.length * itemSize );
  8765. var index = 0, index2 = 0;
  8766. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8767. index = indices[ i ] * itemSize;
  8768. for ( var j = 0; j < itemSize; j ++ ) {
  8769. array2[ index2 ++ ] = array[ index ++ ];
  8770. }
  8771. }
  8772. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8773. }
  8774. return geometry2;
  8775. },
  8776. toJSON: function () {
  8777. var data = {
  8778. metadata: {
  8779. version: 4.5,
  8780. type: 'BufferGeometry',
  8781. generator: 'BufferGeometry.toJSON'
  8782. }
  8783. };
  8784. // standard BufferGeometry serialization
  8785. data.uuid = this.uuid;
  8786. data.type = this.type;
  8787. if ( this.name !== '' ) data.name = this.name;
  8788. if ( this.parameters !== undefined ) {
  8789. var parameters = this.parameters;
  8790. for ( var key in parameters ) {
  8791. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8792. }
  8793. return data;
  8794. }
  8795. data.data = { attributes: {} };
  8796. var index = this.index;
  8797. if ( index !== null ) {
  8798. var array = Array.prototype.slice.call( index.array );
  8799. data.data.index = {
  8800. type: index.array.constructor.name,
  8801. array: array
  8802. };
  8803. }
  8804. var attributes = this.attributes;
  8805. for ( var key in attributes ) {
  8806. var attribute = attributes[ key ];
  8807. var array = Array.prototype.slice.call( attribute.array );
  8808. data.data.attributes[ key ] = {
  8809. itemSize: attribute.itemSize,
  8810. type: attribute.array.constructor.name,
  8811. array: array,
  8812. normalized: attribute.normalized
  8813. };
  8814. }
  8815. var groups = this.groups;
  8816. if ( groups.length > 0 ) {
  8817. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8818. }
  8819. var boundingSphere = this.boundingSphere;
  8820. if ( boundingSphere !== null ) {
  8821. data.data.boundingSphere = {
  8822. center: boundingSphere.center.toArray(),
  8823. radius: boundingSphere.radius
  8824. };
  8825. }
  8826. return data;
  8827. },
  8828. clone: function () {
  8829. /*
  8830. // Handle primitives
  8831. var parameters = this.parameters;
  8832. if ( parameters !== undefined ) {
  8833. var values = [];
  8834. for ( var key in parameters ) {
  8835. values.push( parameters[ key ] );
  8836. }
  8837. var geometry = Object.create( this.constructor.prototype );
  8838. this.constructor.apply( geometry, values );
  8839. return geometry;
  8840. }
  8841. return new this.constructor().copy( this );
  8842. */
  8843. return new BufferGeometry().copy( this );
  8844. },
  8845. copy: function ( source ) {
  8846. var name, i, l;
  8847. // reset
  8848. this.index = null;
  8849. this.attributes = {};
  8850. this.morphAttributes = {};
  8851. this.groups = [];
  8852. this.boundingBox = null;
  8853. this.boundingSphere = null;
  8854. // name
  8855. this.name = source.name;
  8856. // index
  8857. var index = source.index;
  8858. if ( index !== null ) {
  8859. this.setIndex( index.clone() );
  8860. }
  8861. // attributes
  8862. var attributes = source.attributes;
  8863. for ( name in attributes ) {
  8864. var attribute = attributes[ name ];
  8865. this.addAttribute( name, attribute.clone() );
  8866. }
  8867. // morph attributes
  8868. var morphAttributes = source.morphAttributes;
  8869. for ( name in morphAttributes ) {
  8870. var array = [];
  8871. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8872. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8873. array.push( morphAttribute[ i ].clone() );
  8874. }
  8875. this.morphAttributes[ name ] = array;
  8876. }
  8877. // groups
  8878. var groups = source.groups;
  8879. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8880. var group = groups[ i ];
  8881. this.addGroup( group.start, group.count, group.materialIndex );
  8882. }
  8883. // bounding box
  8884. var boundingBox = source.boundingBox;
  8885. if ( boundingBox !== null ) {
  8886. this.boundingBox = boundingBox.clone();
  8887. }
  8888. // bounding sphere
  8889. var boundingSphere = source.boundingSphere;
  8890. if ( boundingSphere !== null ) {
  8891. this.boundingSphere = boundingSphere.clone();
  8892. }
  8893. // draw range
  8894. this.drawRange.start = source.drawRange.start;
  8895. this.drawRange.count = source.drawRange.count;
  8896. return this;
  8897. },
  8898. dispose: function () {
  8899. this.dispatchEvent( { type: 'dispose' } );
  8900. }
  8901. } );
  8902. /**
  8903. * @author mrdoob / http://mrdoob.com/
  8904. * @author alteredq / http://alteredqualia.com/
  8905. * @author mikael emtinger / http://gomo.se/
  8906. * @author jonobr1 / http://jonobr1.com/
  8907. */
  8908. function Mesh( geometry, material ) {
  8909. Object3D.call( this );
  8910. this.type = 'Mesh';
  8911. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8912. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8913. this.drawMode = TrianglesDrawMode;
  8914. this.updateMorphTargets();
  8915. }
  8916. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8917. constructor: Mesh,
  8918. isMesh: true,
  8919. setDrawMode: function ( value ) {
  8920. this.drawMode = value;
  8921. },
  8922. copy: function ( source ) {
  8923. Object3D.prototype.copy.call( this, source );
  8924. this.drawMode = source.drawMode;
  8925. return this;
  8926. },
  8927. updateMorphTargets: function () {
  8928. var morphTargets = this.geometry.morphTargets;
  8929. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8930. this.morphTargetInfluences = [];
  8931. this.morphTargetDictionary = {};
  8932. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8933. this.morphTargetInfluences.push( 0 );
  8934. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8935. }
  8936. }
  8937. },
  8938. raycast: ( function () {
  8939. var inverseMatrix = new Matrix4();
  8940. var ray = new Ray();
  8941. var sphere = new Sphere();
  8942. var vA = new Vector3();
  8943. var vB = new Vector3();
  8944. var vC = new Vector3();
  8945. var tempA = new Vector3();
  8946. var tempB = new Vector3();
  8947. var tempC = new Vector3();
  8948. var uvA = new Vector2();
  8949. var uvB = new Vector2();
  8950. var uvC = new Vector2();
  8951. var barycoord = new Vector3();
  8952. var intersectionPoint = new Vector3();
  8953. var intersectionPointWorld = new Vector3();
  8954. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8955. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8956. uv1.multiplyScalar( barycoord.x );
  8957. uv2.multiplyScalar( barycoord.y );
  8958. uv3.multiplyScalar( barycoord.z );
  8959. uv1.add( uv2 ).add( uv3 );
  8960. return uv1.clone();
  8961. }
  8962. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8963. var intersect;
  8964. var material = object.material;
  8965. if ( material.side === BackSide ) {
  8966. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8967. } else {
  8968. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8969. }
  8970. if ( intersect === null ) return null;
  8971. intersectionPointWorld.copy( point );
  8972. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8973. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8974. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8975. return {
  8976. distance: distance,
  8977. point: intersectionPointWorld.clone(),
  8978. object: object
  8979. };
  8980. }
  8981. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  8982. vA.fromBufferAttribute( position, a );
  8983. vB.fromBufferAttribute( position, b );
  8984. vC.fromBufferAttribute( position, c );
  8985. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8986. if ( intersection ) {
  8987. if ( uv ) {
  8988. uvA.fromBufferAttribute( uv, a );
  8989. uvB.fromBufferAttribute( uv, b );
  8990. uvC.fromBufferAttribute( uv, c );
  8991. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8992. }
  8993. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8994. intersection.faceIndex = a;
  8995. }
  8996. return intersection;
  8997. }
  8998. return function raycast( raycaster, intersects ) {
  8999. var geometry = this.geometry;
  9000. var material = this.material;
  9001. var matrixWorld = this.matrixWorld;
  9002. if ( material === undefined ) return;
  9003. // Checking boundingSphere distance to ray
  9004. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9005. sphere.copy( geometry.boundingSphere );
  9006. sphere.applyMatrix4( matrixWorld );
  9007. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9008. //
  9009. inverseMatrix.getInverse( matrixWorld );
  9010. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9011. // Check boundingBox before continuing
  9012. if ( geometry.boundingBox !== null ) {
  9013. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9014. }
  9015. var intersection;
  9016. if ( geometry.isBufferGeometry ) {
  9017. var a, b, c;
  9018. var index = geometry.index;
  9019. var position = geometry.attributes.position;
  9020. var uv = geometry.attributes.uv;
  9021. var i, l;
  9022. if ( index !== null ) {
  9023. // indexed buffer geometry
  9024. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9025. a = index.getX( i );
  9026. b = index.getX( i + 1 );
  9027. c = index.getX( i + 2 );
  9028. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9029. if ( intersection ) {
  9030. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9031. intersects.push( intersection );
  9032. }
  9033. }
  9034. } else {
  9035. // non-indexed buffer geometry
  9036. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9037. a = i;
  9038. b = i + 1;
  9039. c = i + 2;
  9040. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9041. if ( intersection ) {
  9042. intersection.index = a; // triangle number in positions buffer semantics
  9043. intersects.push( intersection );
  9044. }
  9045. }
  9046. }
  9047. } else if ( geometry.isGeometry ) {
  9048. var fvA, fvB, fvC;
  9049. var isMultiMaterial = Array.isArray( material );
  9050. var vertices = geometry.vertices;
  9051. var faces = geometry.faces;
  9052. var uvs;
  9053. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9054. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9055. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9056. var face = faces[ f ];
  9057. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9058. if ( faceMaterial === undefined ) continue;
  9059. fvA = vertices[ face.a ];
  9060. fvB = vertices[ face.b ];
  9061. fvC = vertices[ face.c ];
  9062. if ( faceMaterial.morphTargets === true ) {
  9063. var morphTargets = geometry.morphTargets;
  9064. var morphInfluences = this.morphTargetInfluences;
  9065. vA.set( 0, 0, 0 );
  9066. vB.set( 0, 0, 0 );
  9067. vC.set( 0, 0, 0 );
  9068. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9069. var influence = morphInfluences[ t ];
  9070. if ( influence === 0 ) continue;
  9071. var targets = morphTargets[ t ].vertices;
  9072. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9073. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9074. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9075. }
  9076. vA.add( fvA );
  9077. vB.add( fvB );
  9078. vC.add( fvC );
  9079. fvA = vA;
  9080. fvB = vB;
  9081. fvC = vC;
  9082. }
  9083. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9084. if ( intersection ) {
  9085. if ( uvs && uvs[ f ] ) {
  9086. var uvs_f = uvs[ f ];
  9087. uvA.copy( uvs_f[ 0 ] );
  9088. uvB.copy( uvs_f[ 1 ] );
  9089. uvC.copy( uvs_f[ 2 ] );
  9090. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9091. }
  9092. intersection.face = face;
  9093. intersection.faceIndex = f;
  9094. intersects.push( intersection );
  9095. }
  9096. }
  9097. }
  9098. };
  9099. }() ),
  9100. clone: function () {
  9101. return new this.constructor( this.geometry, this.material ).copy( this );
  9102. }
  9103. } );
  9104. /**
  9105. * @author mrdoob / http://mrdoob.com/
  9106. * @author Mugen87 / https://github.com/Mugen87
  9107. */
  9108. // BoxGeometry
  9109. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9110. Geometry.call( this );
  9111. this.type = 'BoxGeometry';
  9112. this.parameters = {
  9113. width: width,
  9114. height: height,
  9115. depth: depth,
  9116. widthSegments: widthSegments,
  9117. heightSegments: heightSegments,
  9118. depthSegments: depthSegments
  9119. };
  9120. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  9121. this.mergeVertices();
  9122. }
  9123. BoxGeometry.prototype = Object.create( Geometry.prototype );
  9124. BoxGeometry.prototype.constructor = BoxGeometry;
  9125. // BoxBufferGeometry
  9126. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9127. BufferGeometry.call( this );
  9128. this.type = 'BoxBufferGeometry';
  9129. this.parameters = {
  9130. width: width,
  9131. height: height,
  9132. depth: depth,
  9133. widthSegments: widthSegments,
  9134. heightSegments: heightSegments,
  9135. depthSegments: depthSegments
  9136. };
  9137. var scope = this;
  9138. // segments
  9139. widthSegments = Math.floor( widthSegments ) || 1;
  9140. heightSegments = Math.floor( heightSegments ) || 1;
  9141. depthSegments = Math.floor( depthSegments ) || 1;
  9142. // buffers
  9143. var indices = [];
  9144. var vertices = [];
  9145. var normals = [];
  9146. var uvs = [];
  9147. // helper variables
  9148. var numberOfVertices = 0;
  9149. var groupStart = 0;
  9150. // build each side of the box geometry
  9151. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9152. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9153. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9154. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9155. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9156. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9157. // build geometry
  9158. this.setIndex( indices );
  9159. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9160. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9161. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9162. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9163. var segmentWidth = width / gridX;
  9164. var segmentHeight = height / gridY;
  9165. var widthHalf = width / 2;
  9166. var heightHalf = height / 2;
  9167. var depthHalf = depth / 2;
  9168. var gridX1 = gridX + 1;
  9169. var gridY1 = gridY + 1;
  9170. var vertexCounter = 0;
  9171. var groupCount = 0;
  9172. var ix, iy;
  9173. var vector = new Vector3();
  9174. // generate vertices, normals and uvs
  9175. for ( iy = 0; iy < gridY1; iy ++ ) {
  9176. var y = iy * segmentHeight - heightHalf;
  9177. for ( ix = 0; ix < gridX1; ix ++ ) {
  9178. var x = ix * segmentWidth - widthHalf;
  9179. // set values to correct vector component
  9180. vector[ u ] = x * udir;
  9181. vector[ v ] = y * vdir;
  9182. vector[ w ] = depthHalf;
  9183. // now apply vector to vertex buffer
  9184. vertices.push( vector.x, vector.y, vector.z );
  9185. // set values to correct vector component
  9186. vector[ u ] = 0;
  9187. vector[ v ] = 0;
  9188. vector[ w ] = depth > 0 ? 1 : - 1;
  9189. // now apply vector to normal buffer
  9190. normals.push( vector.x, vector.y, vector.z );
  9191. // uvs
  9192. uvs.push( ix / gridX );
  9193. uvs.push( 1 - ( iy / gridY ) );
  9194. // counters
  9195. vertexCounter += 1;
  9196. }
  9197. }
  9198. // indices
  9199. // 1. you need three indices to draw a single face
  9200. // 2. a single segment consists of two faces
  9201. // 3. so we need to generate six (2*3) indices per segment
  9202. for ( iy = 0; iy < gridY; iy ++ ) {
  9203. for ( ix = 0; ix < gridX; ix ++ ) {
  9204. var a = numberOfVertices + ix + gridX1 * iy;
  9205. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9206. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9207. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9208. // faces
  9209. indices.push( a, b, d );
  9210. indices.push( b, c, d );
  9211. // increase counter
  9212. groupCount += 6;
  9213. }
  9214. }
  9215. // add a group to the geometry. this will ensure multi material support
  9216. scope.addGroup( groupStart, groupCount, materialIndex );
  9217. // calculate new start value for groups
  9218. groupStart += groupCount;
  9219. // update total number of vertices
  9220. numberOfVertices += vertexCounter;
  9221. }
  9222. }
  9223. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9224. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9225. /**
  9226. * @author mrdoob / http://mrdoob.com/
  9227. * @author Mugen87 / https://github.com/Mugen87
  9228. */
  9229. // PlaneGeometry
  9230. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  9231. Geometry.call( this );
  9232. this.type = 'PlaneGeometry';
  9233. this.parameters = {
  9234. width: width,
  9235. height: height,
  9236. widthSegments: widthSegments,
  9237. heightSegments: heightSegments
  9238. };
  9239. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  9240. this.mergeVertices();
  9241. }
  9242. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  9243. PlaneGeometry.prototype.constructor = PlaneGeometry;
  9244. // PlaneBufferGeometry
  9245. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9246. BufferGeometry.call( this );
  9247. this.type = 'PlaneBufferGeometry';
  9248. this.parameters = {
  9249. width: width,
  9250. height: height,
  9251. widthSegments: widthSegments,
  9252. heightSegments: heightSegments
  9253. };
  9254. var width_half = width / 2;
  9255. var height_half = height / 2;
  9256. var gridX = Math.floor( widthSegments ) || 1;
  9257. var gridY = Math.floor( heightSegments ) || 1;
  9258. var gridX1 = gridX + 1;
  9259. var gridY1 = gridY + 1;
  9260. var segment_width = width / gridX;
  9261. var segment_height = height / gridY;
  9262. var ix, iy;
  9263. // buffers
  9264. var indices = [];
  9265. var vertices = [];
  9266. var normals = [];
  9267. var uvs = [];
  9268. // generate vertices, normals and uvs
  9269. for ( iy = 0; iy < gridY1; iy ++ ) {
  9270. var y = iy * segment_height - height_half;
  9271. for ( ix = 0; ix < gridX1; ix ++ ) {
  9272. var x = ix * segment_width - width_half;
  9273. vertices.push( x, - y, 0 );
  9274. normals.push( 0, 0, 1 );
  9275. uvs.push( ix / gridX );
  9276. uvs.push( 1 - ( iy / gridY ) );
  9277. }
  9278. }
  9279. // indices
  9280. for ( iy = 0; iy < gridY; iy ++ ) {
  9281. for ( ix = 0; ix < gridX; ix ++ ) {
  9282. var a = ix + gridX1 * iy;
  9283. var b = ix + gridX1 * ( iy + 1 );
  9284. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9285. var d = ( ix + 1 ) + gridX1 * iy;
  9286. // faces
  9287. indices.push( a, b, d );
  9288. indices.push( b, c, d );
  9289. }
  9290. }
  9291. // build geometry
  9292. this.setIndex( indices );
  9293. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9294. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9295. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9296. }
  9297. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9298. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9299. /**
  9300. * @author mrdoob / http://mrdoob.com/
  9301. * @author mikael emtinger / http://gomo.se/
  9302. * @author WestLangley / http://github.com/WestLangley
  9303. */
  9304. function Camera() {
  9305. Object3D.call( this );
  9306. this.type = 'Camera';
  9307. this.matrixWorldInverse = new Matrix4();
  9308. this.projectionMatrix = new Matrix4();
  9309. }
  9310. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9311. constructor: Camera,
  9312. isCamera: true,
  9313. copy: function ( source ) {
  9314. Object3D.prototype.copy.call( this, source );
  9315. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9316. this.projectionMatrix.copy( source.projectionMatrix );
  9317. return this;
  9318. },
  9319. getWorldDirection: function () {
  9320. var quaternion = new Quaternion();
  9321. return function getWorldDirection( optionalTarget ) {
  9322. var result = optionalTarget || new Vector3();
  9323. this.getWorldQuaternion( quaternion );
  9324. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9325. };
  9326. }(),
  9327. clone: function () {
  9328. return new this.constructor().copy( this );
  9329. }
  9330. } );
  9331. /**
  9332. * @author mrdoob / http://mrdoob.com/
  9333. * @author greggman / http://games.greggman.com/
  9334. * @author zz85 / http://www.lab4games.net/zz85/blog
  9335. * @author tschw
  9336. */
  9337. function PerspectiveCamera( fov, aspect, near, far ) {
  9338. Camera.call( this );
  9339. this.type = 'PerspectiveCamera';
  9340. this.fov = fov !== undefined ? fov : 50;
  9341. this.zoom = 1;
  9342. this.near = near !== undefined ? near : 0.1;
  9343. this.far = far !== undefined ? far : 2000;
  9344. this.focus = 10;
  9345. this.aspect = aspect !== undefined ? aspect : 1;
  9346. this.view = null;
  9347. this.filmGauge = 35; // width of the film (default in millimeters)
  9348. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9349. this.updateProjectionMatrix();
  9350. }
  9351. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9352. constructor: PerspectiveCamera,
  9353. isPerspectiveCamera: true,
  9354. copy: function ( source ) {
  9355. Camera.prototype.copy.call( this, source );
  9356. this.fov = source.fov;
  9357. this.zoom = source.zoom;
  9358. this.near = source.near;
  9359. this.far = source.far;
  9360. this.focus = source.focus;
  9361. this.aspect = source.aspect;
  9362. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9363. this.filmGauge = source.filmGauge;
  9364. this.filmOffset = source.filmOffset;
  9365. return this;
  9366. },
  9367. /**
  9368. * Sets the FOV by focal length in respect to the current .filmGauge.
  9369. *
  9370. * The default film gauge is 35, so that the focal length can be specified for
  9371. * a 35mm (full frame) camera.
  9372. *
  9373. * Values for focal length and film gauge must have the same unit.
  9374. */
  9375. setFocalLength: function ( focalLength ) {
  9376. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9377. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9378. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9379. this.updateProjectionMatrix();
  9380. },
  9381. /**
  9382. * Calculates the focal length from the current .fov and .filmGauge.
  9383. */
  9384. getFocalLength: function () {
  9385. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9386. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9387. },
  9388. getEffectiveFOV: function () {
  9389. return _Math.RAD2DEG * 2 * Math.atan(
  9390. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9391. },
  9392. getFilmWidth: function () {
  9393. // film not completely covered in portrait format (aspect < 1)
  9394. return this.filmGauge * Math.min( this.aspect, 1 );
  9395. },
  9396. getFilmHeight: function () {
  9397. // film not completely covered in landscape format (aspect > 1)
  9398. return this.filmGauge / Math.max( this.aspect, 1 );
  9399. },
  9400. /**
  9401. * Sets an offset in a larger frustum. This is useful for multi-window or
  9402. * multi-monitor/multi-machine setups.
  9403. *
  9404. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9405. * the monitors are in grid like this
  9406. *
  9407. * +---+---+---+
  9408. * | A | B | C |
  9409. * +---+---+---+
  9410. * | D | E | F |
  9411. * +---+---+---+
  9412. *
  9413. * then for each monitor you would call it like this
  9414. *
  9415. * var w = 1920;
  9416. * var h = 1080;
  9417. * var fullWidth = w * 3;
  9418. * var fullHeight = h * 2;
  9419. *
  9420. * --A--
  9421. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9422. * --B--
  9423. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9424. * --C--
  9425. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9426. * --D--
  9427. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9428. * --E--
  9429. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9430. * --F--
  9431. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9432. *
  9433. * Note there is no reason monitors have to be the same size or in a grid.
  9434. */
  9435. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9436. this.aspect = fullWidth / fullHeight;
  9437. this.view = {
  9438. fullWidth: fullWidth,
  9439. fullHeight: fullHeight,
  9440. offsetX: x,
  9441. offsetY: y,
  9442. width: width,
  9443. height: height
  9444. };
  9445. this.updateProjectionMatrix();
  9446. },
  9447. clearViewOffset: function () {
  9448. this.view = null;
  9449. this.updateProjectionMatrix();
  9450. },
  9451. updateProjectionMatrix: function () {
  9452. var near = this.near,
  9453. top = near * Math.tan(
  9454. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9455. height = 2 * top,
  9456. width = this.aspect * height,
  9457. left = - 0.5 * width,
  9458. view = this.view;
  9459. if ( view !== null ) {
  9460. var fullWidth = view.fullWidth,
  9461. fullHeight = view.fullHeight;
  9462. left += view.offsetX * width / fullWidth;
  9463. top -= view.offsetY * height / fullHeight;
  9464. width *= view.width / fullWidth;
  9465. height *= view.height / fullHeight;
  9466. }
  9467. var skew = this.filmOffset;
  9468. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9469. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  9470. },
  9471. toJSON: function ( meta ) {
  9472. var data = Object3D.prototype.toJSON.call( this, meta );
  9473. data.object.fov = this.fov;
  9474. data.object.zoom = this.zoom;
  9475. data.object.near = this.near;
  9476. data.object.far = this.far;
  9477. data.object.focus = this.focus;
  9478. data.object.aspect = this.aspect;
  9479. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9480. data.object.filmGauge = this.filmGauge;
  9481. data.object.filmOffset = this.filmOffset;
  9482. return data;
  9483. }
  9484. } );
  9485. /**
  9486. * @author alteredq / http://alteredqualia.com/
  9487. * @author arose / http://github.com/arose
  9488. */
  9489. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9490. Camera.call( this );
  9491. this.type = 'OrthographicCamera';
  9492. this.zoom = 1;
  9493. this.view = null;
  9494. this.left = left;
  9495. this.right = right;
  9496. this.top = top;
  9497. this.bottom = bottom;
  9498. this.near = ( near !== undefined ) ? near : 0.1;
  9499. this.far = ( far !== undefined ) ? far : 2000;
  9500. this.updateProjectionMatrix();
  9501. }
  9502. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9503. constructor: OrthographicCamera,
  9504. isOrthographicCamera: true,
  9505. copy: function ( source ) {
  9506. Camera.prototype.copy.call( this, source );
  9507. this.left = source.left;
  9508. this.right = source.right;
  9509. this.top = source.top;
  9510. this.bottom = source.bottom;
  9511. this.near = source.near;
  9512. this.far = source.far;
  9513. this.zoom = source.zoom;
  9514. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9515. return this;
  9516. },
  9517. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9518. this.view = {
  9519. fullWidth: fullWidth,
  9520. fullHeight: fullHeight,
  9521. offsetX: x,
  9522. offsetY: y,
  9523. width: width,
  9524. height: height
  9525. };
  9526. this.updateProjectionMatrix();
  9527. },
  9528. clearViewOffset: function() {
  9529. this.view = null;
  9530. this.updateProjectionMatrix();
  9531. },
  9532. updateProjectionMatrix: function () {
  9533. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9534. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9535. var cx = ( this.right + this.left ) / 2;
  9536. var cy = ( this.top + this.bottom ) / 2;
  9537. var left = cx - dx;
  9538. var right = cx + dx;
  9539. var top = cy + dy;
  9540. var bottom = cy - dy;
  9541. if ( this.view !== null ) {
  9542. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9543. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9544. var scaleW = ( this.right - this.left ) / this.view.width;
  9545. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9546. left += scaleW * ( this.view.offsetX / zoomW );
  9547. right = left + scaleW * ( this.view.width / zoomW );
  9548. top -= scaleH * ( this.view.offsetY / zoomH );
  9549. bottom = top - scaleH * ( this.view.height / zoomH );
  9550. }
  9551. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9552. },
  9553. toJSON: function ( meta ) {
  9554. var data = Object3D.prototype.toJSON.call( this, meta );
  9555. data.object.zoom = this.zoom;
  9556. data.object.left = this.left;
  9557. data.object.right = this.right;
  9558. data.object.top = this.top;
  9559. data.object.bottom = this.bottom;
  9560. data.object.near = this.near;
  9561. data.object.far = this.far;
  9562. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9563. return data;
  9564. }
  9565. } );
  9566. /**
  9567. * @author mrdoob / http://mrdoob.com/
  9568. */
  9569. function WebGLAttributes( gl ) {
  9570. var buffers = {};
  9571. function createBuffer( attribute, bufferType ) {
  9572. var array = attribute.array;
  9573. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  9574. var buffer = gl.createBuffer();
  9575. gl.bindBuffer( bufferType, buffer );
  9576. gl.bufferData( bufferType, array, usage );
  9577. attribute.onUploadCallback();
  9578. var type = gl.FLOAT;
  9579. if ( array instanceof Float32Array ) {
  9580. type = gl.FLOAT;
  9581. } else if ( array instanceof Float64Array ) {
  9582. console.warn( "Unsupported data buffer format: Float64Array" );
  9583. } else if ( array instanceof Uint16Array ) {
  9584. type = gl.UNSIGNED_SHORT;
  9585. } else if ( array instanceof Int16Array ) {
  9586. type = gl.SHORT;
  9587. } else if ( array instanceof Uint32Array ) {
  9588. type = gl.UNSIGNED_INT;
  9589. } else if ( array instanceof Int32Array ) {
  9590. type = gl.INT;
  9591. } else if ( array instanceof Int8Array ) {
  9592. type = gl.BYTE;
  9593. } else if ( array instanceof Uint8Array ) {
  9594. type = gl.UNSIGNED_BYTE;
  9595. }
  9596. return {
  9597. buffer: buffer,
  9598. type: type,
  9599. bytesPerElement: array.BYTES_PER_ELEMENT,
  9600. version: attribute.version
  9601. };
  9602. }
  9603. function updateBuffer( buffer, attribute, bufferType ) {
  9604. var array = attribute.array;
  9605. var updateRange = attribute.updateRange;
  9606. gl.bindBuffer( bufferType, buffer );
  9607. if ( attribute.dynamic === false ) {
  9608. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  9609. } else if ( updateRange.count === - 1 ) {
  9610. // Not using update ranges
  9611. gl.bufferSubData( bufferType, 0, array );
  9612. } else if ( updateRange.count === 0 ) {
  9613. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  9614. } else {
  9615. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  9616. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  9617. updateRange.count = 0; // reset range
  9618. }
  9619. }
  9620. //
  9621. function get( attribute ) {
  9622. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9623. return buffers[ attribute.uuid ];
  9624. }
  9625. function remove( attribute ) {
  9626. var data = buffers[ attribute.uuid ];
  9627. if ( data ) {
  9628. gl.deleteBuffer( data.buffer );
  9629. delete buffers[ attribute.uuid ];
  9630. }
  9631. }
  9632. function update( attribute, bufferType ) {
  9633. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9634. var data = buffers[ attribute.uuid ];
  9635. if ( data === undefined ) {
  9636. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  9637. } else if ( data.version < attribute.version ) {
  9638. updateBuffer( data.buffer, attribute, bufferType );
  9639. data.version = attribute.version;
  9640. }
  9641. }
  9642. return {
  9643. get: get,
  9644. remove: remove,
  9645. update: update
  9646. };
  9647. }
  9648. /**
  9649. * @author mrdoob / http://mrdoob.com/
  9650. */
  9651. function painterSortStable( a, b ) {
  9652. if ( a.renderOrder !== b.renderOrder ) {
  9653. return a.renderOrder - b.renderOrder;
  9654. } else if ( a.program && b.program && a.program !== b.program ) {
  9655. return a.program.id - b.program.id;
  9656. } else if ( a.material.id !== b.material.id ) {
  9657. return a.material.id - b.material.id;
  9658. } else if ( a.z !== b.z ) {
  9659. return a.z - b.z;
  9660. } else {
  9661. return a.id - b.id;
  9662. }
  9663. }
  9664. function reversePainterSortStable( a, b ) {
  9665. if ( a.renderOrder !== b.renderOrder ) {
  9666. return a.renderOrder - b.renderOrder;
  9667. } if ( a.z !== b.z ) {
  9668. return b.z - a.z;
  9669. } else {
  9670. return a.id - b.id;
  9671. }
  9672. }
  9673. function WebGLRenderList() {
  9674. var opaque = [];
  9675. var opaqueLastIndex = - 1;
  9676. var transparent = [];
  9677. var transparentLastIndex = - 1;
  9678. function init() {
  9679. opaqueLastIndex = - 1;
  9680. transparentLastIndex = - 1;
  9681. }
  9682. function push( object, geometry, material, z, group ) {
  9683. var array, index;
  9684. // allocate the next position in the appropriate array
  9685. if ( material.transparent ) {
  9686. array = transparent;
  9687. index = ++ transparentLastIndex;
  9688. } else {
  9689. array = opaque;
  9690. index = ++ opaqueLastIndex;
  9691. }
  9692. // recycle existing render item or grow the array
  9693. var renderItem = array[ index ];
  9694. if ( renderItem ) {
  9695. renderItem.id = object.id;
  9696. renderItem.object = object;
  9697. renderItem.geometry = geometry;
  9698. renderItem.material = material;
  9699. renderItem.program = material.program;
  9700. renderItem.renderOrder = object.renderOrder;
  9701. renderItem.z = z;
  9702. renderItem.group = group;
  9703. } else {
  9704. renderItem = {
  9705. id: object.id,
  9706. object: object,
  9707. geometry: geometry,
  9708. material: material,
  9709. program: material.program,
  9710. renderOrder: object.renderOrder,
  9711. z: z,
  9712. group: group
  9713. };
  9714. // assert( index === array.length );
  9715. array.push( renderItem );
  9716. }
  9717. }
  9718. function finish() {
  9719. opaque.length = opaqueLastIndex + 1;
  9720. transparent.length = transparentLastIndex + 1;
  9721. }
  9722. function sort() {
  9723. opaque.sort( painterSortStable );
  9724. transparent.sort( reversePainterSortStable );
  9725. }
  9726. return {
  9727. opaque: opaque,
  9728. transparent: transparent,
  9729. init: init,
  9730. push: push,
  9731. finish: finish,
  9732. sort: sort
  9733. };
  9734. }
  9735. function WebGLRenderLists() {
  9736. var lists = {};
  9737. function get( scene, camera ) {
  9738. var hash = scene.id + ',' + camera.id;
  9739. var list = lists[ hash ];
  9740. if ( list === undefined ) {
  9741. // console.log( 'THREE.WebGLRenderLists:', hash );
  9742. list = new WebGLRenderList();
  9743. lists[ hash ] = list;
  9744. }
  9745. return list;
  9746. }
  9747. function dispose() {
  9748. lists = {};
  9749. }
  9750. return {
  9751. get: get,
  9752. dispose: dispose
  9753. };
  9754. }
  9755. /**
  9756. * @author mrdoob / http://mrdoob.com/
  9757. */
  9758. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9759. var mode;
  9760. function setMode( value ) {
  9761. mode = value;
  9762. }
  9763. var type, size;
  9764. function setIndex( index ) {
  9765. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9766. type = gl.UNSIGNED_INT;
  9767. size = 4;
  9768. } else if ( index.array instanceof Uint16Array ) {
  9769. type = gl.UNSIGNED_SHORT;
  9770. size = 2;
  9771. } else {
  9772. type = gl.UNSIGNED_BYTE;
  9773. size = 1;
  9774. }
  9775. }
  9776. function render( start, count ) {
  9777. gl.drawElements( mode, count, type, start * size );
  9778. infoRender.calls ++;
  9779. infoRender.vertices += count;
  9780. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9781. }
  9782. function renderInstances( geometry, start, count ) {
  9783. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9784. if ( extension === null ) {
  9785. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9786. return;
  9787. }
  9788. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9789. infoRender.calls ++;
  9790. infoRender.vertices += count * geometry.maxInstancedCount;
  9791. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9792. }
  9793. //
  9794. this.setMode = setMode;
  9795. this.setIndex = setIndex;
  9796. this.render = render;
  9797. this.renderInstances = renderInstances;
  9798. }
  9799. /**
  9800. * @author mrdoob / http://mrdoob.com/
  9801. */
  9802. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9803. var mode;
  9804. function setMode( value ) {
  9805. mode = value;
  9806. }
  9807. function render( start, count ) {
  9808. gl.drawArrays( mode, start, count );
  9809. infoRender.calls ++;
  9810. infoRender.vertices += count;
  9811. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9812. }
  9813. function renderInstances( geometry, start, count ) {
  9814. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9815. if ( extension === null ) {
  9816. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9817. return;
  9818. }
  9819. var position = geometry.attributes.position;
  9820. if ( position.isInterleavedBufferAttribute ) {
  9821. count = position.data.count;
  9822. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9823. } else {
  9824. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  9825. }
  9826. infoRender.calls ++;
  9827. infoRender.vertices += count * geometry.maxInstancedCount;
  9828. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9829. }
  9830. //
  9831. this.setMode = setMode;
  9832. this.render = render;
  9833. this.renderInstances = renderInstances;
  9834. }
  9835. /**
  9836. * @author mrdoob / http://mrdoob.com/
  9837. */
  9838. function WebGLGeometries( gl, attributes, infoMemory ) {
  9839. var geometries = {};
  9840. var wireframeAttributes = {};
  9841. function onGeometryDispose( event ) {
  9842. var geometry = event.target;
  9843. var buffergeometry = geometries[ geometry.id ];
  9844. if ( buffergeometry.index !== null ) {
  9845. attributes.remove( buffergeometry.index );
  9846. }
  9847. for ( var name in buffergeometry.attributes ) {
  9848. attributes.remove( buffergeometry.attributes[ name ] );
  9849. }
  9850. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9851. delete geometries[ geometry.id ];
  9852. // TODO Remove duplicate code
  9853. var attribute = wireframeAttributes[ geometry.id ];
  9854. if ( attribute ) {
  9855. attributes.remove( attribute );
  9856. delete wireframeAttributes[ geometry.id ];
  9857. }
  9858. attribute = wireframeAttributes[ buffergeometry.id ];
  9859. if ( attribute ) {
  9860. attributes.remove( attribute );
  9861. delete wireframeAttributes[ buffergeometry.id ];
  9862. }
  9863. //
  9864. infoMemory.geometries --;
  9865. }
  9866. function get( object, geometry ) {
  9867. var buffergeometry = geometries[ geometry.id ];
  9868. if ( buffergeometry ) return buffergeometry;
  9869. geometry.addEventListener( 'dispose', onGeometryDispose );
  9870. if ( geometry.isBufferGeometry ) {
  9871. buffergeometry = geometry;
  9872. } else if ( geometry.isGeometry ) {
  9873. if ( geometry._bufferGeometry === undefined ) {
  9874. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9875. }
  9876. buffergeometry = geometry._bufferGeometry;
  9877. }
  9878. geometries[ geometry.id ] = buffergeometry;
  9879. infoMemory.geometries ++;
  9880. return buffergeometry;
  9881. }
  9882. function update( geometry ) {
  9883. var index = geometry.index;
  9884. var geometryAttributes = geometry.attributes;
  9885. if ( index !== null ) {
  9886. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9887. }
  9888. for ( var name in geometryAttributes ) {
  9889. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9890. }
  9891. // morph targets
  9892. var morphAttributes = geometry.morphAttributes;
  9893. for ( var name in morphAttributes ) {
  9894. var array = morphAttributes[ name ];
  9895. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9896. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9897. }
  9898. }
  9899. }
  9900. function getWireframeAttribute( geometry ) {
  9901. var attribute = wireframeAttributes[ geometry.id ];
  9902. if ( attribute ) return attribute;
  9903. var indices = [];
  9904. var geometryIndex = geometry.index;
  9905. var geometryAttributes = geometry.attributes;
  9906. // console.time( 'wireframe' );
  9907. if ( geometryIndex !== null ) {
  9908. var array = geometryIndex.array;
  9909. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9910. var a = array[ i + 0 ];
  9911. var b = array[ i + 1 ];
  9912. var c = array[ i + 2 ];
  9913. indices.push( a, b, b, c, c, a );
  9914. }
  9915. } else {
  9916. var array = geometryAttributes.position.array;
  9917. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9918. var a = i + 0;
  9919. var b = i + 1;
  9920. var c = i + 2;
  9921. indices.push( a, b, b, c, c, a );
  9922. }
  9923. }
  9924. // console.timeEnd( 'wireframe' );
  9925. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9926. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  9927. wireframeAttributes[ geometry.id ] = attribute;
  9928. return attribute;
  9929. }
  9930. return {
  9931. get: get,
  9932. update: update,
  9933. getWireframeAttribute: getWireframeAttribute
  9934. };
  9935. }
  9936. /**
  9937. * @author mrdoob / http://mrdoob.com/
  9938. */
  9939. function WebGLLights() {
  9940. var lights = {};
  9941. return {
  9942. get: function ( light ) {
  9943. if ( lights[ light.id ] !== undefined ) {
  9944. return lights[ light.id ];
  9945. }
  9946. var uniforms;
  9947. switch ( light.type ) {
  9948. case 'DirectionalLight':
  9949. uniforms = {
  9950. direction: new Vector3(),
  9951. color: new Color(),
  9952. shadow: false,
  9953. shadowBias: 0,
  9954. shadowRadius: 1,
  9955. shadowMapSize: new Vector2()
  9956. };
  9957. break;
  9958. case 'SpotLight':
  9959. uniforms = {
  9960. position: new Vector3(),
  9961. direction: new Vector3(),
  9962. color: new Color(),
  9963. distance: 0,
  9964. coneCos: 0,
  9965. penumbraCos: 0,
  9966. decay: 0,
  9967. shadow: false,
  9968. shadowBias: 0,
  9969. shadowRadius: 1,
  9970. shadowMapSize: new Vector2()
  9971. };
  9972. break;
  9973. case 'PointLight':
  9974. uniforms = {
  9975. position: new Vector3(),
  9976. color: new Color(),
  9977. distance: 0,
  9978. decay: 0,
  9979. shadow: false,
  9980. shadowBias: 0,
  9981. shadowRadius: 1,
  9982. shadowMapSize: new Vector2()
  9983. };
  9984. break;
  9985. case 'HemisphereLight':
  9986. uniforms = {
  9987. direction: new Vector3(),
  9988. skyColor: new Color(),
  9989. groundColor: new Color()
  9990. };
  9991. break;
  9992. case 'RectAreaLight':
  9993. uniforms = {
  9994. color: new Color(),
  9995. position: new Vector3(),
  9996. halfWidth: new Vector3(),
  9997. halfHeight: new Vector3()
  9998. // TODO (abelnation): set RectAreaLight shadow uniforms
  9999. };
  10000. break;
  10001. }
  10002. lights[ light.id ] = uniforms;
  10003. return uniforms;
  10004. }
  10005. };
  10006. }
  10007. /**
  10008. * @author mrdoob / http://mrdoob.com/
  10009. */
  10010. function WebGLObjects( gl, geometries, infoRender ) {
  10011. var updateList = {};
  10012. function update( object ) {
  10013. var frame = infoRender.frame;
  10014. var geometry = object.geometry;
  10015. var buffergeometry = geometries.get( object, geometry );
  10016. // Update once per frame
  10017. if ( updateList[ buffergeometry.id ] !== frame ) {
  10018. if ( geometry.isGeometry ) {
  10019. buffergeometry.updateFromObject( object );
  10020. }
  10021. geometries.update( buffergeometry );
  10022. updateList[ buffergeometry.id ] = frame;
  10023. }
  10024. return buffergeometry;
  10025. }
  10026. function clear() {
  10027. updateList = {};
  10028. }
  10029. return {
  10030. update: update,
  10031. clear: clear
  10032. };
  10033. }
  10034. /**
  10035. * @author mrdoob / http://mrdoob.com/
  10036. */
  10037. function addLineNumbers( string ) {
  10038. var lines = string.split( '\n' );
  10039. for ( var i = 0; i < lines.length; i ++ ) {
  10040. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10041. }
  10042. return lines.join( '\n' );
  10043. }
  10044. function WebGLShader( gl, type, string ) {
  10045. var shader = gl.createShader( type );
  10046. gl.shaderSource( shader, string );
  10047. gl.compileShader( shader );
  10048. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10049. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10050. }
  10051. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10052. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10053. }
  10054. // --enable-privileged-webgl-extension
  10055. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10056. return shader;
  10057. }
  10058. /**
  10059. * @author mrdoob / http://mrdoob.com/
  10060. */
  10061. var programIdCount = 0;
  10062. function getEncodingComponents( encoding ) {
  10063. switch ( encoding ) {
  10064. case LinearEncoding:
  10065. return [ 'Linear','( value )' ];
  10066. case sRGBEncoding:
  10067. return [ 'sRGB','( value )' ];
  10068. case RGBEEncoding:
  10069. return [ 'RGBE','( value )' ];
  10070. case RGBM7Encoding:
  10071. return [ 'RGBM','( value, 7.0 )' ];
  10072. case RGBM16Encoding:
  10073. return [ 'RGBM','( value, 16.0 )' ];
  10074. case RGBDEncoding:
  10075. return [ 'RGBD','( value, 256.0 )' ];
  10076. case GammaEncoding:
  10077. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10078. default:
  10079. throw new Error( 'unsupported encoding: ' + encoding );
  10080. }
  10081. }
  10082. function getTexelDecodingFunction( functionName, encoding ) {
  10083. var components = getEncodingComponents( encoding );
  10084. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10085. }
  10086. function getTexelEncodingFunction( functionName, encoding ) {
  10087. var components = getEncodingComponents( encoding );
  10088. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10089. }
  10090. function getToneMappingFunction( functionName, toneMapping ) {
  10091. var toneMappingName;
  10092. switch ( toneMapping ) {
  10093. case LinearToneMapping:
  10094. toneMappingName = "Linear";
  10095. break;
  10096. case ReinhardToneMapping:
  10097. toneMappingName = "Reinhard";
  10098. break;
  10099. case Uncharted2ToneMapping:
  10100. toneMappingName = "Uncharted2";
  10101. break;
  10102. case CineonToneMapping:
  10103. toneMappingName = "OptimizedCineon";
  10104. break;
  10105. default:
  10106. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10107. }
  10108. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10109. }
  10110. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10111. extensions = extensions || {};
  10112. var chunks = [
  10113. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10114. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10115. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10116. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10117. ];
  10118. return chunks.filter( filterEmptyLine ).join( '\n' );
  10119. }
  10120. function generateDefines( defines ) {
  10121. var chunks = [];
  10122. for ( var name in defines ) {
  10123. var value = defines[ name ];
  10124. if ( value === false ) continue;
  10125. chunks.push( '#define ' + name + ' ' + value );
  10126. }
  10127. return chunks.join( '\n' );
  10128. }
  10129. function fetchAttributeLocations( gl, program, identifiers ) {
  10130. var attributes = {};
  10131. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10132. for ( var i = 0; i < n; i ++ ) {
  10133. var info = gl.getActiveAttrib( program, i );
  10134. var name = info.name;
  10135. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10136. attributes[ name ] = gl.getAttribLocation( program, name );
  10137. }
  10138. return attributes;
  10139. }
  10140. function filterEmptyLine( string ) {
  10141. return string !== '';
  10142. }
  10143. function replaceLightNums( string, parameters ) {
  10144. return string
  10145. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10146. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10147. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10148. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10149. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10150. }
  10151. function parseIncludes( string ) {
  10152. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10153. function replace( match, include ) {
  10154. var replace = ShaderChunk[ include ];
  10155. if ( replace === undefined ) {
  10156. throw new Error( 'Can not resolve #include <' + include + '>' );
  10157. }
  10158. return parseIncludes( replace );
  10159. }
  10160. return string.replace( pattern, replace );
  10161. }
  10162. function unrollLoops( string ) {
  10163. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10164. function replace( match, start, end, snippet ) {
  10165. var unroll = '';
  10166. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10167. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10168. }
  10169. return unroll;
  10170. }
  10171. return string.replace( pattern, replace );
  10172. }
  10173. function WebGLProgram( renderer, code, material, parameters ) {
  10174. var gl = renderer.context;
  10175. var extensions = material.extensions;
  10176. var defines = material.defines;
  10177. var vertexShader = material.__webglShader.vertexShader;
  10178. var fragmentShader = material.__webglShader.fragmentShader;
  10179. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10180. if ( parameters.shadowMapType === PCFShadowMap ) {
  10181. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10182. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10183. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10184. }
  10185. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10186. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10187. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10188. if ( parameters.envMap ) {
  10189. switch ( material.envMap.mapping ) {
  10190. case CubeReflectionMapping:
  10191. case CubeRefractionMapping:
  10192. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10193. break;
  10194. case CubeUVReflectionMapping:
  10195. case CubeUVRefractionMapping:
  10196. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10197. break;
  10198. case EquirectangularReflectionMapping:
  10199. case EquirectangularRefractionMapping:
  10200. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10201. break;
  10202. case SphericalReflectionMapping:
  10203. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10204. break;
  10205. }
  10206. switch ( material.envMap.mapping ) {
  10207. case CubeRefractionMapping:
  10208. case EquirectangularRefractionMapping:
  10209. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10210. break;
  10211. }
  10212. switch ( material.combine ) {
  10213. case MultiplyOperation:
  10214. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10215. break;
  10216. case MixOperation:
  10217. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10218. break;
  10219. case AddOperation:
  10220. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10221. break;
  10222. }
  10223. }
  10224. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10225. // console.log( 'building new program ' );
  10226. //
  10227. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  10228. var customDefines = generateDefines( defines );
  10229. //
  10230. var program = gl.createProgram();
  10231. var prefixVertex, prefixFragment;
  10232. if ( material.isRawShaderMaterial ) {
  10233. prefixVertex = [
  10234. customDefines,
  10235. '\n'
  10236. ].filter( filterEmptyLine ).join( '\n' );
  10237. prefixFragment = [
  10238. customExtensions,
  10239. customDefines,
  10240. '\n'
  10241. ].filter( filterEmptyLine ).join( '\n' );
  10242. } else {
  10243. prefixVertex = [
  10244. 'precision ' + parameters.precision + ' float;',
  10245. 'precision ' + parameters.precision + ' int;',
  10246. '#define SHADER_NAME ' + material.__webglShader.name,
  10247. customDefines,
  10248. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10249. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10250. '#define MAX_BONES ' + parameters.maxBones,
  10251. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10252. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10253. parameters.map ? '#define USE_MAP' : '',
  10254. parameters.envMap ? '#define USE_ENVMAP' : '',
  10255. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10256. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10257. parameters.aoMap ? '#define USE_AOMAP' : '',
  10258. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10259. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10260. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10261. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10262. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10263. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10264. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10265. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10266. parameters.vertexColors ? '#define USE_COLOR' : '',
  10267. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10268. parameters.skinning ? '#define USE_SKINNING' : '',
  10269. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10270. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10271. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10272. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10273. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10274. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10275. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10276. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10277. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10278. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10279. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10280. 'uniform mat4 modelMatrix;',
  10281. 'uniform mat4 modelViewMatrix;',
  10282. 'uniform mat4 projectionMatrix;',
  10283. 'uniform mat4 viewMatrix;',
  10284. 'uniform mat3 normalMatrix;',
  10285. 'uniform vec3 cameraPosition;',
  10286. 'attribute vec3 position;',
  10287. 'attribute vec3 normal;',
  10288. 'attribute vec2 uv;',
  10289. '#ifdef USE_COLOR',
  10290. ' attribute vec3 color;',
  10291. '#endif',
  10292. '#ifdef USE_MORPHTARGETS',
  10293. ' attribute vec3 morphTarget0;',
  10294. ' attribute vec3 morphTarget1;',
  10295. ' attribute vec3 morphTarget2;',
  10296. ' attribute vec3 morphTarget3;',
  10297. ' #ifdef USE_MORPHNORMALS',
  10298. ' attribute vec3 morphNormal0;',
  10299. ' attribute vec3 morphNormal1;',
  10300. ' attribute vec3 morphNormal2;',
  10301. ' attribute vec3 morphNormal3;',
  10302. ' #else',
  10303. ' attribute vec3 morphTarget4;',
  10304. ' attribute vec3 morphTarget5;',
  10305. ' attribute vec3 morphTarget6;',
  10306. ' attribute vec3 morphTarget7;',
  10307. ' #endif',
  10308. '#endif',
  10309. '#ifdef USE_SKINNING',
  10310. ' attribute vec4 skinIndex;',
  10311. ' attribute vec4 skinWeight;',
  10312. '#endif',
  10313. '\n'
  10314. ].filter( filterEmptyLine ).join( '\n' );
  10315. prefixFragment = [
  10316. customExtensions,
  10317. 'precision ' + parameters.precision + ' float;',
  10318. 'precision ' + parameters.precision + ' int;',
  10319. '#define SHADER_NAME ' + material.__webglShader.name,
  10320. customDefines,
  10321. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10322. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10323. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10324. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10325. parameters.map ? '#define USE_MAP' : '',
  10326. parameters.envMap ? '#define USE_ENVMAP' : '',
  10327. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10328. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10329. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10330. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10331. parameters.aoMap ? '#define USE_AOMAP' : '',
  10332. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10333. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10334. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10335. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10336. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10337. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10338. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10339. parameters.vertexColors ? '#define USE_COLOR' : '',
  10340. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10341. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10342. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10343. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10344. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10345. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10346. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10347. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10348. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10349. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10350. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10351. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10352. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10353. 'uniform mat4 viewMatrix;',
  10354. 'uniform vec3 cameraPosition;',
  10355. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10356. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10357. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10358. parameters.dithering ? '#define DITHERING' : '',
  10359. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  10360. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10361. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10362. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10363. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10364. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10365. '\n'
  10366. ].filter( filterEmptyLine ).join( '\n' );
  10367. }
  10368. vertexShader = parseIncludes( vertexShader, parameters );
  10369. vertexShader = replaceLightNums( vertexShader, parameters );
  10370. fragmentShader = parseIncludes( fragmentShader, parameters );
  10371. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10372. if ( ! material.isShaderMaterial ) {
  10373. vertexShader = unrollLoops( vertexShader );
  10374. fragmentShader = unrollLoops( fragmentShader );
  10375. }
  10376. var vertexGlsl = prefixVertex + vertexShader;
  10377. var fragmentGlsl = prefixFragment + fragmentShader;
  10378. // console.log( '*VERTEX*', vertexGlsl );
  10379. // console.log( '*FRAGMENT*', fragmentGlsl );
  10380. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10381. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10382. gl.attachShader( program, glVertexShader );
  10383. gl.attachShader( program, glFragmentShader );
  10384. // Force a particular attribute to index 0.
  10385. if ( material.index0AttributeName !== undefined ) {
  10386. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10387. } else if ( parameters.morphTargets === true ) {
  10388. // programs with morphTargets displace position out of attribute 0
  10389. gl.bindAttribLocation( program, 0, 'position' );
  10390. }
  10391. gl.linkProgram( program );
  10392. var programLog = gl.getProgramInfoLog( program );
  10393. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10394. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10395. var runnable = true;
  10396. var haveDiagnostics = true;
  10397. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10398. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10399. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10400. runnable = false;
  10401. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10402. } else if ( programLog !== '' ) {
  10403. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10404. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10405. haveDiagnostics = false;
  10406. }
  10407. if ( haveDiagnostics ) {
  10408. this.diagnostics = {
  10409. runnable: runnable,
  10410. material: material,
  10411. programLog: programLog,
  10412. vertexShader: {
  10413. log: vertexLog,
  10414. prefix: prefixVertex
  10415. },
  10416. fragmentShader: {
  10417. log: fragmentLog,
  10418. prefix: prefixFragment
  10419. }
  10420. };
  10421. }
  10422. // clean up
  10423. gl.deleteShader( glVertexShader );
  10424. gl.deleteShader( glFragmentShader );
  10425. // set up caching for uniform locations
  10426. var cachedUniforms;
  10427. this.getUniforms = function() {
  10428. if ( cachedUniforms === undefined ) {
  10429. cachedUniforms =
  10430. new WebGLUniforms( gl, program, renderer );
  10431. }
  10432. return cachedUniforms;
  10433. };
  10434. // set up caching for attribute locations
  10435. var cachedAttributes;
  10436. this.getAttributes = function() {
  10437. if ( cachedAttributes === undefined ) {
  10438. cachedAttributes = fetchAttributeLocations( gl, program );
  10439. }
  10440. return cachedAttributes;
  10441. };
  10442. // free resource
  10443. this.destroy = function() {
  10444. gl.deleteProgram( program );
  10445. this.program = undefined;
  10446. };
  10447. // DEPRECATED
  10448. Object.defineProperties( this, {
  10449. uniforms: {
  10450. get: function() {
  10451. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10452. return this.getUniforms();
  10453. }
  10454. },
  10455. attributes: {
  10456. get: function() {
  10457. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10458. return this.getAttributes();
  10459. }
  10460. }
  10461. } );
  10462. //
  10463. this.id = programIdCount ++;
  10464. this.code = code;
  10465. this.usedTimes = 1;
  10466. this.program = program;
  10467. this.vertexShader = glVertexShader;
  10468. this.fragmentShader = glFragmentShader;
  10469. return this;
  10470. }
  10471. /**
  10472. * @author mrdoob / http://mrdoob.com/
  10473. */
  10474. function WebGLPrograms( renderer, capabilities ) {
  10475. var programs = [];
  10476. var shaderIDs = {
  10477. MeshDepthMaterial: 'depth',
  10478. MeshNormalMaterial: 'normal',
  10479. MeshBasicMaterial: 'basic',
  10480. MeshLambertMaterial: 'lambert',
  10481. MeshPhongMaterial: 'phong',
  10482. MeshToonMaterial: 'phong',
  10483. MeshStandardMaterial: 'physical',
  10484. MeshPhysicalMaterial: 'physical',
  10485. LineBasicMaterial: 'basic',
  10486. LineDashedMaterial: 'dashed',
  10487. PointsMaterial: 'points'
  10488. };
  10489. var parameterNames = [
  10490. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10491. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10492. "roughnessMap", "metalnessMap", "gradientMap",
  10493. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10494. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10495. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10496. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10497. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10498. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10499. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10500. ];
  10501. function allocateBones( object ) {
  10502. var skeleton = object.skeleton;
  10503. var bones = skeleton.bones;
  10504. if ( capabilities.floatVertexTextures ) {
  10505. return 1024;
  10506. } else {
  10507. // default for when object is not specified
  10508. // ( for example when prebuilding shader to be used with multiple objects )
  10509. //
  10510. // - leave some extra space for other uniforms
  10511. // - limit here is ANGLE's 254 max uniform vectors
  10512. // (up to 54 should be safe)
  10513. var nVertexUniforms = capabilities.maxVertexUniforms;
  10514. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10515. var maxBones = Math.min( nVertexMatrices, bones.length );
  10516. if ( maxBones < bones.length ) {
  10517. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10518. return 0;
  10519. }
  10520. return maxBones;
  10521. }
  10522. }
  10523. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10524. var encoding;
  10525. if ( ! map ) {
  10526. encoding = LinearEncoding;
  10527. } else if ( map.isTexture ) {
  10528. encoding = map.encoding;
  10529. } else if ( map.isWebGLRenderTarget ) {
  10530. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10531. encoding = map.texture.encoding;
  10532. }
  10533. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10534. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10535. encoding = GammaEncoding;
  10536. }
  10537. return encoding;
  10538. }
  10539. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10540. var shaderID = shaderIDs[ material.type ];
  10541. // heuristics to create shader parameters according to lights in the scene
  10542. // (not to blow over maxLights budget)
  10543. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10544. var precision = renderer.getPrecision();
  10545. if ( material.precision !== null ) {
  10546. precision = capabilities.getMaxPrecision( material.precision );
  10547. if ( precision !== material.precision ) {
  10548. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10549. }
  10550. }
  10551. var currentRenderTarget = renderer.getRenderTarget();
  10552. var parameters = {
  10553. shaderID: shaderID,
  10554. precision: precision,
  10555. supportsVertexTextures: capabilities.vertexTextures,
  10556. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10557. map: !! material.map,
  10558. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10559. envMap: !! material.envMap,
  10560. envMapMode: material.envMap && material.envMap.mapping,
  10561. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10562. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10563. lightMap: !! material.lightMap,
  10564. aoMap: !! material.aoMap,
  10565. emissiveMap: !! material.emissiveMap,
  10566. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10567. bumpMap: !! material.bumpMap,
  10568. normalMap: !! material.normalMap,
  10569. displacementMap: !! material.displacementMap,
  10570. roughnessMap: !! material.roughnessMap,
  10571. metalnessMap: !! material.metalnessMap,
  10572. specularMap: !! material.specularMap,
  10573. alphaMap: !! material.alphaMap,
  10574. gradientMap: !! material.gradientMap,
  10575. combine: material.combine,
  10576. vertexColors: material.vertexColors,
  10577. fog: !! fog,
  10578. useFog: material.fog,
  10579. fogExp: ( fog && fog.isFogExp2 ),
  10580. flatShading: material.shading === FlatShading,
  10581. sizeAttenuation: material.sizeAttenuation,
  10582. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10583. skinning: material.skinning && maxBones > 0,
  10584. maxBones: maxBones,
  10585. useVertexTexture: capabilities.floatVertexTextures,
  10586. morphTargets: material.morphTargets,
  10587. morphNormals: material.morphNormals,
  10588. maxMorphTargets: renderer.maxMorphTargets,
  10589. maxMorphNormals: renderer.maxMorphNormals,
  10590. numDirLights: lights.directional.length,
  10591. numPointLights: lights.point.length,
  10592. numSpotLights: lights.spot.length,
  10593. numRectAreaLights: lights.rectArea.length,
  10594. numHemiLights: lights.hemi.length,
  10595. numClippingPlanes: nClipPlanes,
  10596. numClipIntersection: nClipIntersection,
  10597. dithering: material.dithering,
  10598. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10599. shadowMapType: renderer.shadowMap.type,
  10600. toneMapping: renderer.toneMapping,
  10601. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10602. premultipliedAlpha: material.premultipliedAlpha,
  10603. alphaTest: material.alphaTest,
  10604. doubleSided: material.side === DoubleSide,
  10605. flipSided: material.side === BackSide,
  10606. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10607. };
  10608. return parameters;
  10609. };
  10610. this.getProgramCode = function ( material, parameters ) {
  10611. var array = [];
  10612. if ( parameters.shaderID ) {
  10613. array.push( parameters.shaderID );
  10614. } else {
  10615. array.push( material.fragmentShader );
  10616. array.push( material.vertexShader );
  10617. }
  10618. if ( material.defines !== undefined ) {
  10619. for ( var name in material.defines ) {
  10620. array.push( name );
  10621. array.push( material.defines[ name ] );
  10622. }
  10623. }
  10624. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10625. array.push( parameters[ parameterNames[ i ] ] );
  10626. }
  10627. return array.join();
  10628. };
  10629. this.acquireProgram = function ( material, parameters, code ) {
  10630. var program;
  10631. // Check if code has been already compiled
  10632. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10633. var programInfo = programs[ p ];
  10634. if ( programInfo.code === code ) {
  10635. program = programInfo;
  10636. ++ program.usedTimes;
  10637. break;
  10638. }
  10639. }
  10640. if ( program === undefined ) {
  10641. program = new WebGLProgram( renderer, code, material, parameters );
  10642. programs.push( program );
  10643. }
  10644. return program;
  10645. };
  10646. this.releaseProgram = function ( program ) {
  10647. if ( -- program.usedTimes === 0 ) {
  10648. // Remove from unordered set
  10649. var i = programs.indexOf( program );
  10650. programs[ i ] = programs[ programs.length - 1 ];
  10651. programs.pop();
  10652. // Free WebGL resources
  10653. program.destroy();
  10654. }
  10655. };
  10656. // Exposed for resource monitoring & error feedback via renderer.info:
  10657. this.programs = programs;
  10658. }
  10659. /**
  10660. * @author mrdoob / http://mrdoob.com/
  10661. */
  10662. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  10663. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10664. //
  10665. function clampToMaxSize( image, maxSize ) {
  10666. if ( image.width > maxSize || image.height > maxSize ) {
  10667. // Warning: Scaling through the canvas will only work with images that use
  10668. // premultiplied alpha.
  10669. var scale = maxSize / Math.max( image.width, image.height );
  10670. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10671. canvas.width = Math.floor( image.width * scale );
  10672. canvas.height = Math.floor( image.height * scale );
  10673. var context = canvas.getContext( '2d' );
  10674. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10675. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10676. return canvas;
  10677. }
  10678. return image;
  10679. }
  10680. function isPowerOfTwo( image ) {
  10681. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10682. }
  10683. function makePowerOfTwo( image ) {
  10684. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10685. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10686. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10687. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10688. var context = canvas.getContext( '2d' );
  10689. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10690. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10691. return canvas;
  10692. }
  10693. return image;
  10694. }
  10695. function textureNeedsPowerOfTwo( texture ) {
  10696. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10697. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10698. }
  10699. // Fallback filters for non-power-of-2 textures
  10700. function filterFallback( f ) {
  10701. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10702. return _gl.NEAREST;
  10703. }
  10704. return _gl.LINEAR;
  10705. }
  10706. //
  10707. function onTextureDispose( event ) {
  10708. var texture = event.target;
  10709. texture.removeEventListener( 'dispose', onTextureDispose );
  10710. deallocateTexture( texture );
  10711. infoMemory.textures --;
  10712. }
  10713. function onRenderTargetDispose( event ) {
  10714. var renderTarget = event.target;
  10715. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10716. deallocateRenderTarget( renderTarget );
  10717. infoMemory.textures --;
  10718. }
  10719. //
  10720. function deallocateTexture( texture ) {
  10721. var textureProperties = properties.get( texture );
  10722. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10723. // cube texture
  10724. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10725. } else {
  10726. // 2D texture
  10727. if ( textureProperties.__webglInit === undefined ) return;
  10728. _gl.deleteTexture( textureProperties.__webglTexture );
  10729. }
  10730. // remove all webgl properties
  10731. properties.remove( texture );
  10732. }
  10733. function deallocateRenderTarget( renderTarget ) {
  10734. var renderTargetProperties = properties.get( renderTarget );
  10735. var textureProperties = properties.get( renderTarget.texture );
  10736. if ( ! renderTarget ) return;
  10737. if ( textureProperties.__webglTexture !== undefined ) {
  10738. _gl.deleteTexture( textureProperties.__webglTexture );
  10739. }
  10740. if ( renderTarget.depthTexture ) {
  10741. renderTarget.depthTexture.dispose();
  10742. }
  10743. if ( renderTarget.isWebGLRenderTargetCube ) {
  10744. for ( var i = 0; i < 6; i ++ ) {
  10745. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10746. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10747. }
  10748. } else {
  10749. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10750. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10751. }
  10752. properties.remove( renderTarget.texture );
  10753. properties.remove( renderTarget );
  10754. }
  10755. //
  10756. function setTexture2D( texture, slot ) {
  10757. var textureProperties = properties.get( texture );
  10758. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10759. var image = texture.image;
  10760. if ( image === undefined ) {
  10761. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10762. } else if ( image.complete === false ) {
  10763. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10764. } else {
  10765. uploadTexture( textureProperties, texture, slot );
  10766. return;
  10767. }
  10768. }
  10769. state.activeTexture( _gl.TEXTURE0 + slot );
  10770. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10771. }
  10772. function setTextureCube( texture, slot ) {
  10773. var textureProperties = properties.get( texture );
  10774. if ( texture.image.length === 6 ) {
  10775. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10776. if ( ! textureProperties.__image__webglTextureCube ) {
  10777. texture.addEventListener( 'dispose', onTextureDispose );
  10778. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10779. infoMemory.textures ++;
  10780. }
  10781. state.activeTexture( _gl.TEXTURE0 + slot );
  10782. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10783. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10784. var isCompressed = ( texture && texture.isCompressedTexture );
  10785. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10786. var cubeImage = [];
  10787. for ( var i = 0; i < 6; i ++ ) {
  10788. if ( ! isCompressed && ! isDataTexture ) {
  10789. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10790. } else {
  10791. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10792. }
  10793. }
  10794. var image = cubeImage[ 0 ],
  10795. isPowerOfTwoImage = isPowerOfTwo( image ),
  10796. glFormat = paramThreeToGL( texture.format ),
  10797. glType = paramThreeToGL( texture.type );
  10798. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10799. for ( var i = 0; i < 6; i ++ ) {
  10800. if ( ! isCompressed ) {
  10801. if ( isDataTexture ) {
  10802. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10803. } else {
  10804. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10805. }
  10806. } else {
  10807. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10808. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10809. mipmap = mipmaps[ j ];
  10810. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10811. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10812. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10813. } else {
  10814. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10815. }
  10816. } else {
  10817. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10818. }
  10819. }
  10820. }
  10821. }
  10822. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10823. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10824. }
  10825. textureProperties.__version = texture.version;
  10826. if ( texture.onUpdate ) texture.onUpdate( texture );
  10827. } else {
  10828. state.activeTexture( _gl.TEXTURE0 + slot );
  10829. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10830. }
  10831. }
  10832. }
  10833. function setTextureCubeDynamic( texture, slot ) {
  10834. state.activeTexture( _gl.TEXTURE0 + slot );
  10835. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10836. }
  10837. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10838. var extension;
  10839. if ( isPowerOfTwoImage ) {
  10840. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10841. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10842. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10843. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10844. } else {
  10845. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10846. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10847. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10848. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10849. }
  10850. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10851. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10852. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10853. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10854. }
  10855. }
  10856. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10857. if ( extension ) {
  10858. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10859. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10860. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10861. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10862. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10863. }
  10864. }
  10865. }
  10866. function uploadTexture( textureProperties, texture, slot ) {
  10867. if ( textureProperties.__webglInit === undefined ) {
  10868. textureProperties.__webglInit = true;
  10869. texture.addEventListener( 'dispose', onTextureDispose );
  10870. textureProperties.__webglTexture = _gl.createTexture();
  10871. infoMemory.textures ++;
  10872. }
  10873. state.activeTexture( _gl.TEXTURE0 + slot );
  10874. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10875. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10876. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10877. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10878. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10879. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10880. image = makePowerOfTwo( image );
  10881. }
  10882. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10883. glFormat = paramThreeToGL( texture.format ),
  10884. glType = paramThreeToGL( texture.type );
  10885. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10886. var mipmap, mipmaps = texture.mipmaps;
  10887. if ( texture.isDepthTexture ) {
  10888. // populate depth texture with dummy data
  10889. var internalFormat = _gl.DEPTH_COMPONENT;
  10890. if ( texture.type === FloatType ) {
  10891. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10892. internalFormat = _gl.DEPTH_COMPONENT32F;
  10893. } else if ( _isWebGL2 ) {
  10894. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10895. internalFormat = _gl.DEPTH_COMPONENT16;
  10896. }
  10897. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10898. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10899. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10900. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10901. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10902. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10903. texture.type = UnsignedShortType;
  10904. glType = paramThreeToGL( texture.type );
  10905. }
  10906. }
  10907. // Depth stencil textures need the DEPTH_STENCIL internal format
  10908. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10909. if ( texture.format === DepthStencilFormat ) {
  10910. internalFormat = _gl.DEPTH_STENCIL;
  10911. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10912. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10913. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10914. if ( texture.type !== UnsignedInt248Type ) {
  10915. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10916. texture.type = UnsignedInt248Type;
  10917. glType = paramThreeToGL( texture.type );
  10918. }
  10919. }
  10920. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10921. } else if ( texture.isDataTexture ) {
  10922. // use manually created mipmaps if available
  10923. // if there are no manual mipmaps
  10924. // set 0 level mipmap and then use GL to generate other mipmap levels
  10925. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10926. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10927. mipmap = mipmaps[ i ];
  10928. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10929. }
  10930. texture.generateMipmaps = false;
  10931. } else {
  10932. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10933. }
  10934. } else if ( texture.isCompressedTexture ) {
  10935. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10936. mipmap = mipmaps[ i ];
  10937. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10938. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10939. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10940. } else {
  10941. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10942. }
  10943. } else {
  10944. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10945. }
  10946. }
  10947. } else {
  10948. // regular Texture (image, video, canvas)
  10949. // use manually created mipmaps if available
  10950. // if there are no manual mipmaps
  10951. // set 0 level mipmap and then use GL to generate other mipmap levels
  10952. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10953. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10954. mipmap = mipmaps[ i ];
  10955. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10956. }
  10957. texture.generateMipmaps = false;
  10958. } else {
  10959. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10960. }
  10961. }
  10962. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10963. textureProperties.__version = texture.version;
  10964. if ( texture.onUpdate ) texture.onUpdate( texture );
  10965. }
  10966. // Render targets
  10967. // Setup storage for target texture and bind it to correct framebuffer
  10968. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10969. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10970. var glType = paramThreeToGL( renderTarget.texture.type );
  10971. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10972. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10973. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10974. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10975. }
  10976. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10977. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10978. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10979. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10980. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10981. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10982. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10983. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10984. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10985. } else {
  10986. // FIXME: We don't support !depth !stencil
  10987. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10988. }
  10989. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10990. }
  10991. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10992. function setupDepthTexture( framebuffer, renderTarget ) {
  10993. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10994. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10995. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10996. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10997. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10998. }
  10999. // upload an empty depth texture with framebuffer size
  11000. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11001. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11002. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11003. renderTarget.depthTexture.image.width = renderTarget.width;
  11004. renderTarget.depthTexture.image.height = renderTarget.height;
  11005. renderTarget.depthTexture.needsUpdate = true;
  11006. }
  11007. setTexture2D( renderTarget.depthTexture, 0 );
  11008. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11009. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11010. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11011. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11012. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11013. } else {
  11014. throw new Error('Unknown depthTexture format')
  11015. }
  11016. }
  11017. // Setup GL resources for a non-texture depth buffer
  11018. function setupDepthRenderbuffer( renderTarget ) {
  11019. var renderTargetProperties = properties.get( renderTarget );
  11020. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11021. if ( renderTarget.depthTexture ) {
  11022. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  11023. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11024. } else {
  11025. if ( isCube ) {
  11026. renderTargetProperties.__webglDepthbuffer = [];
  11027. for ( var i = 0; i < 6; i ++ ) {
  11028. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11029. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11030. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11031. }
  11032. } else {
  11033. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11034. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11035. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11036. }
  11037. }
  11038. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11039. }
  11040. // Set up GL resources for the render target
  11041. function setupRenderTarget( renderTarget ) {
  11042. var renderTargetProperties = properties.get( renderTarget );
  11043. var textureProperties = properties.get( renderTarget.texture );
  11044. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11045. textureProperties.__webglTexture = _gl.createTexture();
  11046. infoMemory.textures ++;
  11047. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11048. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11049. // Setup framebuffer
  11050. if ( isCube ) {
  11051. renderTargetProperties.__webglFramebuffer = [];
  11052. for ( var i = 0; i < 6; i ++ ) {
  11053. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11054. }
  11055. } else {
  11056. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11057. }
  11058. // Setup color buffer
  11059. if ( isCube ) {
  11060. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11061. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11062. for ( var i = 0; i < 6; i ++ ) {
  11063. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11064. }
  11065. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11066. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11067. } else {
  11068. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11069. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11070. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11071. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11072. state.bindTexture( _gl.TEXTURE_2D, null );
  11073. }
  11074. // Setup depth and stencil buffers
  11075. if ( renderTarget.depthBuffer ) {
  11076. setupDepthRenderbuffer( renderTarget );
  11077. }
  11078. }
  11079. function updateRenderTargetMipmap( renderTarget ) {
  11080. var texture = renderTarget.texture;
  11081. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  11082. texture.minFilter !== NearestFilter &&
  11083. texture.minFilter !== LinearFilter ) {
  11084. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11085. var webglTexture = properties.get( texture ).__webglTexture;
  11086. state.bindTexture( target, webglTexture );
  11087. _gl.generateMipmap( target );
  11088. state.bindTexture( target, null );
  11089. }
  11090. }
  11091. this.setTexture2D = setTexture2D;
  11092. this.setTextureCube = setTextureCube;
  11093. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11094. this.setupRenderTarget = setupRenderTarget;
  11095. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11096. }
  11097. /**
  11098. * @author fordacious / fordacious.github.io
  11099. */
  11100. function WebGLProperties() {
  11101. var properties = {};
  11102. function get( object ) {
  11103. var uuid = object.uuid;
  11104. var map = properties[ uuid ];
  11105. if ( map === undefined ) {
  11106. map = {};
  11107. properties[ uuid ] = map;
  11108. }
  11109. return map;
  11110. }
  11111. function remove( object ) {
  11112. delete properties[ object.uuid ];
  11113. }
  11114. function clear() {
  11115. properties = {};
  11116. }
  11117. return {
  11118. get: get,
  11119. remove: remove,
  11120. clear: clear
  11121. };
  11122. }
  11123. /**
  11124. * @author mrdoob / http://mrdoob.com/
  11125. */
  11126. function WebGLState( gl, extensions, paramThreeToGL ) {
  11127. function ColorBuffer() {
  11128. var locked = false;
  11129. var color = new Vector4();
  11130. var currentColorMask = null;
  11131. var currentColorClear = new Vector4();
  11132. return {
  11133. setMask: function ( colorMask ) {
  11134. if ( currentColorMask !== colorMask && ! locked ) {
  11135. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11136. currentColorMask = colorMask;
  11137. }
  11138. },
  11139. setLocked: function ( lock ) {
  11140. locked = lock;
  11141. },
  11142. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11143. if ( premultipliedAlpha === true ) {
  11144. r *= a; g *= a; b *= a;
  11145. }
  11146. color.set( r, g, b, a );
  11147. if ( currentColorClear.equals( color ) === false ) {
  11148. gl.clearColor( r, g, b, a );
  11149. currentColorClear.copy( color );
  11150. }
  11151. },
  11152. reset: function () {
  11153. locked = false;
  11154. currentColorMask = null;
  11155. currentColorClear.set( 0, 0, 0, 1 );
  11156. }
  11157. };
  11158. }
  11159. function DepthBuffer() {
  11160. var locked = false;
  11161. var currentDepthMask = null;
  11162. var currentDepthFunc = null;
  11163. var currentDepthClear = null;
  11164. return {
  11165. setTest: function ( depthTest ) {
  11166. if ( depthTest ) {
  11167. enable( gl.DEPTH_TEST );
  11168. } else {
  11169. disable( gl.DEPTH_TEST );
  11170. }
  11171. },
  11172. setMask: function ( depthMask ) {
  11173. if ( currentDepthMask !== depthMask && ! locked ) {
  11174. gl.depthMask( depthMask );
  11175. currentDepthMask = depthMask;
  11176. }
  11177. },
  11178. setFunc: function ( depthFunc ) {
  11179. if ( currentDepthFunc !== depthFunc ) {
  11180. if ( depthFunc ) {
  11181. switch ( depthFunc ) {
  11182. case NeverDepth:
  11183. gl.depthFunc( gl.NEVER );
  11184. break;
  11185. case AlwaysDepth:
  11186. gl.depthFunc( gl.ALWAYS );
  11187. break;
  11188. case LessDepth:
  11189. gl.depthFunc( gl.LESS );
  11190. break;
  11191. case LessEqualDepth:
  11192. gl.depthFunc( gl.LEQUAL );
  11193. break;
  11194. case EqualDepth:
  11195. gl.depthFunc( gl.EQUAL );
  11196. break;
  11197. case GreaterEqualDepth:
  11198. gl.depthFunc( gl.GEQUAL );
  11199. break;
  11200. case GreaterDepth:
  11201. gl.depthFunc( gl.GREATER );
  11202. break;
  11203. case NotEqualDepth:
  11204. gl.depthFunc( gl.NOTEQUAL );
  11205. break;
  11206. default:
  11207. gl.depthFunc( gl.LEQUAL );
  11208. }
  11209. } else {
  11210. gl.depthFunc( gl.LEQUAL );
  11211. }
  11212. currentDepthFunc = depthFunc;
  11213. }
  11214. },
  11215. setLocked: function ( lock ) {
  11216. locked = lock;
  11217. },
  11218. setClear: function ( depth ) {
  11219. if ( currentDepthClear !== depth ) {
  11220. gl.clearDepth( depth );
  11221. currentDepthClear = depth;
  11222. }
  11223. },
  11224. reset: function () {
  11225. locked = false;
  11226. currentDepthMask = null;
  11227. currentDepthFunc = null;
  11228. currentDepthClear = null;
  11229. }
  11230. };
  11231. }
  11232. function StencilBuffer() {
  11233. var locked = false;
  11234. var currentStencilMask = null;
  11235. var currentStencilFunc = null;
  11236. var currentStencilRef = null;
  11237. var currentStencilFuncMask = null;
  11238. var currentStencilFail = null;
  11239. var currentStencilZFail = null;
  11240. var currentStencilZPass = null;
  11241. var currentStencilClear = null;
  11242. return {
  11243. setTest: function ( stencilTest ) {
  11244. if ( stencilTest ) {
  11245. enable( gl.STENCIL_TEST );
  11246. } else {
  11247. disable( gl.STENCIL_TEST );
  11248. }
  11249. },
  11250. setMask: function ( stencilMask ) {
  11251. if ( currentStencilMask !== stencilMask && ! locked ) {
  11252. gl.stencilMask( stencilMask );
  11253. currentStencilMask = stencilMask;
  11254. }
  11255. },
  11256. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11257. if ( currentStencilFunc !== stencilFunc ||
  11258. currentStencilRef !== stencilRef ||
  11259. currentStencilFuncMask !== stencilMask ) {
  11260. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11261. currentStencilFunc = stencilFunc;
  11262. currentStencilRef = stencilRef;
  11263. currentStencilFuncMask = stencilMask;
  11264. }
  11265. },
  11266. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11267. if ( currentStencilFail !== stencilFail ||
  11268. currentStencilZFail !== stencilZFail ||
  11269. currentStencilZPass !== stencilZPass ) {
  11270. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11271. currentStencilFail = stencilFail;
  11272. currentStencilZFail = stencilZFail;
  11273. currentStencilZPass = stencilZPass;
  11274. }
  11275. },
  11276. setLocked: function ( lock ) {
  11277. locked = lock;
  11278. },
  11279. setClear: function ( stencil ) {
  11280. if ( currentStencilClear !== stencil ) {
  11281. gl.clearStencil( stencil );
  11282. currentStencilClear = stencil;
  11283. }
  11284. },
  11285. reset: function () {
  11286. locked = false;
  11287. currentStencilMask = null;
  11288. currentStencilFunc = null;
  11289. currentStencilRef = null;
  11290. currentStencilFuncMask = null;
  11291. currentStencilFail = null;
  11292. currentStencilZFail = null;
  11293. currentStencilZPass = null;
  11294. currentStencilClear = null;
  11295. }
  11296. };
  11297. }
  11298. //
  11299. var colorBuffer = new ColorBuffer();
  11300. var depthBuffer = new DepthBuffer();
  11301. var stencilBuffer = new StencilBuffer();
  11302. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11303. var newAttributes = new Uint8Array( maxVertexAttributes );
  11304. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11305. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11306. var capabilities = {};
  11307. var compressedTextureFormats = null;
  11308. var currentBlending = null;
  11309. var currentBlendEquation = null;
  11310. var currentBlendSrc = null;
  11311. var currentBlendDst = null;
  11312. var currentBlendEquationAlpha = null;
  11313. var currentBlendSrcAlpha = null;
  11314. var currentBlendDstAlpha = null;
  11315. var currentPremultipledAlpha = false;
  11316. var currentFlipSided = null;
  11317. var currentCullFace = null;
  11318. var currentLineWidth = null;
  11319. var currentPolygonOffsetFactor = null;
  11320. var currentPolygonOffsetUnits = null;
  11321. var currentScissorTest = null;
  11322. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11323. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11324. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11325. var currentTextureSlot = null;
  11326. var currentBoundTextures = {};
  11327. var currentScissor = new Vector4();
  11328. var currentViewport = new Vector4();
  11329. function createTexture( type, target, count ) {
  11330. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11331. var texture = gl.createTexture();
  11332. gl.bindTexture( type, texture );
  11333. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11334. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11335. for ( var i = 0; i < count; i ++ ) {
  11336. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11337. }
  11338. return texture;
  11339. }
  11340. var emptyTextures = {};
  11341. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11342. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11343. //
  11344. function init() {
  11345. colorBuffer.setClear( 0, 0, 0, 1 );
  11346. depthBuffer.setClear( 1 );
  11347. stencilBuffer.setClear( 0 );
  11348. enable( gl.DEPTH_TEST );
  11349. depthBuffer.setFunc( LessEqualDepth );
  11350. setFlipSided( false );
  11351. setCullFace( CullFaceBack );
  11352. enable( gl.CULL_FACE );
  11353. enable( gl.BLEND );
  11354. setBlending( NormalBlending );
  11355. }
  11356. function initAttributes() {
  11357. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11358. newAttributes[ i ] = 0;
  11359. }
  11360. }
  11361. function enableAttribute( attribute ) {
  11362. newAttributes[ attribute ] = 1;
  11363. if ( enabledAttributes[ attribute ] === 0 ) {
  11364. gl.enableVertexAttribArray( attribute );
  11365. enabledAttributes[ attribute ] = 1;
  11366. }
  11367. if ( attributeDivisors[ attribute ] !== 0 ) {
  11368. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11369. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11370. attributeDivisors[ attribute ] = 0;
  11371. }
  11372. }
  11373. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11374. newAttributes[ attribute ] = 1;
  11375. if ( enabledAttributes[ attribute ] === 0 ) {
  11376. gl.enableVertexAttribArray( attribute );
  11377. enabledAttributes[ attribute ] = 1;
  11378. }
  11379. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11380. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11381. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11382. attributeDivisors[ attribute ] = meshPerAttribute;
  11383. }
  11384. }
  11385. function disableUnusedAttributes() {
  11386. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11387. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11388. gl.disableVertexAttribArray( i );
  11389. enabledAttributes[ i ] = 0;
  11390. }
  11391. }
  11392. }
  11393. function enable( id ) {
  11394. if ( capabilities[ id ] !== true ) {
  11395. gl.enable( id );
  11396. capabilities[ id ] = true;
  11397. }
  11398. }
  11399. function disable( id ) {
  11400. if ( capabilities[ id ] !== false ) {
  11401. gl.disable( id );
  11402. capabilities[ id ] = false;
  11403. }
  11404. }
  11405. function getCompressedTextureFormats() {
  11406. if ( compressedTextureFormats === null ) {
  11407. compressedTextureFormats = [];
  11408. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11409. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11410. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11411. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11412. for ( var i = 0; i < formats.length; i ++ ) {
  11413. compressedTextureFormats.push( formats[ i ] );
  11414. }
  11415. }
  11416. }
  11417. return compressedTextureFormats;
  11418. }
  11419. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11420. if ( blending !== NoBlending ) {
  11421. enable( gl.BLEND );
  11422. } else {
  11423. disable( gl.BLEND );
  11424. }
  11425. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11426. if ( blending === AdditiveBlending ) {
  11427. if ( premultipliedAlpha ) {
  11428. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11429. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11430. } else {
  11431. gl.blendEquation( gl.FUNC_ADD );
  11432. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11433. }
  11434. } else if ( blending === SubtractiveBlending ) {
  11435. if ( premultipliedAlpha ) {
  11436. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11437. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11438. } else {
  11439. gl.blendEquation( gl.FUNC_ADD );
  11440. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11441. }
  11442. } else if ( blending === MultiplyBlending ) {
  11443. if ( premultipliedAlpha ) {
  11444. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11445. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11446. } else {
  11447. gl.blendEquation( gl.FUNC_ADD );
  11448. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11449. }
  11450. } else {
  11451. if ( premultipliedAlpha ) {
  11452. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11453. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11454. } else {
  11455. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11456. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11457. }
  11458. }
  11459. currentBlending = blending;
  11460. currentPremultipledAlpha = premultipliedAlpha;
  11461. }
  11462. if ( blending === CustomBlending ) {
  11463. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11464. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11465. blendDstAlpha = blendDstAlpha || blendDst;
  11466. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11467. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11468. currentBlendEquation = blendEquation;
  11469. currentBlendEquationAlpha = blendEquationAlpha;
  11470. }
  11471. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11472. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11473. currentBlendSrc = blendSrc;
  11474. currentBlendDst = blendDst;
  11475. currentBlendSrcAlpha = blendSrcAlpha;
  11476. currentBlendDstAlpha = blendDstAlpha;
  11477. }
  11478. } else {
  11479. currentBlendEquation = null;
  11480. currentBlendSrc = null;
  11481. currentBlendDst = null;
  11482. currentBlendEquationAlpha = null;
  11483. currentBlendSrcAlpha = null;
  11484. currentBlendDstAlpha = null;
  11485. }
  11486. }
  11487. function setMaterial( material ) {
  11488. material.side === DoubleSide
  11489. ? disable( gl.CULL_FACE )
  11490. : enable( gl.CULL_FACE );
  11491. setFlipSided( material.side === BackSide );
  11492. material.transparent === true
  11493. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11494. : setBlending( NoBlending );
  11495. depthBuffer.setFunc( material.depthFunc );
  11496. depthBuffer.setTest( material.depthTest );
  11497. depthBuffer.setMask( material.depthWrite );
  11498. colorBuffer.setMask( material.colorWrite );
  11499. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11500. }
  11501. //
  11502. function setFlipSided( flipSided ) {
  11503. if ( currentFlipSided !== flipSided ) {
  11504. if ( flipSided ) {
  11505. gl.frontFace( gl.CW );
  11506. } else {
  11507. gl.frontFace( gl.CCW );
  11508. }
  11509. currentFlipSided = flipSided;
  11510. }
  11511. }
  11512. function setCullFace( cullFace ) {
  11513. if ( cullFace !== CullFaceNone ) {
  11514. enable( gl.CULL_FACE );
  11515. if ( cullFace !== currentCullFace ) {
  11516. if ( cullFace === CullFaceBack ) {
  11517. gl.cullFace( gl.BACK );
  11518. } else if ( cullFace === CullFaceFront ) {
  11519. gl.cullFace( gl.FRONT );
  11520. } else {
  11521. gl.cullFace( gl.FRONT_AND_BACK );
  11522. }
  11523. }
  11524. } else {
  11525. disable( gl.CULL_FACE );
  11526. }
  11527. currentCullFace = cullFace;
  11528. }
  11529. function setLineWidth( width ) {
  11530. if ( width !== currentLineWidth ) {
  11531. if ( lineWidthAvailable ) gl.lineWidth( width );
  11532. currentLineWidth = width;
  11533. }
  11534. }
  11535. function setPolygonOffset( polygonOffset, factor, units ) {
  11536. if ( polygonOffset ) {
  11537. enable( gl.POLYGON_OFFSET_FILL );
  11538. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11539. gl.polygonOffset( factor, units );
  11540. currentPolygonOffsetFactor = factor;
  11541. currentPolygonOffsetUnits = units;
  11542. }
  11543. } else {
  11544. disable( gl.POLYGON_OFFSET_FILL );
  11545. }
  11546. }
  11547. function getScissorTest() {
  11548. return currentScissorTest;
  11549. }
  11550. function setScissorTest( scissorTest ) {
  11551. currentScissorTest = scissorTest;
  11552. if ( scissorTest ) {
  11553. enable( gl.SCISSOR_TEST );
  11554. } else {
  11555. disable( gl.SCISSOR_TEST );
  11556. }
  11557. }
  11558. // texture
  11559. function activeTexture( webglSlot ) {
  11560. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11561. if ( currentTextureSlot !== webglSlot ) {
  11562. gl.activeTexture( webglSlot );
  11563. currentTextureSlot = webglSlot;
  11564. }
  11565. }
  11566. function bindTexture( webglType, webglTexture ) {
  11567. if ( currentTextureSlot === null ) {
  11568. activeTexture();
  11569. }
  11570. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11571. if ( boundTexture === undefined ) {
  11572. boundTexture = { type: undefined, texture: undefined };
  11573. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11574. }
  11575. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11576. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11577. boundTexture.type = webglType;
  11578. boundTexture.texture = webglTexture;
  11579. }
  11580. }
  11581. function compressedTexImage2D() {
  11582. try {
  11583. gl.compressedTexImage2D.apply( gl, arguments );
  11584. } catch ( error ) {
  11585. console.error( error );
  11586. }
  11587. }
  11588. function texImage2D() {
  11589. try {
  11590. gl.texImage2D.apply( gl, arguments );
  11591. } catch ( error ) {
  11592. console.error( error );
  11593. }
  11594. }
  11595. //
  11596. function scissor( scissor ) {
  11597. if ( currentScissor.equals( scissor ) === false ) {
  11598. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11599. currentScissor.copy( scissor );
  11600. }
  11601. }
  11602. function viewport( viewport ) {
  11603. if ( currentViewport.equals( viewport ) === false ) {
  11604. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11605. currentViewport.copy( viewport );
  11606. }
  11607. }
  11608. //
  11609. function reset() {
  11610. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11611. if ( enabledAttributes[ i ] === 1 ) {
  11612. gl.disableVertexAttribArray( i );
  11613. enabledAttributes[ i ] = 0;
  11614. }
  11615. }
  11616. capabilities = {};
  11617. compressedTextureFormats = null;
  11618. currentTextureSlot = null;
  11619. currentBoundTextures = {};
  11620. currentBlending = null;
  11621. currentFlipSided = null;
  11622. currentCullFace = null;
  11623. colorBuffer.reset();
  11624. depthBuffer.reset();
  11625. stencilBuffer.reset();
  11626. }
  11627. return {
  11628. buffers: {
  11629. color: colorBuffer,
  11630. depth: depthBuffer,
  11631. stencil: stencilBuffer
  11632. },
  11633. init: init,
  11634. initAttributes: initAttributes,
  11635. enableAttribute: enableAttribute,
  11636. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11637. disableUnusedAttributes: disableUnusedAttributes,
  11638. enable: enable,
  11639. disable: disable,
  11640. getCompressedTextureFormats: getCompressedTextureFormats,
  11641. setBlending: setBlending,
  11642. setMaterial: setMaterial,
  11643. setFlipSided: setFlipSided,
  11644. setCullFace: setCullFace,
  11645. setLineWidth: setLineWidth,
  11646. setPolygonOffset: setPolygonOffset,
  11647. getScissorTest: getScissorTest,
  11648. setScissorTest: setScissorTest,
  11649. activeTexture: activeTexture,
  11650. bindTexture: bindTexture,
  11651. compressedTexImage2D: compressedTexImage2D,
  11652. texImage2D: texImage2D,
  11653. scissor: scissor,
  11654. viewport: viewport,
  11655. reset: reset
  11656. };
  11657. }
  11658. /**
  11659. * @author mrdoob / http://mrdoob.com/
  11660. */
  11661. function WebGLCapabilities( gl, extensions, parameters ) {
  11662. var maxAnisotropy;
  11663. function getMaxAnisotropy() {
  11664. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11665. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11666. if ( extension !== null ) {
  11667. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11668. } else {
  11669. maxAnisotropy = 0;
  11670. }
  11671. return maxAnisotropy;
  11672. }
  11673. function getMaxPrecision( precision ) {
  11674. if ( precision === 'highp' ) {
  11675. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11676. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11677. return 'highp';
  11678. }
  11679. precision = 'mediump';
  11680. }
  11681. if ( precision === 'mediump' ) {
  11682. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11683. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11684. return 'mediump';
  11685. }
  11686. }
  11687. return 'lowp';
  11688. }
  11689. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11690. var maxPrecision = getMaxPrecision( precision );
  11691. if ( maxPrecision !== precision ) {
  11692. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11693. precision = maxPrecision;
  11694. }
  11695. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11696. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11697. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11698. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11699. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11700. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11701. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11702. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11703. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11704. var vertexTextures = maxVertexTextures > 0;
  11705. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11706. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11707. return {
  11708. getMaxAnisotropy: getMaxAnisotropy,
  11709. getMaxPrecision: getMaxPrecision,
  11710. precision: precision,
  11711. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11712. maxTextures: maxTextures,
  11713. maxVertexTextures: maxVertexTextures,
  11714. maxTextureSize: maxTextureSize,
  11715. maxCubemapSize: maxCubemapSize,
  11716. maxAttributes: maxAttributes,
  11717. maxVertexUniforms: maxVertexUniforms,
  11718. maxVaryings: maxVaryings,
  11719. maxFragmentUniforms: maxFragmentUniforms,
  11720. vertexTextures: vertexTextures,
  11721. floatFragmentTextures: floatFragmentTextures,
  11722. floatVertexTextures: floatVertexTextures
  11723. };
  11724. }
  11725. /**
  11726. * @author mrdoob / http://mrdoob.com/
  11727. */
  11728. function WebGLExtensions( gl ) {
  11729. var extensions = {};
  11730. return {
  11731. get: function ( name ) {
  11732. if ( extensions[ name ] !== undefined ) {
  11733. return extensions[ name ];
  11734. }
  11735. var extension;
  11736. switch ( name ) {
  11737. case 'WEBGL_depth_texture':
  11738. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11739. break;
  11740. case 'EXT_texture_filter_anisotropic':
  11741. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11742. break;
  11743. case 'WEBGL_compressed_texture_s3tc':
  11744. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11745. break;
  11746. case 'WEBGL_compressed_texture_pvrtc':
  11747. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11748. break;
  11749. case 'WEBGL_compressed_texture_etc1':
  11750. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11751. break;
  11752. default:
  11753. extension = gl.getExtension( name );
  11754. }
  11755. if ( extension === null ) {
  11756. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11757. }
  11758. extensions[ name ] = extension;
  11759. return extension;
  11760. }
  11761. };
  11762. }
  11763. /**
  11764. * @author tschw
  11765. */
  11766. function WebGLClipping() {
  11767. var scope = this,
  11768. globalState = null,
  11769. numGlobalPlanes = 0,
  11770. localClippingEnabled = false,
  11771. renderingShadows = false,
  11772. plane = new Plane(),
  11773. viewNormalMatrix = new Matrix3(),
  11774. uniform = { value: null, needsUpdate: false };
  11775. this.uniform = uniform;
  11776. this.numPlanes = 0;
  11777. this.numIntersection = 0;
  11778. this.init = function( planes, enableLocalClipping, camera ) {
  11779. var enabled =
  11780. planes.length !== 0 ||
  11781. enableLocalClipping ||
  11782. // enable state of previous frame - the clipping code has to
  11783. // run another frame in order to reset the state:
  11784. numGlobalPlanes !== 0 ||
  11785. localClippingEnabled;
  11786. localClippingEnabled = enableLocalClipping;
  11787. globalState = projectPlanes( planes, camera, 0 );
  11788. numGlobalPlanes = planes.length;
  11789. return enabled;
  11790. };
  11791. this.beginShadows = function() {
  11792. renderingShadows = true;
  11793. projectPlanes( null );
  11794. };
  11795. this.endShadows = function() {
  11796. renderingShadows = false;
  11797. resetGlobalState();
  11798. };
  11799. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11800. if ( ! localClippingEnabled ||
  11801. planes === null || planes.length === 0 ||
  11802. renderingShadows && ! clipShadows ) {
  11803. // there's no local clipping
  11804. if ( renderingShadows ) {
  11805. // there's no global clipping
  11806. projectPlanes( null );
  11807. } else {
  11808. resetGlobalState();
  11809. }
  11810. } else {
  11811. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11812. lGlobal = nGlobal * 4,
  11813. dstArray = cache.clippingState || null;
  11814. uniform.value = dstArray; // ensure unique state
  11815. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11816. for ( var i = 0; i !== lGlobal; ++ i ) {
  11817. dstArray[ i ] = globalState[ i ];
  11818. }
  11819. cache.clippingState = dstArray;
  11820. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11821. this.numPlanes += nGlobal;
  11822. }
  11823. };
  11824. function resetGlobalState() {
  11825. if ( uniform.value !== globalState ) {
  11826. uniform.value = globalState;
  11827. uniform.needsUpdate = numGlobalPlanes > 0;
  11828. }
  11829. scope.numPlanes = numGlobalPlanes;
  11830. scope.numIntersection = 0;
  11831. }
  11832. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11833. var nPlanes = planes !== null ? planes.length : 0,
  11834. dstArray = null;
  11835. if ( nPlanes !== 0 ) {
  11836. dstArray = uniform.value;
  11837. if ( skipTransform !== true || dstArray === null ) {
  11838. var flatSize = dstOffset + nPlanes * 4,
  11839. viewMatrix = camera.matrixWorldInverse;
  11840. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11841. if ( dstArray === null || dstArray.length < flatSize ) {
  11842. dstArray = new Float32Array( flatSize );
  11843. }
  11844. for ( var i = 0, i4 = dstOffset;
  11845. i !== nPlanes; ++ i, i4 += 4 ) {
  11846. plane.copy( planes[ i ] ).
  11847. applyMatrix4( viewMatrix, viewNormalMatrix );
  11848. plane.normal.toArray( dstArray, i4 );
  11849. dstArray[ i4 + 3 ] = plane.constant;
  11850. }
  11851. }
  11852. uniform.value = dstArray;
  11853. uniform.needsUpdate = true;
  11854. }
  11855. scope.numPlanes = nPlanes;
  11856. return dstArray;
  11857. }
  11858. }
  11859. // import { Sphere } from '../math/Sphere';
  11860. /**
  11861. * @author supereggbert / http://www.paulbrunt.co.uk/
  11862. * @author mrdoob / http://mrdoob.com/
  11863. * @author alteredq / http://alteredqualia.com/
  11864. * @author szimek / https://github.com/szimek/
  11865. * @author tschw
  11866. */
  11867. function WebGLRenderer( parameters ) {
  11868. console.log( 'THREE.WebGLRenderer', REVISION );
  11869. parameters = parameters || {};
  11870. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11871. _context = parameters.context !== undefined ? parameters.context : null,
  11872. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11873. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11874. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11875. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11876. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11877. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11878. var lights = [];
  11879. var currentRenderList = null;
  11880. var morphInfluences = new Float32Array( 8 );
  11881. var sprites = [];
  11882. var lensFlares = [];
  11883. // public properties
  11884. this.domElement = _canvas;
  11885. this.context = null;
  11886. // clearing
  11887. this.autoClear = true;
  11888. this.autoClearColor = true;
  11889. this.autoClearDepth = true;
  11890. this.autoClearStencil = true;
  11891. // scene graph
  11892. this.sortObjects = true;
  11893. // user-defined clipping
  11894. this.clippingPlanes = [];
  11895. this.localClippingEnabled = false;
  11896. // physically based shading
  11897. this.gammaFactor = 2.0; // for backwards compatibility
  11898. this.gammaInput = false;
  11899. this.gammaOutput = false;
  11900. // physical lights
  11901. this.physicallyCorrectLights = false;
  11902. // tone mapping
  11903. this.toneMapping = LinearToneMapping;
  11904. this.toneMappingExposure = 1.0;
  11905. this.toneMappingWhitePoint = 1.0;
  11906. // morphs
  11907. this.maxMorphTargets = 8;
  11908. this.maxMorphNormals = 4;
  11909. // internal properties
  11910. var _this = this,
  11911. // internal state cache
  11912. _currentProgram = null,
  11913. _currentRenderTarget = null,
  11914. _currentFramebuffer = null,
  11915. _currentMaterialId = - 1,
  11916. _currentGeometryProgram = '',
  11917. _currentCamera = null,
  11918. _currentScissor = new Vector4(),
  11919. _currentScissorTest = null,
  11920. _currentViewport = new Vector4(),
  11921. //
  11922. _usedTextureUnits = 0,
  11923. //
  11924. _clearColor = new Color( 0x000000 ),
  11925. _clearAlpha = 0,
  11926. _width = _canvas.width,
  11927. _height = _canvas.height,
  11928. _pixelRatio = 1,
  11929. _scissor = new Vector4( 0, 0, _width, _height ),
  11930. _scissorTest = false,
  11931. _viewport = new Vector4( 0, 0, _width, _height ),
  11932. // frustum
  11933. _frustum = new Frustum(),
  11934. // clipping
  11935. _clipping = new WebGLClipping(),
  11936. _clippingEnabled = false,
  11937. _localClippingEnabled = false,
  11938. // camera matrices cache
  11939. _projScreenMatrix = new Matrix4(),
  11940. _vector3 = new Vector3(),
  11941. _matrix4 = new Matrix4(),
  11942. _matrix42 = new Matrix4(),
  11943. // light arrays cache
  11944. _lights = {
  11945. hash: '',
  11946. ambient: [ 0, 0, 0 ],
  11947. directional: [],
  11948. directionalShadowMap: [],
  11949. directionalShadowMatrix: [],
  11950. spot: [],
  11951. spotShadowMap: [],
  11952. spotShadowMatrix: [],
  11953. rectArea: [],
  11954. point: [],
  11955. pointShadowMap: [],
  11956. pointShadowMatrix: [],
  11957. hemi: [],
  11958. shadows: []
  11959. },
  11960. // info
  11961. _infoMemory = {
  11962. geometries: 0,
  11963. textures: 0
  11964. },
  11965. _infoRender = {
  11966. frame: 0,
  11967. calls: 0,
  11968. vertices: 0,
  11969. faces: 0,
  11970. points: 0
  11971. };
  11972. this.info = {
  11973. render: _infoRender,
  11974. memory: _infoMemory,
  11975. programs: null
  11976. };
  11977. // initialize
  11978. var _gl;
  11979. try {
  11980. var contextAttributes = {
  11981. alpha: _alpha,
  11982. depth: _depth,
  11983. stencil: _stencil,
  11984. antialias: _antialias,
  11985. premultipliedAlpha: _premultipliedAlpha,
  11986. preserveDrawingBuffer: _preserveDrawingBuffer
  11987. };
  11988. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  11989. if ( _gl === null ) {
  11990. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11991. throw 'Error creating WebGL context with your selected attributes.';
  11992. } else {
  11993. throw 'Error creating WebGL context.';
  11994. }
  11995. }
  11996. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11997. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11998. _gl.getShaderPrecisionFormat = function () {
  11999. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12000. };
  12001. }
  12002. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12003. } catch ( error ) {
  12004. console.error( 'THREE.WebGLRenderer: ' + error );
  12005. }
  12006. var extensions = new WebGLExtensions( _gl );
  12007. extensions.get( 'WEBGL_depth_texture' );
  12008. extensions.get( 'OES_texture_float' );
  12009. extensions.get( 'OES_texture_float_linear' );
  12010. extensions.get( 'OES_texture_half_float' );
  12011. extensions.get( 'OES_texture_half_float_linear' );
  12012. extensions.get( 'OES_standard_derivatives' );
  12013. extensions.get( 'ANGLE_instanced_arrays' );
  12014. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12015. BufferGeometry.MaxIndex = 4294967296;
  12016. }
  12017. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12018. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  12019. var properties = new WebGLProperties();
  12020. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  12021. var attributes = new WebGLAttributes( _gl );
  12022. var geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12023. var objects = new WebGLObjects( _gl, geometries, _infoRender );
  12024. var programCache = new WebGLPrograms( this, capabilities );
  12025. var lightCache = new WebGLLights();
  12026. var renderLists = new WebGLRenderLists();
  12027. this.info.programs = programCache.programs;
  12028. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12029. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12030. //
  12031. var backgroundPlaneCamera, backgroundPlaneMesh;
  12032. var backgroundBoxCamera, backgroundBoxMesh;
  12033. //
  12034. function getTargetPixelRatio() {
  12035. return _currentRenderTarget === null ? _pixelRatio : 1;
  12036. }
  12037. function setDefaultGLState() {
  12038. state.init();
  12039. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12040. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12041. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12042. }
  12043. function resetGLState() {
  12044. _currentProgram = null;
  12045. _currentCamera = null;
  12046. _currentGeometryProgram = '';
  12047. _currentMaterialId = - 1;
  12048. state.reset();
  12049. }
  12050. setDefaultGLState();
  12051. this.context = _gl;
  12052. this.capabilities = capabilities;
  12053. this.extensions = extensions;
  12054. this.properties = properties;
  12055. this.state = state;
  12056. // shadow map
  12057. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  12058. this.shadowMap = shadowMap;
  12059. // Plugins
  12060. var spritePlugin = new SpritePlugin( this, sprites );
  12061. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  12062. // API
  12063. this.getContext = function () {
  12064. return _gl;
  12065. };
  12066. this.getContextAttributes = function () {
  12067. return _gl.getContextAttributes();
  12068. };
  12069. this.forceContextLoss = function () {
  12070. var extension = extensions.get( 'WEBGL_lose_context' );
  12071. if ( extension ) extension.loseContext();
  12072. };
  12073. this.getMaxAnisotropy = function () {
  12074. return capabilities.getMaxAnisotropy();
  12075. };
  12076. this.getPrecision = function () {
  12077. return capabilities.precision;
  12078. };
  12079. this.getPixelRatio = function () {
  12080. return _pixelRatio;
  12081. };
  12082. this.setPixelRatio = function ( value ) {
  12083. if ( value === undefined ) return;
  12084. _pixelRatio = value;
  12085. this.setSize( _viewport.z, _viewport.w, false );
  12086. };
  12087. this.getSize = function () {
  12088. return {
  12089. width: _width,
  12090. height: _height
  12091. };
  12092. };
  12093. this.setSize = function ( width, height, updateStyle ) {
  12094. _width = width;
  12095. _height = height;
  12096. _canvas.width = width * _pixelRatio;
  12097. _canvas.height = height * _pixelRatio;
  12098. if ( updateStyle !== false ) {
  12099. _canvas.style.width = width + 'px';
  12100. _canvas.style.height = height + 'px';
  12101. }
  12102. this.setViewport( 0, 0, width, height );
  12103. };
  12104. this.setViewport = function ( x, y, width, height ) {
  12105. state.viewport( _viewport.set( x, y, width, height ) );
  12106. };
  12107. this.setScissor = function ( x, y, width, height ) {
  12108. state.scissor( _scissor.set( x, y, width, height ) );
  12109. };
  12110. this.setScissorTest = function ( boolean ) {
  12111. state.setScissorTest( _scissorTest = boolean );
  12112. };
  12113. // Clearing
  12114. this.getClearColor = function () {
  12115. return _clearColor;
  12116. };
  12117. this.setClearColor = function ( color, alpha ) {
  12118. _clearColor.set( color );
  12119. _clearAlpha = alpha !== undefined ? alpha : 1;
  12120. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12121. };
  12122. this.getClearAlpha = function () {
  12123. return _clearAlpha;
  12124. };
  12125. this.setClearAlpha = function ( alpha ) {
  12126. _clearAlpha = alpha;
  12127. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12128. };
  12129. this.clear = function ( color, depth, stencil ) {
  12130. var bits = 0;
  12131. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12132. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12133. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12134. _gl.clear( bits );
  12135. };
  12136. this.clearColor = function () {
  12137. this.clear( true, false, false );
  12138. };
  12139. this.clearDepth = function () {
  12140. this.clear( false, true, false );
  12141. };
  12142. this.clearStencil = function () {
  12143. this.clear( false, false, true );
  12144. };
  12145. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12146. this.setRenderTarget( renderTarget );
  12147. this.clear( color, depth, stencil );
  12148. };
  12149. // Reset
  12150. this.resetGLState = resetGLState;
  12151. this.dispose = function () {
  12152. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12153. renderLists.dispose();
  12154. };
  12155. // Events
  12156. function onContextLost( event ) {
  12157. event.preventDefault();
  12158. resetGLState();
  12159. setDefaultGLState();
  12160. properties.clear();
  12161. objects.clear();
  12162. }
  12163. function onMaterialDispose( event ) {
  12164. var material = event.target;
  12165. material.removeEventListener( 'dispose', onMaterialDispose );
  12166. deallocateMaterial( material );
  12167. }
  12168. // Buffer deallocation
  12169. function deallocateMaterial( material ) {
  12170. releaseMaterialProgramReference( material );
  12171. properties.remove( material );
  12172. }
  12173. function releaseMaterialProgramReference( material ) {
  12174. var programInfo = properties.get( material ).program;
  12175. material.program = undefined;
  12176. if ( programInfo !== undefined ) {
  12177. programCache.releaseProgram( programInfo );
  12178. }
  12179. }
  12180. // Buffer rendering
  12181. function renderObjectImmediate( object, program, material ) {
  12182. object.render( function ( object ) {
  12183. _this.renderBufferImmediate( object, program, material );
  12184. } );
  12185. }
  12186. this.renderBufferImmediate = function ( object, program, material ) {
  12187. state.initAttributes();
  12188. var buffers = properties.get( object );
  12189. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12190. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12191. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12192. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12193. var programAttributes = program.getAttributes();
  12194. if ( object.hasPositions ) {
  12195. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12196. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12197. state.enableAttribute( programAttributes.position );
  12198. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12199. }
  12200. if ( object.hasNormals ) {
  12201. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12202. if ( ! material.isMeshPhongMaterial &&
  12203. ! material.isMeshStandardMaterial &&
  12204. ! material.isMeshNormalMaterial &&
  12205. material.shading === FlatShading ) {
  12206. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12207. var array = object.normalArray;
  12208. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12209. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12210. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12211. array[ i + 0 ] = nx;
  12212. array[ i + 1 ] = ny;
  12213. array[ i + 2 ] = nz;
  12214. array[ i + 3 ] = nx;
  12215. array[ i + 4 ] = ny;
  12216. array[ i + 5 ] = nz;
  12217. array[ i + 6 ] = nx;
  12218. array[ i + 7 ] = ny;
  12219. array[ i + 8 ] = nz;
  12220. }
  12221. }
  12222. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12223. state.enableAttribute( programAttributes.normal );
  12224. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12225. }
  12226. if ( object.hasUvs && material.map ) {
  12227. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12228. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12229. state.enableAttribute( programAttributes.uv );
  12230. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12231. }
  12232. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12233. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12234. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12235. state.enableAttribute( programAttributes.color );
  12236. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12237. }
  12238. state.disableUnusedAttributes();
  12239. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12240. object.count = 0;
  12241. };
  12242. function absNumericalSort( a, b ) {
  12243. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12244. }
  12245. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12246. state.setMaterial( material );
  12247. var program = setProgram( camera, fog, material, object );
  12248. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12249. var updateBuffers = false;
  12250. if ( geometryProgram !== _currentGeometryProgram ) {
  12251. _currentGeometryProgram = geometryProgram;
  12252. updateBuffers = true;
  12253. }
  12254. // morph targets
  12255. var morphTargetInfluences = object.morphTargetInfluences;
  12256. if ( morphTargetInfluences !== undefined ) {
  12257. // TODO Remove allocations
  12258. var activeInfluences = [];
  12259. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12260. var influence = morphTargetInfluences[ i ];
  12261. activeInfluences.push( [ influence, i ] );
  12262. }
  12263. activeInfluences.sort( absNumericalSort );
  12264. if ( activeInfluences.length > 8 ) {
  12265. activeInfluences.length = 8;
  12266. }
  12267. var morphAttributes = geometry.morphAttributes;
  12268. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12269. var influence = activeInfluences[ i ];
  12270. morphInfluences[ i ] = influence[ 0 ];
  12271. if ( influence[ 0 ] !== 0 ) {
  12272. var index = influence[ 1 ];
  12273. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12274. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12275. } else {
  12276. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12277. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12278. }
  12279. }
  12280. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12281. morphInfluences[ i ] = 0.0;
  12282. }
  12283. program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
  12284. updateBuffers = true;
  12285. }
  12286. //
  12287. var index = geometry.index;
  12288. var position = geometry.attributes.position;
  12289. var rangeFactor = 1;
  12290. if ( material.wireframe === true ) {
  12291. index = geometries.getWireframeAttribute( geometry );
  12292. rangeFactor = 2;
  12293. }
  12294. var renderer = bufferRenderer;
  12295. if ( index !== null ) {
  12296. renderer = indexedBufferRenderer;
  12297. renderer.setIndex( index );
  12298. }
  12299. if ( updateBuffers ) {
  12300. setupVertexAttributes( material, program, geometry );
  12301. if ( index !== null ) {
  12302. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  12303. }
  12304. }
  12305. //
  12306. var dataCount = 0;
  12307. if ( index !== null ) {
  12308. dataCount = index.count;
  12309. } else if ( position !== undefined ) {
  12310. dataCount = position.count;
  12311. }
  12312. var rangeStart = geometry.drawRange.start * rangeFactor;
  12313. var rangeCount = geometry.drawRange.count * rangeFactor;
  12314. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12315. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12316. var drawStart = Math.max( rangeStart, groupStart );
  12317. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12318. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12319. if ( drawCount === 0 ) return;
  12320. //
  12321. if ( object.isMesh ) {
  12322. if ( material.wireframe === true ) {
  12323. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12324. renderer.setMode( _gl.LINES );
  12325. } else {
  12326. switch ( object.drawMode ) {
  12327. case TrianglesDrawMode:
  12328. renderer.setMode( _gl.TRIANGLES );
  12329. break;
  12330. case TriangleStripDrawMode:
  12331. renderer.setMode( _gl.TRIANGLE_STRIP );
  12332. break;
  12333. case TriangleFanDrawMode:
  12334. renderer.setMode( _gl.TRIANGLE_FAN );
  12335. break;
  12336. }
  12337. }
  12338. } else if ( object.isLine ) {
  12339. var lineWidth = material.linewidth;
  12340. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12341. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12342. if ( object.isLineSegments ) {
  12343. renderer.setMode( _gl.LINES );
  12344. } else if ( object.isLineLoop ) {
  12345. renderer.setMode( _gl.LINE_LOOP );
  12346. } else {
  12347. renderer.setMode( _gl.LINE_STRIP );
  12348. }
  12349. } else if ( object.isPoints ) {
  12350. renderer.setMode( _gl.POINTS );
  12351. }
  12352. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12353. if ( geometry.maxInstancedCount > 0 ) {
  12354. renderer.renderInstances( geometry, drawStart, drawCount );
  12355. }
  12356. } else {
  12357. renderer.render( drawStart, drawCount );
  12358. }
  12359. };
  12360. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12361. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12362. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12363. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12364. return;
  12365. }
  12366. }
  12367. if ( startIndex === undefined ) startIndex = 0;
  12368. state.initAttributes();
  12369. var geometryAttributes = geometry.attributes;
  12370. var programAttributes = program.getAttributes();
  12371. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12372. for ( var name in programAttributes ) {
  12373. var programAttribute = programAttributes[ name ];
  12374. if ( programAttribute >= 0 ) {
  12375. var geometryAttribute = geometryAttributes[ name ];
  12376. if ( geometryAttribute !== undefined ) {
  12377. var normalized = geometryAttribute.normalized;
  12378. var size = geometryAttribute.itemSize;
  12379. var attributeProperties = attributes.get( geometryAttribute );
  12380. var buffer = attributeProperties.buffer;
  12381. var type = attributeProperties.type;
  12382. var bytesPerElement = attributeProperties.bytesPerElement;
  12383. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12384. var data = geometryAttribute.data;
  12385. var stride = data.stride;
  12386. var offset = geometryAttribute.offset;
  12387. if ( data && data.isInstancedInterleavedBuffer ) {
  12388. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12389. if ( geometry.maxInstancedCount === undefined ) {
  12390. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12391. }
  12392. } else {
  12393. state.enableAttribute( programAttribute );
  12394. }
  12395. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12396. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12397. } else {
  12398. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12399. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12400. if ( geometry.maxInstancedCount === undefined ) {
  12401. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12402. }
  12403. } else {
  12404. state.enableAttribute( programAttribute );
  12405. }
  12406. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12407. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12408. }
  12409. } else if ( materialDefaultAttributeValues !== undefined ) {
  12410. var value = materialDefaultAttributeValues[ name ];
  12411. if ( value !== undefined ) {
  12412. switch ( value.length ) {
  12413. case 2:
  12414. _gl.vertexAttrib2fv( programAttribute, value );
  12415. break;
  12416. case 3:
  12417. _gl.vertexAttrib3fv( programAttribute, value );
  12418. break;
  12419. case 4:
  12420. _gl.vertexAttrib4fv( programAttribute, value );
  12421. break;
  12422. default:
  12423. _gl.vertexAttrib1fv( programAttribute, value );
  12424. }
  12425. }
  12426. }
  12427. }
  12428. }
  12429. state.disableUnusedAttributes();
  12430. }
  12431. // Compile
  12432. this.compile = function ( scene, camera ) {
  12433. lights = [];
  12434. scene.traverse( function ( object ) {
  12435. if ( object.isLight ) {
  12436. lights.push( object );
  12437. }
  12438. } );
  12439. setupLights( lights, camera );
  12440. scene.traverse( function ( object ) {
  12441. if ( object.material ) {
  12442. if ( Array.isArray( object.material ) ) {
  12443. for ( var i = 0; i < object.material.length; i ++ ) {
  12444. initMaterial( object.material[ i ], scene.fog, object );
  12445. }
  12446. } else {
  12447. initMaterial( object.material, scene.fog, object );
  12448. }
  12449. }
  12450. } );
  12451. };
  12452. // Rendering
  12453. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12454. if ( camera !== undefined && camera.isCamera !== true ) {
  12455. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12456. return;
  12457. }
  12458. // reset caching for this frame
  12459. _currentGeometryProgram = '';
  12460. _currentMaterialId = - 1;
  12461. _currentCamera = null;
  12462. // update scene graph
  12463. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12464. // update camera matrices and frustum
  12465. camera.onBeforeRender( _this );
  12466. if ( camera.parent === null ) camera.updateMatrixWorld();
  12467. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12468. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12469. _frustum.setFromMatrix( _projScreenMatrix );
  12470. lights.length = 0;
  12471. sprites.length = 0;
  12472. lensFlares.length = 0;
  12473. _localClippingEnabled = this.localClippingEnabled;
  12474. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12475. currentRenderList = renderLists.get( scene, camera );
  12476. currentRenderList.init();
  12477. projectObject( scene, camera, _this.sortObjects );
  12478. currentRenderList.finish();
  12479. if ( _this.sortObjects === true ) {
  12480. currentRenderList.sort();
  12481. }
  12482. //
  12483. if ( _clippingEnabled ) _clipping.beginShadows();
  12484. setupShadows( lights );
  12485. shadowMap.render( scene, camera );
  12486. setupLights( lights, camera );
  12487. if ( _clippingEnabled ) _clipping.endShadows();
  12488. //
  12489. _infoRender.frame ++;
  12490. _infoRender.calls = 0;
  12491. _infoRender.vertices = 0;
  12492. _infoRender.faces = 0;
  12493. _infoRender.points = 0;
  12494. if ( renderTarget === undefined ) {
  12495. renderTarget = null;
  12496. }
  12497. this.setRenderTarget( renderTarget );
  12498. //
  12499. var background = scene.background;
  12500. if ( background === null ) {
  12501. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12502. } else if ( background && background.isColor ) {
  12503. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12504. forceClear = true;
  12505. }
  12506. if ( this.autoClear || forceClear ) {
  12507. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12508. }
  12509. if ( background && background.isCubeTexture ) {
  12510. if ( backgroundBoxCamera === undefined ) {
  12511. backgroundBoxCamera = new PerspectiveCamera();
  12512. backgroundBoxMesh = new Mesh(
  12513. new BoxBufferGeometry( 5, 5, 5 ),
  12514. new ShaderMaterial( {
  12515. uniforms: ShaderLib.cube.uniforms,
  12516. vertexShader: ShaderLib.cube.vertexShader,
  12517. fragmentShader: ShaderLib.cube.fragmentShader,
  12518. side: BackSide,
  12519. depthTest: false,
  12520. depthWrite: false,
  12521. fog: false
  12522. } )
  12523. );
  12524. }
  12525. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  12526. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  12527. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  12528. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12529. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12530. objects.update( backgroundBoxMesh );
  12531. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12532. } else if ( background && background.isTexture ) {
  12533. if ( backgroundPlaneCamera === undefined ) {
  12534. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12535. backgroundPlaneMesh = new Mesh(
  12536. new PlaneBufferGeometry( 2, 2 ),
  12537. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  12538. );
  12539. }
  12540. backgroundPlaneMesh.material.map = background;
  12541. objects.update( backgroundPlaneMesh );
  12542. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12543. }
  12544. //
  12545. var opaqueObjects = currentRenderList.opaque;
  12546. var transparentObjects = currentRenderList.transparent;
  12547. if ( scene.overrideMaterial ) {
  12548. var overrideMaterial = scene.overrideMaterial;
  12549. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12550. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12551. } else {
  12552. // opaque pass (front-to-back order)
  12553. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12554. // transparent pass (back-to-front order)
  12555. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12556. }
  12557. // custom render plugins (post pass)
  12558. spritePlugin.render( scene, camera );
  12559. lensFlarePlugin.render( scene, camera, _currentViewport );
  12560. // Generate mipmap if we're using any kind of mipmap filtering
  12561. if ( renderTarget ) {
  12562. textures.updateRenderTargetMipmap( renderTarget );
  12563. }
  12564. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12565. state.buffers.depth.setTest( true );
  12566. state.buffers.depth.setMask( true );
  12567. state.buffers.color.setMask( true );
  12568. if ( camera.isArrayCamera && camera.enabled ) {
  12569. _this.setScissorTest( false );
  12570. }
  12571. camera.onAfterRender( _this );
  12572. // _gl.finish();
  12573. };
  12574. /*
  12575. // TODO Duplicated code (Frustum)
  12576. var _sphere = new Sphere();
  12577. function isObjectViewable( object ) {
  12578. var geometry = object.geometry;
  12579. if ( geometry.boundingSphere === null )
  12580. geometry.computeBoundingSphere();
  12581. _sphere.copy( geometry.boundingSphere ).
  12582. applyMatrix4( object.matrixWorld );
  12583. return isSphereViewable( _sphere );
  12584. }
  12585. function isSpriteViewable( sprite ) {
  12586. _sphere.center.set( 0, 0, 0 );
  12587. _sphere.radius = 0.7071067811865476;
  12588. _sphere.applyMatrix4( sprite.matrixWorld );
  12589. return isSphereViewable( _sphere );
  12590. }
  12591. function isSphereViewable( sphere ) {
  12592. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12593. var numPlanes = _clipping.numPlanes;
  12594. if ( numPlanes === 0 ) return true;
  12595. var planes = _this.clippingPlanes,
  12596. center = sphere.center,
  12597. negRad = - sphere.radius,
  12598. i = 0;
  12599. do {
  12600. // out when deeper than radius in the negative halfspace
  12601. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12602. } while ( ++ i !== numPlanes );
  12603. return true;
  12604. }
  12605. */
  12606. function projectObject( object, camera, sortObjects ) {
  12607. if ( ! object.visible ) return;
  12608. var visible = object.layers.test( camera.layers );
  12609. if ( visible ) {
  12610. if ( object.isLight ) {
  12611. lights.push( object );
  12612. } else if ( object.isSprite ) {
  12613. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  12614. sprites.push( object );
  12615. }
  12616. } else if ( object.isLensFlare ) {
  12617. lensFlares.push( object );
  12618. } else if ( object.isImmediateRenderObject ) {
  12619. if ( sortObjects ) {
  12620. _vector3.setFromMatrixPosition( object.matrixWorld )
  12621. .applyMatrix4( _projScreenMatrix );
  12622. }
  12623. currentRenderList.push( object, null, object.material, _vector3.z, null );
  12624. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12625. if ( object.isSkinnedMesh ) {
  12626. object.skeleton.update();
  12627. }
  12628. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  12629. if ( sortObjects ) {
  12630. _vector3.setFromMatrixPosition( object.matrixWorld )
  12631. .applyMatrix4( _projScreenMatrix );
  12632. }
  12633. var geometry = objects.update( object );
  12634. var material = object.material;
  12635. if ( Array.isArray( material ) ) {
  12636. var groups = geometry.groups;
  12637. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12638. var group = groups[ i ];
  12639. var groupMaterial = material[ group.materialIndex ];
  12640. if ( groupMaterial && groupMaterial.visible ) {
  12641. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  12642. }
  12643. }
  12644. } else if ( material.visible ) {
  12645. currentRenderList.push( object, geometry, material, _vector3.z, null );
  12646. }
  12647. }
  12648. }
  12649. }
  12650. var children = object.children;
  12651. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12652. projectObject( children[ i ], camera, sortObjects );
  12653. }
  12654. }
  12655. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12656. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12657. var renderItem = renderList[ i ];
  12658. var object = renderItem.object;
  12659. var geometry = renderItem.geometry;
  12660. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12661. var group = renderItem.group;
  12662. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12663. if ( camera.isArrayCamera && camera.enabled ) {
  12664. var cameras = camera.cameras;
  12665. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  12666. var camera2 = cameras[ j ];
  12667. var bounds = camera2.bounds;
  12668. _this.setViewport(
  12669. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12670. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12671. );
  12672. _this.setScissor(
  12673. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12674. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12675. );
  12676. _this.setScissorTest( true );
  12677. renderObject( object, scene, camera2, geometry, material, group );
  12678. }
  12679. } else {
  12680. renderObject( object, scene, camera, geometry, material, group );
  12681. }
  12682. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12683. }
  12684. }
  12685. function renderObject( object, scene, camera, geometry, material, group ) {
  12686. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12687. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12688. if ( object.isImmediateRenderObject ) {
  12689. state.setMaterial( material );
  12690. var program = setProgram( camera, scene.fog, material, object );
  12691. _currentGeometryProgram = '';
  12692. renderObjectImmediate( object, program, material );
  12693. } else {
  12694. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12695. }
  12696. }
  12697. function initMaterial( material, fog, object ) {
  12698. var materialProperties = properties.get( material );
  12699. var parameters = programCache.getParameters(
  12700. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12701. var code = programCache.getProgramCode( material, parameters );
  12702. var program = materialProperties.program;
  12703. var programChange = true;
  12704. if ( program === undefined ) {
  12705. // new material
  12706. material.addEventListener( 'dispose', onMaterialDispose );
  12707. } else if ( program.code !== code ) {
  12708. // changed glsl or parameters
  12709. releaseMaterialProgramReference( material );
  12710. } else if ( parameters.shaderID !== undefined ) {
  12711. // same glsl and uniform list
  12712. return;
  12713. } else {
  12714. // only rebuild uniform list
  12715. programChange = false;
  12716. }
  12717. if ( programChange ) {
  12718. if ( parameters.shaderID ) {
  12719. var shader = ShaderLib[ parameters.shaderID ];
  12720. materialProperties.__webglShader = {
  12721. name: material.type,
  12722. uniforms: UniformsUtils.clone( shader.uniforms ),
  12723. vertexShader: shader.vertexShader,
  12724. fragmentShader: shader.fragmentShader
  12725. };
  12726. } else {
  12727. materialProperties.__webglShader = {
  12728. name: material.type,
  12729. uniforms: material.uniforms,
  12730. vertexShader: material.vertexShader,
  12731. fragmentShader: material.fragmentShader
  12732. };
  12733. }
  12734. material.__webglShader = materialProperties.__webglShader;
  12735. program = programCache.acquireProgram( material, parameters, code );
  12736. materialProperties.program = program;
  12737. material.program = program;
  12738. }
  12739. var programAttributes = program.getAttributes();
  12740. if ( material.morphTargets ) {
  12741. material.numSupportedMorphTargets = 0;
  12742. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12743. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  12744. material.numSupportedMorphTargets ++;
  12745. }
  12746. }
  12747. }
  12748. if ( material.morphNormals ) {
  12749. material.numSupportedMorphNormals = 0;
  12750. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12751. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  12752. material.numSupportedMorphNormals ++;
  12753. }
  12754. }
  12755. }
  12756. var uniforms = materialProperties.__webglShader.uniforms;
  12757. if ( ! material.isShaderMaterial &&
  12758. ! material.isRawShaderMaterial ||
  12759. material.clipping === true ) {
  12760. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12761. materialProperties.numIntersection = _clipping.numIntersection;
  12762. uniforms.clippingPlanes = _clipping.uniform;
  12763. }
  12764. materialProperties.fog = fog;
  12765. // store the light setup it was created for
  12766. materialProperties.lightsHash = _lights.hash;
  12767. if ( material.lights ) {
  12768. // wire up the material to this renderer's lighting state
  12769. uniforms.ambientLightColor.value = _lights.ambient;
  12770. uniforms.directionalLights.value = _lights.directional;
  12771. uniforms.spotLights.value = _lights.spot;
  12772. uniforms.rectAreaLights.value = _lights.rectArea;
  12773. uniforms.pointLights.value = _lights.point;
  12774. uniforms.hemisphereLights.value = _lights.hemi;
  12775. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12776. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12777. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12778. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12779. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12780. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12781. // TODO (abelnation): add area lights shadow info to uniforms
  12782. }
  12783. var progUniforms = materialProperties.program.getUniforms(),
  12784. uniformsList =
  12785. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12786. materialProperties.uniformsList = uniformsList;
  12787. }
  12788. function setProgram( camera, fog, material, object ) {
  12789. _usedTextureUnits = 0;
  12790. var materialProperties = properties.get( material );
  12791. if ( _clippingEnabled ) {
  12792. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12793. var useCache =
  12794. camera === _currentCamera &&
  12795. material.id === _currentMaterialId;
  12796. // we might want to call this function with some ClippingGroup
  12797. // object instead of the material, once it becomes feasible
  12798. // (#8465, #8379)
  12799. _clipping.setState(
  12800. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12801. camera, materialProperties, useCache );
  12802. }
  12803. }
  12804. if ( material.needsUpdate === false ) {
  12805. if ( materialProperties.program === undefined ) {
  12806. material.needsUpdate = true;
  12807. } else if ( material.fog && materialProperties.fog !== fog ) {
  12808. material.needsUpdate = true;
  12809. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12810. material.needsUpdate = true;
  12811. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12812. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12813. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12814. material.needsUpdate = true;
  12815. }
  12816. }
  12817. if ( material.needsUpdate ) {
  12818. initMaterial( material, fog, object );
  12819. material.needsUpdate = false;
  12820. }
  12821. var refreshProgram = false;
  12822. var refreshMaterial = false;
  12823. var refreshLights = false;
  12824. var program = materialProperties.program,
  12825. p_uniforms = program.getUniforms(),
  12826. m_uniforms = materialProperties.__webglShader.uniforms;
  12827. if ( program.id !== _currentProgram ) {
  12828. _gl.useProgram( program.program );
  12829. _currentProgram = program.id;
  12830. refreshProgram = true;
  12831. refreshMaterial = true;
  12832. refreshLights = true;
  12833. }
  12834. if ( material.id !== _currentMaterialId ) {
  12835. _currentMaterialId = material.id;
  12836. refreshMaterial = true;
  12837. }
  12838. if ( refreshProgram || camera !== _currentCamera ) {
  12839. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  12840. if ( capabilities.logarithmicDepthBuffer ) {
  12841. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12842. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12843. }
  12844. if ( camera !== _currentCamera ) {
  12845. _currentCamera = camera;
  12846. // lighting uniforms depend on the camera so enforce an update
  12847. // now, in case this material supports lights - or later, when
  12848. // the next material that does gets activated:
  12849. refreshMaterial = true; // set to true on material change
  12850. refreshLights = true; // remains set until update done
  12851. }
  12852. // load material specific uniforms
  12853. // (shader material also gets them for the sake of genericity)
  12854. if ( material.isShaderMaterial ||
  12855. material.isMeshPhongMaterial ||
  12856. material.isMeshStandardMaterial ||
  12857. material.envMap ) {
  12858. var uCamPos = p_uniforms.map.cameraPosition;
  12859. if ( uCamPos !== undefined ) {
  12860. uCamPos.setValue( _gl,
  12861. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12862. }
  12863. }
  12864. if ( material.isMeshPhongMaterial ||
  12865. material.isMeshLambertMaterial ||
  12866. material.isMeshBasicMaterial ||
  12867. material.isMeshStandardMaterial ||
  12868. material.isShaderMaterial ||
  12869. material.skinning ) {
  12870. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12871. }
  12872. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  12873. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  12874. }
  12875. // skinning uniforms must be set even if material didn't change
  12876. // auto-setting of texture unit for bone texture must go before other textures
  12877. // not sure why, but otherwise weird things happen
  12878. if ( material.skinning ) {
  12879. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12880. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12881. var skeleton = object.skeleton;
  12882. if ( skeleton ) {
  12883. var bones = skeleton.bones;
  12884. if ( capabilities.floatVertexTextures ) {
  12885. if ( skeleton.boneTexture === undefined ) {
  12886. // layout (1 matrix = 4 pixels)
  12887. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  12888. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  12889. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  12890. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  12891. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  12892. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  12893. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  12894. size = Math.max( size, 4 );
  12895. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  12896. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  12897. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  12898. skeleton.boneMatrices = boneMatrices;
  12899. skeleton.boneTexture = boneTexture;
  12900. skeleton.boneTextureSize = size;
  12901. }
  12902. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  12903. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  12904. } else {
  12905. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12906. }
  12907. }
  12908. }
  12909. if ( refreshMaterial ) {
  12910. if ( material.lights ) {
  12911. // the current material requires lighting info
  12912. // note: all lighting uniforms are always set correctly
  12913. // they simply reference the renderer's state for their
  12914. // values
  12915. //
  12916. // use the current material's .needsUpdate flags to set
  12917. // the GL state when required
  12918. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12919. }
  12920. // refresh uniforms common to several materials
  12921. if ( fog && material.fog ) {
  12922. refreshUniformsFog( m_uniforms, fog );
  12923. }
  12924. if ( material.isMeshBasicMaterial ||
  12925. material.isMeshLambertMaterial ||
  12926. material.isMeshPhongMaterial ||
  12927. material.isMeshStandardMaterial ||
  12928. material.isMeshNormalMaterial ||
  12929. material.isMeshDepthMaterial ) {
  12930. refreshUniformsCommon( m_uniforms, material );
  12931. }
  12932. // refresh single material specific uniforms
  12933. if ( material.isLineBasicMaterial ) {
  12934. refreshUniformsLine( m_uniforms, material );
  12935. } else if ( material.isLineDashedMaterial ) {
  12936. refreshUniformsLine( m_uniforms, material );
  12937. refreshUniformsDash( m_uniforms, material );
  12938. } else if ( material.isPointsMaterial ) {
  12939. refreshUniformsPoints( m_uniforms, material );
  12940. } else if ( material.isMeshLambertMaterial ) {
  12941. refreshUniformsLambert( m_uniforms, material );
  12942. } else if ( material.isMeshToonMaterial ) {
  12943. refreshUniformsToon( m_uniforms, material );
  12944. } else if ( material.isMeshPhongMaterial ) {
  12945. refreshUniformsPhong( m_uniforms, material );
  12946. } else if ( material.isMeshPhysicalMaterial ) {
  12947. refreshUniformsPhysical( m_uniforms, material );
  12948. } else if ( material.isMeshStandardMaterial ) {
  12949. refreshUniformsStandard( m_uniforms, material );
  12950. } else if ( material.isMeshDepthMaterial ) {
  12951. if ( material.displacementMap ) {
  12952. m_uniforms.displacementMap.value = material.displacementMap;
  12953. m_uniforms.displacementScale.value = material.displacementScale;
  12954. m_uniforms.displacementBias.value = material.displacementBias;
  12955. }
  12956. } else if ( material.isMeshNormalMaterial ) {
  12957. refreshUniformsNormal( m_uniforms, material );
  12958. }
  12959. // RectAreaLight Texture
  12960. // TODO (mrdoob): Find a nicer implementation
  12961. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  12962. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  12963. WebGLUniforms.upload(
  12964. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12965. }
  12966. // common matrices
  12967. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  12968. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  12969. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12970. return program;
  12971. }
  12972. // Uniforms (refresh uniforms objects)
  12973. function refreshUniformsCommon( uniforms, material ) {
  12974. uniforms.opacity.value = material.opacity;
  12975. uniforms.diffuse.value = material.color;
  12976. if ( material.emissive ) {
  12977. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12978. }
  12979. uniforms.map.value = material.map;
  12980. uniforms.specularMap.value = material.specularMap;
  12981. uniforms.alphaMap.value = material.alphaMap;
  12982. if ( material.lightMap ) {
  12983. uniforms.lightMap.value = material.lightMap;
  12984. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12985. }
  12986. if ( material.aoMap ) {
  12987. uniforms.aoMap.value = material.aoMap;
  12988. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12989. }
  12990. // uv repeat and offset setting priorities
  12991. // 1. color map
  12992. // 2. specular map
  12993. // 3. normal map
  12994. // 4. bump map
  12995. // 5. alpha map
  12996. // 6. emissive map
  12997. var uvScaleMap;
  12998. if ( material.map ) {
  12999. uvScaleMap = material.map;
  13000. } else if ( material.specularMap ) {
  13001. uvScaleMap = material.specularMap;
  13002. } else if ( material.displacementMap ) {
  13003. uvScaleMap = material.displacementMap;
  13004. } else if ( material.normalMap ) {
  13005. uvScaleMap = material.normalMap;
  13006. } else if ( material.bumpMap ) {
  13007. uvScaleMap = material.bumpMap;
  13008. } else if ( material.roughnessMap ) {
  13009. uvScaleMap = material.roughnessMap;
  13010. } else if ( material.metalnessMap ) {
  13011. uvScaleMap = material.metalnessMap;
  13012. } else if ( material.alphaMap ) {
  13013. uvScaleMap = material.alphaMap;
  13014. } else if ( material.emissiveMap ) {
  13015. uvScaleMap = material.emissiveMap;
  13016. }
  13017. if ( uvScaleMap !== undefined ) {
  13018. // backwards compatibility
  13019. if ( uvScaleMap.isWebGLRenderTarget ) {
  13020. uvScaleMap = uvScaleMap.texture;
  13021. }
  13022. var offset = uvScaleMap.offset;
  13023. var repeat = uvScaleMap.repeat;
  13024. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13025. }
  13026. uniforms.envMap.value = material.envMap;
  13027. // don't flip CubeTexture envMaps, flip everything else:
  13028. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13029. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13030. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13031. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13032. uniforms.reflectivity.value = material.reflectivity;
  13033. uniforms.refractionRatio.value = material.refractionRatio;
  13034. }
  13035. function refreshUniformsLine( uniforms, material ) {
  13036. uniforms.diffuse.value = material.color;
  13037. uniforms.opacity.value = material.opacity;
  13038. }
  13039. function refreshUniformsDash( uniforms, material ) {
  13040. uniforms.dashSize.value = material.dashSize;
  13041. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13042. uniforms.scale.value = material.scale;
  13043. }
  13044. function refreshUniformsPoints( uniforms, material ) {
  13045. uniforms.diffuse.value = material.color;
  13046. uniforms.opacity.value = material.opacity;
  13047. uniforms.size.value = material.size * _pixelRatio;
  13048. uniforms.scale.value = _height * 0.5;
  13049. uniforms.map.value = material.map;
  13050. if ( material.map !== null ) {
  13051. var offset = material.map.offset;
  13052. var repeat = material.map.repeat;
  13053. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13054. }
  13055. }
  13056. function refreshUniformsFog( uniforms, fog ) {
  13057. uniforms.fogColor.value = fog.color;
  13058. if ( fog.isFog ) {
  13059. uniforms.fogNear.value = fog.near;
  13060. uniforms.fogFar.value = fog.far;
  13061. } else if ( fog.isFogExp2 ) {
  13062. uniforms.fogDensity.value = fog.density;
  13063. }
  13064. }
  13065. function refreshUniformsLambert( uniforms, material ) {
  13066. if ( material.emissiveMap ) {
  13067. uniforms.emissiveMap.value = material.emissiveMap;
  13068. }
  13069. }
  13070. function refreshUniformsPhong( uniforms, material ) {
  13071. uniforms.specular.value = material.specular;
  13072. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13073. if ( material.emissiveMap ) {
  13074. uniforms.emissiveMap.value = material.emissiveMap;
  13075. }
  13076. if ( material.bumpMap ) {
  13077. uniforms.bumpMap.value = material.bumpMap;
  13078. uniforms.bumpScale.value = material.bumpScale;
  13079. }
  13080. if ( material.normalMap ) {
  13081. uniforms.normalMap.value = material.normalMap;
  13082. uniforms.normalScale.value.copy( material.normalScale );
  13083. }
  13084. if ( material.displacementMap ) {
  13085. uniforms.displacementMap.value = material.displacementMap;
  13086. uniforms.displacementScale.value = material.displacementScale;
  13087. uniforms.displacementBias.value = material.displacementBias;
  13088. }
  13089. }
  13090. function refreshUniformsToon( uniforms, material ) {
  13091. refreshUniformsPhong( uniforms, material );
  13092. if ( material.gradientMap ) {
  13093. uniforms.gradientMap.value = material.gradientMap;
  13094. }
  13095. }
  13096. function refreshUniformsStandard( uniforms, material ) {
  13097. uniforms.roughness.value = material.roughness;
  13098. uniforms.metalness.value = material.metalness;
  13099. if ( material.roughnessMap ) {
  13100. uniforms.roughnessMap.value = material.roughnessMap;
  13101. }
  13102. if ( material.metalnessMap ) {
  13103. uniforms.metalnessMap.value = material.metalnessMap;
  13104. }
  13105. if ( material.emissiveMap ) {
  13106. uniforms.emissiveMap.value = material.emissiveMap;
  13107. }
  13108. if ( material.bumpMap ) {
  13109. uniforms.bumpMap.value = material.bumpMap;
  13110. uniforms.bumpScale.value = material.bumpScale;
  13111. }
  13112. if ( material.normalMap ) {
  13113. uniforms.normalMap.value = material.normalMap;
  13114. uniforms.normalScale.value.copy( material.normalScale );
  13115. }
  13116. if ( material.displacementMap ) {
  13117. uniforms.displacementMap.value = material.displacementMap;
  13118. uniforms.displacementScale.value = material.displacementScale;
  13119. uniforms.displacementBias.value = material.displacementBias;
  13120. }
  13121. if ( material.envMap ) {
  13122. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13123. uniforms.envMapIntensity.value = material.envMapIntensity;
  13124. }
  13125. }
  13126. function refreshUniformsPhysical( uniforms, material ) {
  13127. uniforms.clearCoat.value = material.clearCoat;
  13128. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13129. refreshUniformsStandard( uniforms, material );
  13130. }
  13131. function refreshUniformsNormal( uniforms, material ) {
  13132. if ( material.bumpMap ) {
  13133. uniforms.bumpMap.value = material.bumpMap;
  13134. uniforms.bumpScale.value = material.bumpScale;
  13135. }
  13136. if ( material.normalMap ) {
  13137. uniforms.normalMap.value = material.normalMap;
  13138. uniforms.normalScale.value.copy( material.normalScale );
  13139. }
  13140. if ( material.displacementMap ) {
  13141. uniforms.displacementMap.value = material.displacementMap;
  13142. uniforms.displacementScale.value = material.displacementScale;
  13143. uniforms.displacementBias.value = material.displacementBias;
  13144. }
  13145. }
  13146. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13147. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13148. uniforms.ambientLightColor.needsUpdate = value;
  13149. uniforms.directionalLights.needsUpdate = value;
  13150. uniforms.pointLights.needsUpdate = value;
  13151. uniforms.spotLights.needsUpdate = value;
  13152. uniforms.rectAreaLights.needsUpdate = value;
  13153. uniforms.hemisphereLights.needsUpdate = value;
  13154. }
  13155. // Lighting
  13156. function setupShadows( lights ) {
  13157. var lightShadowsLength = 0;
  13158. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  13159. var light = lights[ i ];
  13160. if ( light.castShadow ) {
  13161. _lights.shadows[ lightShadowsLength ] = light;
  13162. lightShadowsLength ++;
  13163. }
  13164. }
  13165. _lights.shadows.length = lightShadowsLength;
  13166. }
  13167. function setupLights( lights, camera ) {
  13168. var l, ll, light, shadow,
  13169. r = 0, g = 0, b = 0,
  13170. color,
  13171. intensity,
  13172. distance,
  13173. shadowMap,
  13174. viewMatrix = camera.matrixWorldInverse,
  13175. directionalLength = 0,
  13176. pointLength = 0,
  13177. spotLength = 0,
  13178. rectAreaLength = 0,
  13179. hemiLength = 0;
  13180. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13181. light = lights[ l ];
  13182. color = light.color;
  13183. intensity = light.intensity;
  13184. distance = light.distance;
  13185. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13186. if ( light.isAmbientLight ) {
  13187. r += color.r * intensity;
  13188. g += color.g * intensity;
  13189. b += color.b * intensity;
  13190. } else if ( light.isDirectionalLight ) {
  13191. var uniforms = lightCache.get( light );
  13192. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13193. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13194. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13195. uniforms.direction.sub( _vector3 );
  13196. uniforms.direction.transformDirection( viewMatrix );
  13197. uniforms.shadow = light.castShadow;
  13198. if ( light.castShadow ) {
  13199. shadow = light.shadow;
  13200. uniforms.shadowBias = shadow.bias;
  13201. uniforms.shadowRadius = shadow.radius;
  13202. uniforms.shadowMapSize = shadow.mapSize;
  13203. }
  13204. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  13205. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13206. _lights.directional[ directionalLength ] = uniforms;
  13207. directionalLength ++;
  13208. } else if ( light.isSpotLight ) {
  13209. var uniforms = lightCache.get( light );
  13210. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13211. uniforms.position.applyMatrix4( viewMatrix );
  13212. uniforms.color.copy( color ).multiplyScalar( intensity );
  13213. uniforms.distance = distance;
  13214. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13215. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13216. uniforms.direction.sub( _vector3 );
  13217. uniforms.direction.transformDirection( viewMatrix );
  13218. uniforms.coneCos = Math.cos( light.angle );
  13219. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13220. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13221. uniforms.shadow = light.castShadow;
  13222. if ( light.castShadow ) {
  13223. shadow = light.shadow;
  13224. uniforms.shadowBias = shadow.bias;
  13225. uniforms.shadowRadius = shadow.radius;
  13226. uniforms.shadowMapSize = shadow.mapSize;
  13227. }
  13228. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13229. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13230. _lights.spot[ spotLength ] = uniforms;
  13231. spotLength ++;
  13232. } else if ( light.isRectAreaLight ) {
  13233. var uniforms = lightCache.get( light );
  13234. // (a) intensity controls irradiance of entire light
  13235. uniforms.color
  13236. .copy( color )
  13237. .multiplyScalar( intensity / ( light.width * light.height ) );
  13238. // (b) intensity controls the radiance per light area
  13239. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13240. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13241. uniforms.position.applyMatrix4( viewMatrix );
  13242. // extract local rotation of light to derive width/height half vectors
  13243. _matrix42.identity();
  13244. _matrix4.copy( light.matrixWorld );
  13245. _matrix4.premultiply( viewMatrix );
  13246. _matrix42.extractRotation( _matrix4 );
  13247. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13248. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13249. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13250. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13251. // TODO (abelnation): RectAreaLight distance?
  13252. // uniforms.distance = distance;
  13253. _lights.rectArea[ rectAreaLength ] = uniforms;
  13254. rectAreaLength ++;
  13255. } else if ( light.isPointLight ) {
  13256. var uniforms = lightCache.get( light );
  13257. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13258. uniforms.position.applyMatrix4( viewMatrix );
  13259. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13260. uniforms.distance = light.distance;
  13261. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13262. uniforms.shadow = light.castShadow;
  13263. if ( light.castShadow ) {
  13264. shadow = light.shadow;
  13265. uniforms.shadowBias = shadow.bias;
  13266. uniforms.shadowRadius = shadow.radius;
  13267. uniforms.shadowMapSize = shadow.mapSize;
  13268. }
  13269. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13270. _lights.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13271. _lights.point[ pointLength ] = uniforms;
  13272. pointLength ++;
  13273. } else if ( light.isHemisphereLight ) {
  13274. var uniforms = lightCache.get( light );
  13275. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13276. uniforms.direction.transformDirection( viewMatrix );
  13277. uniforms.direction.normalize();
  13278. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13279. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13280. _lights.hemi[ hemiLength ] = uniforms;
  13281. hemiLength ++;
  13282. }
  13283. }
  13284. _lights.ambient[ 0 ] = r;
  13285. _lights.ambient[ 1 ] = g;
  13286. _lights.ambient[ 2 ] = b;
  13287. _lights.directional.length = directionalLength;
  13288. _lights.spot.length = spotLength;
  13289. _lights.rectArea.length = rectAreaLength;
  13290. _lights.point.length = pointLength;
  13291. _lights.hemi.length = hemiLength;
  13292. // TODO (sam-g-steel) why aren't we using join
  13293. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13294. }
  13295. // GL state setting
  13296. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13297. state.setCullFace( cullFace );
  13298. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13299. };
  13300. // Textures
  13301. function allocTextureUnit() {
  13302. var textureUnit = _usedTextureUnits;
  13303. if ( textureUnit >= capabilities.maxTextures ) {
  13304. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13305. }
  13306. _usedTextureUnits += 1;
  13307. return textureUnit;
  13308. }
  13309. this.allocTextureUnit = allocTextureUnit;
  13310. // this.setTexture2D = setTexture2D;
  13311. this.setTexture2D = ( function () {
  13312. var warned = false;
  13313. // backwards compatibility: peel texture.texture
  13314. return function setTexture2D( texture, slot ) {
  13315. if ( texture && texture.isWebGLRenderTarget ) {
  13316. if ( ! warned ) {
  13317. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13318. warned = true;
  13319. }
  13320. texture = texture.texture;
  13321. }
  13322. textures.setTexture2D( texture, slot );
  13323. };
  13324. }() );
  13325. this.setTexture = ( function () {
  13326. var warned = false;
  13327. return function setTexture( texture, slot ) {
  13328. if ( ! warned ) {
  13329. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13330. warned = true;
  13331. }
  13332. textures.setTexture2D( texture, slot );
  13333. };
  13334. }() );
  13335. this.setTextureCube = ( function () {
  13336. var warned = false;
  13337. return function setTextureCube( texture, slot ) {
  13338. // backwards compatibility: peel texture.texture
  13339. if ( texture && texture.isWebGLRenderTargetCube ) {
  13340. if ( ! warned ) {
  13341. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13342. warned = true;
  13343. }
  13344. texture = texture.texture;
  13345. }
  13346. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13347. // TODO: unify these code paths
  13348. if ( ( texture && texture.isCubeTexture ) ||
  13349. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13350. // CompressedTexture can have Array in image :/
  13351. // this function alone should take care of cube textures
  13352. textures.setTextureCube( texture, slot );
  13353. } else {
  13354. // assumed: texture property of THREE.WebGLRenderTargetCube
  13355. textures.setTextureCubeDynamic( texture, slot );
  13356. }
  13357. };
  13358. }() );
  13359. this.getRenderTarget = function () {
  13360. return _currentRenderTarget;
  13361. };
  13362. this.setRenderTarget = function ( renderTarget ) {
  13363. _currentRenderTarget = renderTarget;
  13364. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13365. textures.setupRenderTarget( renderTarget );
  13366. }
  13367. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13368. var framebuffer;
  13369. if ( renderTarget ) {
  13370. var renderTargetProperties = properties.get( renderTarget );
  13371. if ( isCube ) {
  13372. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13373. } else {
  13374. framebuffer = renderTargetProperties.__webglFramebuffer;
  13375. }
  13376. _currentScissor.copy( renderTarget.scissor );
  13377. _currentScissorTest = renderTarget.scissorTest;
  13378. _currentViewport.copy( renderTarget.viewport );
  13379. } else {
  13380. framebuffer = null;
  13381. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13382. _currentScissorTest = _scissorTest;
  13383. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13384. }
  13385. if ( _currentFramebuffer !== framebuffer ) {
  13386. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13387. _currentFramebuffer = framebuffer;
  13388. }
  13389. state.scissor( _currentScissor );
  13390. state.setScissorTest( _currentScissorTest );
  13391. state.viewport( _currentViewport );
  13392. if ( isCube ) {
  13393. var textureProperties = properties.get( renderTarget.texture );
  13394. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13395. }
  13396. };
  13397. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13398. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13399. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13400. return;
  13401. }
  13402. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13403. if ( framebuffer ) {
  13404. var restore = false;
  13405. if ( framebuffer !== _currentFramebuffer ) {
  13406. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13407. restore = true;
  13408. }
  13409. try {
  13410. var texture = renderTarget.texture;
  13411. var textureFormat = texture.format;
  13412. var textureType = texture.type;
  13413. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13414. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13415. return;
  13416. }
  13417. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13418. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13419. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13420. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13421. return;
  13422. }
  13423. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13424. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13425. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13426. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13427. }
  13428. } else {
  13429. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13430. }
  13431. } finally {
  13432. if ( restore ) {
  13433. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13434. }
  13435. }
  13436. }
  13437. };
  13438. // Map three.js constants to WebGL constants
  13439. function paramThreeToGL( p ) {
  13440. var extension;
  13441. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13442. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13443. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13444. if ( p === NearestFilter ) return _gl.NEAREST;
  13445. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13446. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13447. if ( p === LinearFilter ) return _gl.LINEAR;
  13448. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13449. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13450. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13451. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13452. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13453. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13454. if ( p === ByteType ) return _gl.BYTE;
  13455. if ( p === ShortType ) return _gl.SHORT;
  13456. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13457. if ( p === IntType ) return _gl.INT;
  13458. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13459. if ( p === FloatType ) return _gl.FLOAT;
  13460. if ( p === HalfFloatType ) {
  13461. extension = extensions.get( 'OES_texture_half_float' );
  13462. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13463. }
  13464. if ( p === AlphaFormat ) return _gl.ALPHA;
  13465. if ( p === RGBFormat ) return _gl.RGB;
  13466. if ( p === RGBAFormat ) return _gl.RGBA;
  13467. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13468. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13469. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13470. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13471. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13472. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13473. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13474. if ( p === ZeroFactor ) return _gl.ZERO;
  13475. if ( p === OneFactor ) return _gl.ONE;
  13476. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13477. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13478. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13479. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13480. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13481. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13482. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13483. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13484. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13485. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13486. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13487. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13488. if ( extension !== null ) {
  13489. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13490. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13491. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13492. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13493. }
  13494. }
  13495. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13496. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13497. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13498. if ( extension !== null ) {
  13499. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13500. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13501. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13502. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13503. }
  13504. }
  13505. if ( p === RGB_ETC1_Format ) {
  13506. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13507. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13508. }
  13509. if ( p === MinEquation || p === MaxEquation ) {
  13510. extension = extensions.get( 'EXT_blend_minmax' );
  13511. if ( extension !== null ) {
  13512. if ( p === MinEquation ) return extension.MIN_EXT;
  13513. if ( p === MaxEquation ) return extension.MAX_EXT;
  13514. }
  13515. }
  13516. if ( p === UnsignedInt248Type ) {
  13517. extension = extensions.get( 'WEBGL_depth_texture' );
  13518. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13519. }
  13520. return 0;
  13521. }
  13522. }
  13523. /**
  13524. * @author mrdoob / http://mrdoob.com/
  13525. * @author alteredq / http://alteredqualia.com/
  13526. */
  13527. function FogExp2 ( color, density ) {
  13528. this.name = '';
  13529. this.color = new Color( color );
  13530. this.density = ( density !== undefined ) ? density : 0.00025;
  13531. }
  13532. FogExp2.prototype.isFogExp2 = true;
  13533. FogExp2.prototype.clone = function () {
  13534. return new FogExp2( this.color.getHex(), this.density );
  13535. };
  13536. FogExp2.prototype.toJSON = function ( meta ) {
  13537. return {
  13538. type: 'FogExp2',
  13539. color: this.color.getHex(),
  13540. density: this.density
  13541. };
  13542. };
  13543. /**
  13544. * @author mrdoob / http://mrdoob.com/
  13545. * @author alteredq / http://alteredqualia.com/
  13546. */
  13547. function Fog ( color, near, far ) {
  13548. this.name = '';
  13549. this.color = new Color( color );
  13550. this.near = ( near !== undefined ) ? near : 1;
  13551. this.far = ( far !== undefined ) ? far : 1000;
  13552. }
  13553. Fog.prototype.isFog = true;
  13554. Fog.prototype.clone = function () {
  13555. return new Fog( this.color.getHex(), this.near, this.far );
  13556. };
  13557. Fog.prototype.toJSON = function ( meta ) {
  13558. return {
  13559. type: 'Fog',
  13560. color: this.color.getHex(),
  13561. near: this.near,
  13562. far: this.far
  13563. };
  13564. };
  13565. /**
  13566. * @author mrdoob / http://mrdoob.com/
  13567. */
  13568. function Scene () {
  13569. Object3D.call( this );
  13570. this.type = 'Scene';
  13571. this.background = null;
  13572. this.fog = null;
  13573. this.overrideMaterial = null;
  13574. this.autoUpdate = true; // checked by the renderer
  13575. }
  13576. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13577. constructor: Scene,
  13578. copy: function ( source, recursive ) {
  13579. Object3D.prototype.copy.call( this, source, recursive );
  13580. if ( source.background !== null ) this.background = source.background.clone();
  13581. if ( source.fog !== null ) this.fog = source.fog.clone();
  13582. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13583. this.autoUpdate = source.autoUpdate;
  13584. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13585. return this;
  13586. },
  13587. toJSON: function ( meta ) {
  13588. var data = Object3D.prototype.toJSON.call( this, meta );
  13589. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13590. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13591. return data;
  13592. }
  13593. } );
  13594. /**
  13595. * @author mikael emtinger / http://gomo.se/
  13596. * @author alteredq / http://alteredqualia.com/
  13597. */
  13598. function LensFlare( texture, size, distance, blending, color ) {
  13599. Object3D.call( this );
  13600. this.lensFlares = [];
  13601. this.positionScreen = new Vector3();
  13602. this.customUpdateCallback = undefined;
  13603. if ( texture !== undefined ) {
  13604. this.add( texture, size, distance, blending, color );
  13605. }
  13606. }
  13607. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13608. constructor: LensFlare,
  13609. isLensFlare: true,
  13610. copy: function ( source ) {
  13611. Object3D.prototype.copy.call( this, source );
  13612. this.positionScreen.copy( source.positionScreen );
  13613. this.customUpdateCallback = source.customUpdateCallback;
  13614. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13615. this.lensFlares.push( source.lensFlares[ i ] );
  13616. }
  13617. return this;
  13618. },
  13619. add: function ( texture, size, distance, blending, color, opacity ) {
  13620. if ( size === undefined ) size = - 1;
  13621. if ( distance === undefined ) distance = 0;
  13622. if ( opacity === undefined ) opacity = 1;
  13623. if ( color === undefined ) color = new Color( 0xffffff );
  13624. if ( blending === undefined ) blending = NormalBlending;
  13625. distance = Math.min( distance, Math.max( 0, distance ) );
  13626. this.lensFlares.push( {
  13627. texture: texture, // THREE.Texture
  13628. size: size, // size in pixels (-1 = use texture.width)
  13629. distance: distance, // distance (0-1) from light source (0=at light source)
  13630. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13631. scale: 1, // scale
  13632. rotation: 0, // rotation
  13633. opacity: opacity, // opacity
  13634. color: color, // color
  13635. blending: blending // blending
  13636. } );
  13637. },
  13638. /*
  13639. * Update lens flares update positions on all flares based on the screen position
  13640. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13641. */
  13642. updateLensFlares: function () {
  13643. var f, fl = this.lensFlares.length;
  13644. var flare;
  13645. var vecX = - this.positionScreen.x * 2;
  13646. var vecY = - this.positionScreen.y * 2;
  13647. for ( f = 0; f < fl; f ++ ) {
  13648. flare = this.lensFlares[ f ];
  13649. flare.x = this.positionScreen.x + vecX * flare.distance;
  13650. flare.y = this.positionScreen.y + vecY * flare.distance;
  13651. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13652. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13653. }
  13654. }
  13655. } );
  13656. /**
  13657. * @author alteredq / http://alteredqualia.com/
  13658. *
  13659. * parameters = {
  13660. * color: <hex>,
  13661. * opacity: <float>,
  13662. * map: new THREE.Texture( <Image> ),
  13663. *
  13664. * uvOffset: new THREE.Vector2(),
  13665. * uvScale: new THREE.Vector2()
  13666. * }
  13667. */
  13668. function SpriteMaterial( parameters ) {
  13669. Material.call( this );
  13670. this.type = 'SpriteMaterial';
  13671. this.color = new Color( 0xffffff );
  13672. this.map = null;
  13673. this.rotation = 0;
  13674. this.fog = false;
  13675. this.lights = false;
  13676. this.setValues( parameters );
  13677. }
  13678. SpriteMaterial.prototype = Object.create( Material.prototype );
  13679. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13680. SpriteMaterial.prototype.isSpriteMaterial = true;
  13681. SpriteMaterial.prototype.copy = function ( source ) {
  13682. Material.prototype.copy.call( this, source );
  13683. this.color.copy( source.color );
  13684. this.map = source.map;
  13685. this.rotation = source.rotation;
  13686. return this;
  13687. };
  13688. /**
  13689. * @author mikael emtinger / http://gomo.se/
  13690. * @author alteredq / http://alteredqualia.com/
  13691. */
  13692. function Sprite( material ) {
  13693. Object3D.call( this );
  13694. this.type = 'Sprite';
  13695. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13696. }
  13697. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13698. constructor: Sprite,
  13699. isSprite: true,
  13700. raycast: ( function () {
  13701. var intersectPoint = new Vector3();
  13702. var worldPosition = new Vector3();
  13703. var worldScale = new Vector3();
  13704. return function raycast( raycaster, intersects ) {
  13705. worldPosition.setFromMatrixPosition( this.matrixWorld );
  13706. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  13707. worldScale.setFromMatrixScale( this.matrixWorld );
  13708. var guessSizeSq = worldScale.x * worldScale.y / 4;
  13709. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  13710. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13711. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13712. intersects.push( {
  13713. distance: distance,
  13714. point: intersectPoint.clone(),
  13715. face: null,
  13716. object: this
  13717. } );
  13718. };
  13719. }() ),
  13720. clone: function () {
  13721. return new this.constructor( this.material ).copy( this );
  13722. }
  13723. } );
  13724. /**
  13725. * @author mikael emtinger / http://gomo.se/
  13726. * @author alteredq / http://alteredqualia.com/
  13727. * @author mrdoob / http://mrdoob.com/
  13728. */
  13729. function LOD() {
  13730. Object3D.call( this );
  13731. this.type = 'LOD';
  13732. Object.defineProperties( this, {
  13733. levels: {
  13734. enumerable: true,
  13735. value: []
  13736. }
  13737. } );
  13738. }
  13739. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13740. constructor: LOD,
  13741. copy: function ( source ) {
  13742. Object3D.prototype.copy.call( this, source, false );
  13743. var levels = source.levels;
  13744. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13745. var level = levels[ i ];
  13746. this.addLevel( level.object.clone(), level.distance );
  13747. }
  13748. return this;
  13749. },
  13750. addLevel: function ( object, distance ) {
  13751. if ( distance === undefined ) distance = 0;
  13752. distance = Math.abs( distance );
  13753. var levels = this.levels;
  13754. for ( var l = 0; l < levels.length; l ++ ) {
  13755. if ( distance < levels[ l ].distance ) {
  13756. break;
  13757. }
  13758. }
  13759. levels.splice( l, 0, { distance: distance, object: object } );
  13760. this.add( object );
  13761. },
  13762. getObjectForDistance: function ( distance ) {
  13763. var levels = this.levels;
  13764. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13765. if ( distance < levels[ i ].distance ) {
  13766. break;
  13767. }
  13768. }
  13769. return levels[ i - 1 ].object;
  13770. },
  13771. raycast: ( function () {
  13772. var matrixPosition = new Vector3();
  13773. return function raycast( raycaster, intersects ) {
  13774. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13775. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13776. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13777. };
  13778. }() ),
  13779. update: function () {
  13780. var v1 = new Vector3();
  13781. var v2 = new Vector3();
  13782. return function update( camera ) {
  13783. var levels = this.levels;
  13784. if ( levels.length > 1 ) {
  13785. v1.setFromMatrixPosition( camera.matrixWorld );
  13786. v2.setFromMatrixPosition( this.matrixWorld );
  13787. var distance = v1.distanceTo( v2 );
  13788. levels[ 0 ].object.visible = true;
  13789. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13790. if ( distance >= levels[ i ].distance ) {
  13791. levels[ i - 1 ].object.visible = false;
  13792. levels[ i ].object.visible = true;
  13793. } else {
  13794. break;
  13795. }
  13796. }
  13797. for ( ; i < l; i ++ ) {
  13798. levels[ i ].object.visible = false;
  13799. }
  13800. }
  13801. };
  13802. }(),
  13803. toJSON: function ( meta ) {
  13804. var data = Object3D.prototype.toJSON.call( this, meta );
  13805. data.object.levels = [];
  13806. var levels = this.levels;
  13807. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13808. var level = levels[ i ];
  13809. data.object.levels.push( {
  13810. object: level.object.uuid,
  13811. distance: level.distance
  13812. } );
  13813. }
  13814. return data;
  13815. }
  13816. } );
  13817. /**
  13818. * @author mikael emtinger / http://gomo.se/
  13819. * @author alteredq / http://alteredqualia.com/
  13820. * @author michael guerrero / http://realitymeltdown.com
  13821. * @author ikerr / http://verold.com
  13822. */
  13823. function Skeleton( bones, boneInverses ) {
  13824. // copy the bone array
  13825. bones = bones || [];
  13826. this.bones = bones.slice( 0 );
  13827. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  13828. // use the supplied bone inverses or calculate the inverses
  13829. if ( boneInverses === undefined ) {
  13830. this.calculateInverses();
  13831. } else {
  13832. if ( this.bones.length === boneInverses.length ) {
  13833. this.boneInverses = boneInverses.slice( 0 );
  13834. } else {
  13835. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  13836. this.boneInverses = [];
  13837. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13838. this.boneInverses.push( new Matrix4() );
  13839. }
  13840. }
  13841. }
  13842. }
  13843. Object.assign( Skeleton.prototype, {
  13844. calculateInverses: function () {
  13845. this.boneInverses = [];
  13846. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13847. var inverse = new Matrix4();
  13848. if ( this.bones[ i ] ) {
  13849. inverse.getInverse( this.bones[ i ].matrixWorld );
  13850. }
  13851. this.boneInverses.push( inverse );
  13852. }
  13853. },
  13854. pose: function () {
  13855. var bone, i, il;
  13856. // recover the bind-time world matrices
  13857. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13858. bone = this.bones[ i ];
  13859. if ( bone ) {
  13860. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  13861. }
  13862. }
  13863. // compute the local matrices, positions, rotations and scales
  13864. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13865. bone = this.bones[ i ];
  13866. if ( bone ) {
  13867. if ( bone.parent && bone.parent.isBone ) {
  13868. bone.matrix.getInverse( bone.parent.matrixWorld );
  13869. bone.matrix.multiply( bone.matrixWorld );
  13870. } else {
  13871. bone.matrix.copy( bone.matrixWorld );
  13872. }
  13873. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13874. }
  13875. }
  13876. },
  13877. update: ( function () {
  13878. var offsetMatrix = new Matrix4();
  13879. var identityMatrix = new Matrix4();
  13880. return function update() {
  13881. var bones = this.bones;
  13882. var boneInverses = this.boneInverses;
  13883. var boneMatrices = this.boneMatrices;
  13884. var boneTexture = this.boneTexture;
  13885. // flatten bone matrices to array
  13886. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  13887. // compute the offset between the current and the original transform
  13888. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  13889. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  13890. offsetMatrix.toArray( boneMatrices, i * 16 );
  13891. }
  13892. if ( boneTexture !== undefined ) {
  13893. boneTexture.needsUpdate = true;
  13894. }
  13895. };
  13896. } )(),
  13897. clone: function () {
  13898. return new Skeleton( this.bones, this.boneInverses );
  13899. }
  13900. } );
  13901. /**
  13902. * @author mikael emtinger / http://gomo.se/
  13903. * @author alteredq / http://alteredqualia.com/
  13904. * @author ikerr / http://verold.com
  13905. */
  13906. function Bone() {
  13907. Object3D.call( this );
  13908. this.type = 'Bone';
  13909. }
  13910. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13911. constructor: Bone,
  13912. isBone: true
  13913. } );
  13914. /**
  13915. * @author mikael emtinger / http://gomo.se/
  13916. * @author alteredq / http://alteredqualia.com/
  13917. * @author ikerr / http://verold.com
  13918. */
  13919. function SkinnedMesh( geometry, material ) {
  13920. Mesh.call( this, geometry, material );
  13921. this.type = 'SkinnedMesh';
  13922. this.bindMode = 'attached';
  13923. this.bindMatrix = new Matrix4();
  13924. this.bindMatrixInverse = new Matrix4();
  13925. var bones = this.initBones();
  13926. var skeleton = new Skeleton( bones );
  13927. this.bind( skeleton, this.matrixWorld );
  13928. this.normalizeSkinWeights();
  13929. }
  13930. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13931. constructor: SkinnedMesh,
  13932. isSkinnedMesh: true,
  13933. initBones: function () {
  13934. var bones = [], bone, gbone;
  13935. var i, il;
  13936. if ( this.geometry && this.geometry.bones !== undefined ) {
  13937. // first, create array of 'Bone' objects from geometry data
  13938. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13939. gbone = this.geometry.bones[ i ];
  13940. // create new 'Bone' object
  13941. bone = new Bone();
  13942. bones.push( bone );
  13943. // apply values
  13944. bone.name = gbone.name;
  13945. bone.position.fromArray( gbone.pos );
  13946. bone.quaternion.fromArray( gbone.rotq );
  13947. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13948. }
  13949. // second, create bone hierarchy
  13950. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13951. gbone = this.geometry.bones[ i ];
  13952. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  13953. // subsequent bones in the hierarchy
  13954. bones[ gbone.parent ].add( bones[ i ] );
  13955. } else {
  13956. // topmost bone, immediate child of the skinned mesh
  13957. this.add( bones[ i ] );
  13958. }
  13959. }
  13960. }
  13961. // now the bones are part of the scene graph and children of the skinned mesh.
  13962. // let's update the corresponding matrices
  13963. this.updateMatrixWorld( true );
  13964. return bones;
  13965. },
  13966. bind: function ( skeleton, bindMatrix ) {
  13967. this.skeleton = skeleton;
  13968. if ( bindMatrix === undefined ) {
  13969. this.updateMatrixWorld( true );
  13970. this.skeleton.calculateInverses();
  13971. bindMatrix = this.matrixWorld;
  13972. }
  13973. this.bindMatrix.copy( bindMatrix );
  13974. this.bindMatrixInverse.getInverse( bindMatrix );
  13975. },
  13976. pose: function () {
  13977. this.skeleton.pose();
  13978. },
  13979. normalizeSkinWeights: function () {
  13980. var scale, i;
  13981. if ( this.geometry && this.geometry.isGeometry ) {
  13982. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13983. var sw = this.geometry.skinWeights[ i ];
  13984. scale = 1.0 / sw.lengthManhattan();
  13985. if ( scale !== Infinity ) {
  13986. sw.multiplyScalar( scale );
  13987. } else {
  13988. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13989. }
  13990. }
  13991. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13992. var vec = new Vector4();
  13993. var skinWeight = this.geometry.attributes.skinWeight;
  13994. for ( i = 0; i < skinWeight.count; i ++ ) {
  13995. vec.x = skinWeight.getX( i );
  13996. vec.y = skinWeight.getY( i );
  13997. vec.z = skinWeight.getZ( i );
  13998. vec.w = skinWeight.getW( i );
  13999. scale = 1.0 / vec.lengthManhattan();
  14000. if ( scale !== Infinity ) {
  14001. vec.multiplyScalar( scale );
  14002. } else {
  14003. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14004. }
  14005. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14006. }
  14007. }
  14008. },
  14009. updateMatrixWorld: function ( force ) {
  14010. Mesh.prototype.updateMatrixWorld.call( this, force );
  14011. if ( this.bindMode === 'attached' ) {
  14012. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14013. } else if ( this.bindMode === 'detached' ) {
  14014. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14015. } else {
  14016. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14017. }
  14018. },
  14019. clone: function () {
  14020. return new this.constructor( this.geometry, this.material ).copy( this );
  14021. }
  14022. } );
  14023. /**
  14024. * @author mrdoob / http://mrdoob.com/
  14025. * @author alteredq / http://alteredqualia.com/
  14026. *
  14027. * parameters = {
  14028. * color: <hex>,
  14029. * opacity: <float>,
  14030. *
  14031. * linewidth: <float>,
  14032. * linecap: "round",
  14033. * linejoin: "round"
  14034. * }
  14035. */
  14036. function LineBasicMaterial( parameters ) {
  14037. Material.call( this );
  14038. this.type = 'LineBasicMaterial';
  14039. this.color = new Color( 0xffffff );
  14040. this.linewidth = 1;
  14041. this.linecap = 'round';
  14042. this.linejoin = 'round';
  14043. this.lights = false;
  14044. this.setValues( parameters );
  14045. }
  14046. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14047. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14048. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14049. LineBasicMaterial.prototype.copy = function ( source ) {
  14050. Material.prototype.copy.call( this, source );
  14051. this.color.copy( source.color );
  14052. this.linewidth = source.linewidth;
  14053. this.linecap = source.linecap;
  14054. this.linejoin = source.linejoin;
  14055. return this;
  14056. };
  14057. /**
  14058. * @author mrdoob / http://mrdoob.com/
  14059. */
  14060. function Line( geometry, material, mode ) {
  14061. if ( mode === 1 ) {
  14062. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14063. return new LineSegments( geometry, material );
  14064. }
  14065. Object3D.call( this );
  14066. this.type = 'Line';
  14067. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14068. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14069. }
  14070. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14071. constructor: Line,
  14072. isLine: true,
  14073. raycast: ( function () {
  14074. var inverseMatrix = new Matrix4();
  14075. var ray = new Ray();
  14076. var sphere = new Sphere();
  14077. return function raycast( raycaster, intersects ) {
  14078. var precision = raycaster.linePrecision;
  14079. var precisionSq = precision * precision;
  14080. var geometry = this.geometry;
  14081. var matrixWorld = this.matrixWorld;
  14082. // Checking boundingSphere distance to ray
  14083. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14084. sphere.copy( geometry.boundingSphere );
  14085. sphere.applyMatrix4( matrixWorld );
  14086. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14087. //
  14088. inverseMatrix.getInverse( matrixWorld );
  14089. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14090. var vStart = new Vector3();
  14091. var vEnd = new Vector3();
  14092. var interSegment = new Vector3();
  14093. var interRay = new Vector3();
  14094. var step = (this && this.isLineSegments) ? 2 : 1;
  14095. if ( geometry.isBufferGeometry ) {
  14096. var index = geometry.index;
  14097. var attributes = geometry.attributes;
  14098. var positions = attributes.position.array;
  14099. if ( index !== null ) {
  14100. var indices = index.array;
  14101. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14102. var a = indices[ i ];
  14103. var b = indices[ i + 1 ];
  14104. vStart.fromArray( positions, a * 3 );
  14105. vEnd.fromArray( positions, b * 3 );
  14106. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14107. if ( distSq > precisionSq ) continue;
  14108. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14109. var distance = raycaster.ray.origin.distanceTo( interRay );
  14110. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14111. intersects.push( {
  14112. distance: distance,
  14113. // What do we want? intersection point on the ray or on the segment??
  14114. // point: raycaster.ray.at( distance ),
  14115. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14116. index: i,
  14117. face: null,
  14118. faceIndex: null,
  14119. object: this
  14120. } );
  14121. }
  14122. } else {
  14123. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14124. vStart.fromArray( positions, 3 * i );
  14125. vEnd.fromArray( positions, 3 * i + 3 );
  14126. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14127. if ( distSq > precisionSq ) continue;
  14128. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14129. var distance = raycaster.ray.origin.distanceTo( interRay );
  14130. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14131. intersects.push( {
  14132. distance: distance,
  14133. // What do we want? intersection point on the ray or on the segment??
  14134. // point: raycaster.ray.at( distance ),
  14135. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14136. index: i,
  14137. face: null,
  14138. faceIndex: null,
  14139. object: this
  14140. } );
  14141. }
  14142. }
  14143. } else if ( geometry.isGeometry ) {
  14144. var vertices = geometry.vertices;
  14145. var nbVertices = vertices.length;
  14146. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14147. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14148. if ( distSq > precisionSq ) continue;
  14149. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14150. var distance = raycaster.ray.origin.distanceTo( interRay );
  14151. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14152. intersects.push( {
  14153. distance: distance,
  14154. // What do we want? intersection point on the ray or on the segment??
  14155. // point: raycaster.ray.at( distance ),
  14156. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14157. index: i,
  14158. face: null,
  14159. faceIndex: null,
  14160. object: this
  14161. } );
  14162. }
  14163. }
  14164. };
  14165. }() ),
  14166. clone: function () {
  14167. return new this.constructor( this.geometry, this.material ).copy( this );
  14168. }
  14169. } );
  14170. /**
  14171. * @author mrdoob / http://mrdoob.com/
  14172. */
  14173. function LineSegments( geometry, material ) {
  14174. Line.call( this, geometry, material );
  14175. this.type = 'LineSegments';
  14176. }
  14177. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14178. constructor: LineSegments,
  14179. isLineSegments: true
  14180. } );
  14181. /**
  14182. * @author mgreter / http://github.com/mgreter
  14183. */
  14184. function LineLoop( geometry, material ) {
  14185. Line.call( this, geometry, material );
  14186. this.type = 'LineLoop';
  14187. }
  14188. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14189. constructor: LineLoop,
  14190. isLineLoop: true,
  14191. } );
  14192. /**
  14193. * @author mrdoob / http://mrdoob.com/
  14194. * @author alteredq / http://alteredqualia.com/
  14195. *
  14196. * parameters = {
  14197. * color: <hex>,
  14198. * opacity: <float>,
  14199. * map: new THREE.Texture( <Image> ),
  14200. *
  14201. * size: <float>,
  14202. * sizeAttenuation: <bool>
  14203. * }
  14204. */
  14205. function PointsMaterial( parameters ) {
  14206. Material.call( this );
  14207. this.type = 'PointsMaterial';
  14208. this.color = new Color( 0xffffff );
  14209. this.map = null;
  14210. this.size = 1;
  14211. this.sizeAttenuation = true;
  14212. this.lights = false;
  14213. this.setValues( parameters );
  14214. }
  14215. PointsMaterial.prototype = Object.create( Material.prototype );
  14216. PointsMaterial.prototype.constructor = PointsMaterial;
  14217. PointsMaterial.prototype.isPointsMaterial = true;
  14218. PointsMaterial.prototype.copy = function ( source ) {
  14219. Material.prototype.copy.call( this, source );
  14220. this.color.copy( source.color );
  14221. this.map = source.map;
  14222. this.size = source.size;
  14223. this.sizeAttenuation = source.sizeAttenuation;
  14224. return this;
  14225. };
  14226. /**
  14227. * @author alteredq / http://alteredqualia.com/
  14228. */
  14229. function Points( geometry, material ) {
  14230. Object3D.call( this );
  14231. this.type = 'Points';
  14232. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14233. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14234. }
  14235. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14236. constructor: Points,
  14237. isPoints: true,
  14238. raycast: ( function () {
  14239. var inverseMatrix = new Matrix4();
  14240. var ray = new Ray();
  14241. var sphere = new Sphere();
  14242. return function raycast( raycaster, intersects ) {
  14243. var object = this;
  14244. var geometry = this.geometry;
  14245. var matrixWorld = this.matrixWorld;
  14246. var threshold = raycaster.params.Points.threshold;
  14247. // Checking boundingSphere distance to ray
  14248. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14249. sphere.copy( geometry.boundingSphere );
  14250. sphere.applyMatrix4( matrixWorld );
  14251. sphere.radius += threshold;
  14252. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14253. //
  14254. inverseMatrix.getInverse( matrixWorld );
  14255. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14256. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14257. var localThresholdSq = localThreshold * localThreshold;
  14258. var position = new Vector3();
  14259. function testPoint( point, index ) {
  14260. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14261. if ( rayPointDistanceSq < localThresholdSq ) {
  14262. var intersectPoint = ray.closestPointToPoint( point );
  14263. intersectPoint.applyMatrix4( matrixWorld );
  14264. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14265. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14266. intersects.push( {
  14267. distance: distance,
  14268. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14269. point: intersectPoint.clone(),
  14270. index: index,
  14271. face: null,
  14272. object: object
  14273. } );
  14274. }
  14275. }
  14276. if ( geometry.isBufferGeometry ) {
  14277. var index = geometry.index;
  14278. var attributes = geometry.attributes;
  14279. var positions = attributes.position.array;
  14280. if ( index !== null ) {
  14281. var indices = index.array;
  14282. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14283. var a = indices[ i ];
  14284. position.fromArray( positions, a * 3 );
  14285. testPoint( position, a );
  14286. }
  14287. } else {
  14288. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14289. position.fromArray( positions, i * 3 );
  14290. testPoint( position, i );
  14291. }
  14292. }
  14293. } else {
  14294. var vertices = geometry.vertices;
  14295. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14296. testPoint( vertices[ i ], i );
  14297. }
  14298. }
  14299. };
  14300. }() ),
  14301. clone: function () {
  14302. return new this.constructor( this.geometry, this.material ).copy( this );
  14303. }
  14304. } );
  14305. /**
  14306. * @author mrdoob / http://mrdoob.com/
  14307. */
  14308. function Group() {
  14309. Object3D.call( this );
  14310. this.type = 'Group';
  14311. }
  14312. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14313. constructor: Group
  14314. } );
  14315. /**
  14316. * @author mrdoob / http://mrdoob.com/
  14317. */
  14318. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14319. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14320. this.generateMipmaps = false;
  14321. var scope = this;
  14322. function update() {
  14323. requestAnimationFrame( update );
  14324. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14325. scope.needsUpdate = true;
  14326. }
  14327. }
  14328. update();
  14329. }
  14330. VideoTexture.prototype = Object.create( Texture.prototype );
  14331. VideoTexture.prototype.constructor = VideoTexture;
  14332. /**
  14333. * @author alteredq / http://alteredqualia.com/
  14334. */
  14335. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14336. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14337. this.image = { width: width, height: height };
  14338. this.mipmaps = mipmaps;
  14339. // no flipping for cube textures
  14340. // (also flipping doesn't work for compressed textures )
  14341. this.flipY = false;
  14342. // can't generate mipmaps for compressed textures
  14343. // mips must be embedded in DDS files
  14344. this.generateMipmaps = false;
  14345. }
  14346. CompressedTexture.prototype = Object.create( Texture.prototype );
  14347. CompressedTexture.prototype.constructor = CompressedTexture;
  14348. CompressedTexture.prototype.isCompressedTexture = true;
  14349. /**
  14350. * @author mrdoob / http://mrdoob.com/
  14351. */
  14352. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14353. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14354. this.needsUpdate = true;
  14355. }
  14356. CanvasTexture.prototype = Object.create( Texture.prototype );
  14357. CanvasTexture.prototype.constructor = CanvasTexture;
  14358. /**
  14359. * @author Matt DesLauriers / @mattdesl
  14360. * @author atix / arthursilber.de
  14361. */
  14362. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14363. format = format !== undefined ? format : DepthFormat;
  14364. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14365. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14366. }
  14367. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14368. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14369. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14370. this.image = { width: width, height: height };
  14371. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14372. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14373. this.flipY = false;
  14374. this.generateMipmaps = false;
  14375. }
  14376. DepthTexture.prototype = Object.create( Texture.prototype );
  14377. DepthTexture.prototype.constructor = DepthTexture;
  14378. DepthTexture.prototype.isDepthTexture = true;
  14379. /**
  14380. * @author mrdoob / http://mrdoob.com/
  14381. * @author Mugen87 / https://github.com/Mugen87
  14382. */
  14383. function WireframeGeometry( geometry ) {
  14384. BufferGeometry.call( this );
  14385. this.type = 'WireframeGeometry';
  14386. // buffer
  14387. var vertices = [];
  14388. // helper variables
  14389. var i, j, l, o, ol;
  14390. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14391. var key, keys = [ 'a', 'b', 'c' ];
  14392. var vertex;
  14393. // different logic for Geometry and BufferGeometry
  14394. if ( geometry && geometry.isGeometry ) {
  14395. // create a data structure that contains all edges without duplicates
  14396. var faces = geometry.faces;
  14397. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14398. var face = faces[ i ];
  14399. for ( j = 0; j < 3; j ++ ) {
  14400. edge1 = face[ keys[ j ] ];
  14401. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14402. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14403. edge[ 1 ] = Math.max( edge1, edge2 );
  14404. key = edge[ 0 ] + ',' + edge[ 1 ];
  14405. if ( edges[ key ] === undefined ) {
  14406. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14407. }
  14408. }
  14409. }
  14410. // generate vertices
  14411. for ( key in edges ) {
  14412. e = edges[ key ];
  14413. vertex = geometry.vertices[ e.index1 ];
  14414. vertices.push( vertex.x, vertex.y, vertex.z );
  14415. vertex = geometry.vertices[ e.index2 ];
  14416. vertices.push( vertex.x, vertex.y, vertex.z );
  14417. }
  14418. } else if ( geometry && geometry.isBufferGeometry ) {
  14419. var position, indices, groups;
  14420. var group, start, count;
  14421. var index1, index2;
  14422. vertex = new Vector3();
  14423. if ( geometry.index !== null ) {
  14424. // indexed BufferGeometry
  14425. position = geometry.attributes.position;
  14426. indices = geometry.index;
  14427. groups = geometry.groups;
  14428. if ( groups.length === 0 ) {
  14429. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14430. }
  14431. // create a data structure that contains all eges without duplicates
  14432. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14433. group = groups[ o ];
  14434. start = group.start;
  14435. count = group.count;
  14436. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14437. for ( j = 0; j < 3; j ++ ) {
  14438. edge1 = indices.getX( i + j );
  14439. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14440. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14441. edge[ 1 ] = Math.max( edge1, edge2 );
  14442. key = edge[ 0 ] + ',' + edge[ 1 ];
  14443. if ( edges[ key ] === undefined ) {
  14444. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14445. }
  14446. }
  14447. }
  14448. }
  14449. // generate vertices
  14450. for ( key in edges ) {
  14451. e = edges[ key ];
  14452. vertex.fromBufferAttribute( position, e.index1 );
  14453. vertices.push( vertex.x, vertex.y, vertex.z );
  14454. vertex.fromBufferAttribute( position, e.index2 );
  14455. vertices.push( vertex.x, vertex.y, vertex.z );
  14456. }
  14457. } else {
  14458. // non-indexed BufferGeometry
  14459. position = geometry.attributes.position;
  14460. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14461. for ( j = 0; j < 3; j ++ ) {
  14462. // three edges per triangle, an edge is represented as (index1, index2)
  14463. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14464. index1 = 3 * i + j;
  14465. vertex.fromBufferAttribute( position, index1 );
  14466. vertices.push( vertex.x, vertex.y, vertex.z );
  14467. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14468. vertex.fromBufferAttribute( position, index2 );
  14469. vertices.push( vertex.x, vertex.y, vertex.z );
  14470. }
  14471. }
  14472. }
  14473. }
  14474. // build geometry
  14475. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14476. }
  14477. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14478. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14479. /**
  14480. * @author zz85 / https://github.com/zz85
  14481. * @author Mugen87 / https://github.com/Mugen87
  14482. *
  14483. * Parametric Surfaces Geometry
  14484. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14485. */
  14486. // ParametricGeometry
  14487. function ParametricGeometry( func, slices, stacks ) {
  14488. Geometry.call( this );
  14489. this.type = 'ParametricGeometry';
  14490. this.parameters = {
  14491. func: func,
  14492. slices: slices,
  14493. stacks: stacks
  14494. };
  14495. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14496. this.mergeVertices();
  14497. }
  14498. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14499. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14500. // ParametricBufferGeometry
  14501. function ParametricBufferGeometry( func, slices, stacks ) {
  14502. BufferGeometry.call( this );
  14503. this.type = 'ParametricBufferGeometry';
  14504. this.parameters = {
  14505. func: func,
  14506. slices: slices,
  14507. stacks: stacks
  14508. };
  14509. // buffers
  14510. var indices = [];
  14511. var vertices = [];
  14512. var normals = [];
  14513. var uvs = [];
  14514. var EPS = 0.00001;
  14515. var normal = new Vector3();
  14516. var p0 = new Vector3(), p1 = new Vector3();
  14517. var pu = new Vector3(), pv = new Vector3();
  14518. var i, j;
  14519. // generate vertices, normals and uvs
  14520. var sliceCount = slices + 1;
  14521. for ( i = 0; i <= stacks; i ++ ) {
  14522. var v = i / stacks;
  14523. for ( j = 0; j <= slices; j ++ ) {
  14524. var u = j / slices;
  14525. // vertex
  14526. p0 = func( u, v, p0 );
  14527. vertices.push( p0.x, p0.y, p0.z );
  14528. // normal
  14529. // approximate tangent vectors via finite differences
  14530. if ( u - EPS >= 0 ) {
  14531. p1 = func( u - EPS, v, p1 );
  14532. pu.subVectors( p0, p1 );
  14533. } else {
  14534. p1 = func( u + EPS, v, p1 );
  14535. pu.subVectors( p1, p0 );
  14536. }
  14537. if ( v - EPS >= 0 ) {
  14538. p1 = func( u, v - EPS, p1 );
  14539. pv.subVectors( p0, p1 );
  14540. } else {
  14541. p1 = func( u, v + EPS, p1 );
  14542. pv.subVectors( p1, p0 );
  14543. }
  14544. // cross product of tangent vectors returns surface normal
  14545. normal.crossVectors( pu, pv ).normalize();
  14546. normals.push( normal.x, normal.y, normal.z );
  14547. // uv
  14548. uvs.push( u, v );
  14549. }
  14550. }
  14551. // generate indices
  14552. for ( i = 0; i < stacks; i ++ ) {
  14553. for ( j = 0; j < slices; j ++ ) {
  14554. var a = i * sliceCount + j;
  14555. var b = i * sliceCount + j + 1;
  14556. var c = ( i + 1 ) * sliceCount + j + 1;
  14557. var d = ( i + 1 ) * sliceCount + j;
  14558. // faces one and two
  14559. indices.push( a, b, d );
  14560. indices.push( b, c, d );
  14561. }
  14562. }
  14563. // build geometry
  14564. this.setIndex( indices );
  14565. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14566. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14567. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14568. }
  14569. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14570. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14571. /**
  14572. * @author clockworkgeek / https://github.com/clockworkgeek
  14573. * @author timothypratley / https://github.com/timothypratley
  14574. * @author WestLangley / http://github.com/WestLangley
  14575. * @author Mugen87 / https://github.com/Mugen87
  14576. */
  14577. // PolyhedronGeometry
  14578. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14579. Geometry.call( this );
  14580. this.type = 'PolyhedronGeometry';
  14581. this.parameters = {
  14582. vertices: vertices,
  14583. indices: indices,
  14584. radius: radius,
  14585. detail: detail
  14586. };
  14587. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14588. this.mergeVertices();
  14589. }
  14590. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14591. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14592. // PolyhedronBufferGeometry
  14593. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14594. BufferGeometry.call( this );
  14595. this.type = 'PolyhedronBufferGeometry';
  14596. this.parameters = {
  14597. vertices: vertices,
  14598. indices: indices,
  14599. radius: radius,
  14600. detail: detail
  14601. };
  14602. radius = radius || 1;
  14603. detail = detail || 0;
  14604. // default buffer data
  14605. var vertexBuffer = [];
  14606. var uvBuffer = [];
  14607. // the subdivision creates the vertex buffer data
  14608. subdivide( detail );
  14609. // all vertices should lie on a conceptual sphere with a given radius
  14610. appplyRadius( radius );
  14611. // finally, create the uv data
  14612. generateUVs();
  14613. // build non-indexed geometry
  14614. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14615. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14616. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14617. if ( detail === 0 ) {
  14618. this.computeVertexNormals(); // flat normals
  14619. } else {
  14620. this.normalizeNormals(); // smooth normals
  14621. }
  14622. // helper functions
  14623. function subdivide( detail ) {
  14624. var a = new Vector3();
  14625. var b = new Vector3();
  14626. var c = new Vector3();
  14627. // iterate over all faces and apply a subdivison with the given detail value
  14628. for ( var i = 0; i < indices.length; i += 3 ) {
  14629. // get the vertices of the face
  14630. getVertexByIndex( indices[ i + 0 ], a );
  14631. getVertexByIndex( indices[ i + 1 ], b );
  14632. getVertexByIndex( indices[ i + 2 ], c );
  14633. // perform subdivision
  14634. subdivideFace( a, b, c, detail );
  14635. }
  14636. }
  14637. function subdivideFace( a, b, c, detail ) {
  14638. var cols = Math.pow( 2, detail );
  14639. // we use this multidimensional array as a data structure for creating the subdivision
  14640. var v = [];
  14641. var i, j;
  14642. // construct all of the vertices for this subdivision
  14643. for ( i = 0; i <= cols; i ++ ) {
  14644. v[ i ] = [];
  14645. var aj = a.clone().lerp( c, i / cols );
  14646. var bj = b.clone().lerp( c, i / cols );
  14647. var rows = cols - i;
  14648. for ( j = 0; j <= rows; j ++ ) {
  14649. if ( j === 0 && i === cols ) {
  14650. v[ i ][ j ] = aj;
  14651. } else {
  14652. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14653. }
  14654. }
  14655. }
  14656. // construct all of the faces
  14657. for ( i = 0; i < cols; i ++ ) {
  14658. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14659. var k = Math.floor( j / 2 );
  14660. if ( j % 2 === 0 ) {
  14661. pushVertex( v[ i ][ k + 1 ] );
  14662. pushVertex( v[ i + 1 ][ k ] );
  14663. pushVertex( v[ i ][ k ] );
  14664. } else {
  14665. pushVertex( v[ i ][ k + 1 ] );
  14666. pushVertex( v[ i + 1 ][ k + 1 ] );
  14667. pushVertex( v[ i + 1 ][ k ] );
  14668. }
  14669. }
  14670. }
  14671. }
  14672. function appplyRadius( radius ) {
  14673. var vertex = new Vector3();
  14674. // iterate over the entire buffer and apply the radius to each vertex
  14675. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14676. vertex.x = vertexBuffer[ i + 0 ];
  14677. vertex.y = vertexBuffer[ i + 1 ];
  14678. vertex.z = vertexBuffer[ i + 2 ];
  14679. vertex.normalize().multiplyScalar( radius );
  14680. vertexBuffer[ i + 0 ] = vertex.x;
  14681. vertexBuffer[ i + 1 ] = vertex.y;
  14682. vertexBuffer[ i + 2 ] = vertex.z;
  14683. }
  14684. }
  14685. function generateUVs() {
  14686. var vertex = new Vector3();
  14687. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14688. vertex.x = vertexBuffer[ i + 0 ];
  14689. vertex.y = vertexBuffer[ i + 1 ];
  14690. vertex.z = vertexBuffer[ i + 2 ];
  14691. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14692. var v = inclination( vertex ) / Math.PI + 0.5;
  14693. uvBuffer.push( u, 1 - v );
  14694. }
  14695. correctUVs();
  14696. correctSeam();
  14697. }
  14698. function correctSeam() {
  14699. // handle case when face straddles the seam, see #3269
  14700. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14701. // uv data of a single face
  14702. var x0 = uvBuffer[ i + 0 ];
  14703. var x1 = uvBuffer[ i + 2 ];
  14704. var x2 = uvBuffer[ i + 4 ];
  14705. var max = Math.max( x0, x1, x2 );
  14706. var min = Math.min( x0, x1, x2 );
  14707. // 0.9 is somewhat arbitrary
  14708. if ( max > 0.9 && min < 0.1 ) {
  14709. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14710. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14711. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14712. }
  14713. }
  14714. }
  14715. function pushVertex( vertex ) {
  14716. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14717. }
  14718. function getVertexByIndex( index, vertex ) {
  14719. var stride = index * 3;
  14720. vertex.x = vertices[ stride + 0 ];
  14721. vertex.y = vertices[ stride + 1 ];
  14722. vertex.z = vertices[ stride + 2 ];
  14723. }
  14724. function correctUVs() {
  14725. var a = new Vector3();
  14726. var b = new Vector3();
  14727. var c = new Vector3();
  14728. var centroid = new Vector3();
  14729. var uvA = new Vector2();
  14730. var uvB = new Vector2();
  14731. var uvC = new Vector2();
  14732. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14733. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14734. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14735. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14736. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14737. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14738. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14739. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14740. var azi = azimuth( centroid );
  14741. correctUV( uvA, j + 0, a, azi );
  14742. correctUV( uvB, j + 2, b, azi );
  14743. correctUV( uvC, j + 4, c, azi );
  14744. }
  14745. }
  14746. function correctUV( uv, stride, vector, azimuth ) {
  14747. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14748. uvBuffer[ stride ] = uv.x - 1;
  14749. }
  14750. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14751. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14752. }
  14753. }
  14754. // Angle around the Y axis, counter-clockwise when looking from above.
  14755. function azimuth( vector ) {
  14756. return Math.atan2( vector.z, - vector.x );
  14757. }
  14758. // Angle above the XZ plane.
  14759. function inclination( vector ) {
  14760. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14761. }
  14762. }
  14763. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14764. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14765. /**
  14766. * @author timothypratley / https://github.com/timothypratley
  14767. * @author Mugen87 / https://github.com/Mugen87
  14768. */
  14769. // TetrahedronGeometry
  14770. function TetrahedronGeometry( radius, detail ) {
  14771. Geometry.call( this );
  14772. this.type = 'TetrahedronGeometry';
  14773. this.parameters = {
  14774. radius: radius,
  14775. detail: detail
  14776. };
  14777. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14778. this.mergeVertices();
  14779. }
  14780. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14781. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14782. // TetrahedronBufferGeometry
  14783. function TetrahedronBufferGeometry( radius, detail ) {
  14784. var vertices = [
  14785. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14786. ];
  14787. var indices = [
  14788. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14789. ];
  14790. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14791. this.type = 'TetrahedronBufferGeometry';
  14792. this.parameters = {
  14793. radius: radius,
  14794. detail: detail
  14795. };
  14796. }
  14797. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14798. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14799. /**
  14800. * @author timothypratley / https://github.com/timothypratley
  14801. * @author Mugen87 / https://github.com/Mugen87
  14802. */
  14803. // OctahedronGeometry
  14804. function OctahedronGeometry( radius, detail ) {
  14805. Geometry.call( this );
  14806. this.type = 'OctahedronGeometry';
  14807. this.parameters = {
  14808. radius: radius,
  14809. detail: detail
  14810. };
  14811. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14812. this.mergeVertices();
  14813. }
  14814. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14815. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14816. // OctahedronBufferGeometry
  14817. function OctahedronBufferGeometry( radius, detail ) {
  14818. var vertices = [
  14819. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14820. ];
  14821. var indices = [
  14822. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14823. ];
  14824. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14825. this.type = 'OctahedronBufferGeometry';
  14826. this.parameters = {
  14827. radius: radius,
  14828. detail: detail
  14829. };
  14830. }
  14831. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14832. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14833. /**
  14834. * @author timothypratley / https://github.com/timothypratley
  14835. * @author Mugen87 / https://github.com/Mugen87
  14836. */
  14837. // IcosahedronGeometry
  14838. function IcosahedronGeometry( radius, detail ) {
  14839. Geometry.call( this );
  14840. this.type = 'IcosahedronGeometry';
  14841. this.parameters = {
  14842. radius: radius,
  14843. detail: detail
  14844. };
  14845. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14846. this.mergeVertices();
  14847. }
  14848. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14849. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14850. // IcosahedronBufferGeometry
  14851. function IcosahedronBufferGeometry( radius, detail ) {
  14852. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14853. var vertices = [
  14854. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14855. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14856. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14857. ];
  14858. var indices = [
  14859. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14860. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14861. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14862. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14863. ];
  14864. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14865. this.type = 'IcosahedronBufferGeometry';
  14866. this.parameters = {
  14867. radius: radius,
  14868. detail: detail
  14869. };
  14870. }
  14871. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14872. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14873. /**
  14874. * @author Abe Pazos / https://hamoid.com
  14875. * @author Mugen87 / https://github.com/Mugen87
  14876. */
  14877. // DodecahedronGeometry
  14878. function DodecahedronGeometry( radius, detail ) {
  14879. Geometry.call( this );
  14880. this.type = 'DodecahedronGeometry';
  14881. this.parameters = {
  14882. radius: radius,
  14883. detail: detail
  14884. };
  14885. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14886. this.mergeVertices();
  14887. }
  14888. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14889. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14890. // DodecahedronBufferGeometry
  14891. function DodecahedronBufferGeometry( radius, detail ) {
  14892. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14893. var r = 1 / t;
  14894. var vertices = [
  14895. // (±1, ±1, ±1)
  14896. - 1, - 1, - 1, - 1, - 1, 1,
  14897. - 1, 1, - 1, - 1, 1, 1,
  14898. 1, - 1, - 1, 1, - 1, 1,
  14899. 1, 1, - 1, 1, 1, 1,
  14900. // (0, ±1/φ, ±φ)
  14901. 0, - r, - t, 0, - r, t,
  14902. 0, r, - t, 0, r, t,
  14903. // (±1/φ, ±φ, 0)
  14904. - r, - t, 0, - r, t, 0,
  14905. r, - t, 0, r, t, 0,
  14906. // (±φ, 0, ±1/φ)
  14907. - t, 0, - r, t, 0, - r,
  14908. - t, 0, r, t, 0, r
  14909. ];
  14910. var indices = [
  14911. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14912. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14913. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14914. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14915. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14916. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14917. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14918. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14919. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14920. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14921. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14922. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14923. ];
  14924. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14925. this.type = 'DodecahedronBufferGeometry';
  14926. this.parameters = {
  14927. radius: radius,
  14928. detail: detail
  14929. };
  14930. }
  14931. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14932. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14933. /**
  14934. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14935. * @author WestLangley / https://github.com/WestLangley
  14936. * @author zz85 / https://github.com/zz85
  14937. * @author miningold / https://github.com/miningold
  14938. * @author jonobr1 / https://github.com/jonobr1
  14939. * @author Mugen87 / https://github.com/Mugen87
  14940. *
  14941. */
  14942. // TubeGeometry
  14943. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14944. Geometry.call( this );
  14945. this.type = 'TubeGeometry';
  14946. this.parameters = {
  14947. path: path,
  14948. tubularSegments: tubularSegments,
  14949. radius: radius,
  14950. radialSegments: radialSegments,
  14951. closed: closed
  14952. };
  14953. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14954. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14955. // expose internals
  14956. this.tangents = bufferGeometry.tangents;
  14957. this.normals = bufferGeometry.normals;
  14958. this.binormals = bufferGeometry.binormals;
  14959. // create geometry
  14960. this.fromBufferGeometry( bufferGeometry );
  14961. this.mergeVertices();
  14962. }
  14963. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14964. TubeGeometry.prototype.constructor = TubeGeometry;
  14965. // TubeBufferGeometry
  14966. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14967. BufferGeometry.call( this );
  14968. this.type = 'TubeBufferGeometry';
  14969. this.parameters = {
  14970. path: path,
  14971. tubularSegments: tubularSegments,
  14972. radius: radius,
  14973. radialSegments: radialSegments,
  14974. closed: closed
  14975. };
  14976. tubularSegments = tubularSegments || 64;
  14977. radius = radius || 1;
  14978. radialSegments = radialSegments || 8;
  14979. closed = closed || false;
  14980. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14981. // expose internals
  14982. this.tangents = frames.tangents;
  14983. this.normals = frames.normals;
  14984. this.binormals = frames.binormals;
  14985. // helper variables
  14986. var vertex = new Vector3();
  14987. var normal = new Vector3();
  14988. var uv = new Vector2();
  14989. var i, j;
  14990. // buffer
  14991. var vertices = [];
  14992. var normals = [];
  14993. var uvs = [];
  14994. var indices = [];
  14995. // create buffer data
  14996. generateBufferData();
  14997. // build geometry
  14998. this.setIndex( indices );
  14999. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15000. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15001. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15002. // functions
  15003. function generateBufferData() {
  15004. for ( i = 0; i < tubularSegments; i ++ ) {
  15005. generateSegment( i );
  15006. }
  15007. // if the geometry is not closed, generate the last row of vertices and normals
  15008. // at the regular position on the given path
  15009. //
  15010. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15011. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15012. // uvs are generated in a separate function.
  15013. // this makes it easy compute correct values for closed geometries
  15014. generateUVs();
  15015. // finally create faces
  15016. generateIndices();
  15017. }
  15018. function generateSegment( i ) {
  15019. // we use getPointAt to sample evenly distributed points from the given path
  15020. var P = path.getPointAt( i / tubularSegments );
  15021. // retrieve corresponding normal and binormal
  15022. var N = frames.normals[ i ];
  15023. var B = frames.binormals[ i ];
  15024. // generate normals and vertices for the current segment
  15025. for ( j = 0; j <= radialSegments; j ++ ) {
  15026. var v = j / radialSegments * Math.PI * 2;
  15027. var sin = Math.sin( v );
  15028. var cos = - Math.cos( v );
  15029. // normal
  15030. normal.x = ( cos * N.x + sin * B.x );
  15031. normal.y = ( cos * N.y + sin * B.y );
  15032. normal.z = ( cos * N.z + sin * B.z );
  15033. normal.normalize();
  15034. normals.push( normal.x, normal.y, normal.z );
  15035. // vertex
  15036. vertex.x = P.x + radius * normal.x;
  15037. vertex.y = P.y + radius * normal.y;
  15038. vertex.z = P.z + radius * normal.z;
  15039. vertices.push( vertex.x, vertex.y, vertex.z );
  15040. }
  15041. }
  15042. function generateIndices() {
  15043. for ( j = 1; j <= tubularSegments; j ++ ) {
  15044. for ( i = 1; i <= radialSegments; i ++ ) {
  15045. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15046. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15047. var c = ( radialSegments + 1 ) * j + i;
  15048. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15049. // faces
  15050. indices.push( a, b, d );
  15051. indices.push( b, c, d );
  15052. }
  15053. }
  15054. }
  15055. function generateUVs() {
  15056. for ( i = 0; i <= tubularSegments; i ++ ) {
  15057. for ( j = 0; j <= radialSegments; j ++ ) {
  15058. uv.x = i / tubularSegments;
  15059. uv.y = j / radialSegments;
  15060. uvs.push( uv.x, uv.y );
  15061. }
  15062. }
  15063. }
  15064. }
  15065. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15066. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15067. /**
  15068. * @author oosmoxiecode
  15069. * @author Mugen87 / https://github.com/Mugen87
  15070. *
  15071. * based on http://www.blackpawn.com/texts/pqtorus/
  15072. */
  15073. // TorusKnotGeometry
  15074. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15075. Geometry.call( this );
  15076. this.type = 'TorusKnotGeometry';
  15077. this.parameters = {
  15078. radius: radius,
  15079. tube: tube,
  15080. tubularSegments: tubularSegments,
  15081. radialSegments: radialSegments,
  15082. p: p,
  15083. q: q
  15084. };
  15085. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15086. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15087. this.mergeVertices();
  15088. }
  15089. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15090. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15091. // TorusKnotBufferGeometry
  15092. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15093. BufferGeometry.call( this );
  15094. this.type = 'TorusKnotBufferGeometry';
  15095. this.parameters = {
  15096. radius: radius,
  15097. tube: tube,
  15098. tubularSegments: tubularSegments,
  15099. radialSegments: radialSegments,
  15100. p: p,
  15101. q: q
  15102. };
  15103. radius = radius || 100;
  15104. tube = tube || 40;
  15105. tubularSegments = Math.floor( tubularSegments ) || 64;
  15106. radialSegments = Math.floor( radialSegments ) || 8;
  15107. p = p || 2;
  15108. q = q || 3;
  15109. // buffers
  15110. var indices = [];
  15111. var vertices = [];
  15112. var normals = [];
  15113. var uvs = [];
  15114. // helper variables
  15115. var i, j;
  15116. var vertex = new Vector3();
  15117. var normal = new Vector3();
  15118. var P1 = new Vector3();
  15119. var P2 = new Vector3();
  15120. var B = new Vector3();
  15121. var T = new Vector3();
  15122. var N = new Vector3();
  15123. // generate vertices, normals and uvs
  15124. for ( i = 0; i <= tubularSegments; ++ i ) {
  15125. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15126. var u = i / tubularSegments * p * Math.PI * 2;
  15127. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15128. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15129. calculatePositionOnCurve( u, p, q, radius, P1 );
  15130. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15131. // calculate orthonormal basis
  15132. T.subVectors( P2, P1 );
  15133. N.addVectors( P2, P1 );
  15134. B.crossVectors( T, N );
  15135. N.crossVectors( B, T );
  15136. // normalize B, N. T can be ignored, we don't use it
  15137. B.normalize();
  15138. N.normalize();
  15139. for ( j = 0; j <= radialSegments; ++ j ) {
  15140. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15141. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15142. var v = j / radialSegments * Math.PI * 2;
  15143. var cx = - tube * Math.cos( v );
  15144. var cy = tube * Math.sin( v );
  15145. // now calculate the final vertex position.
  15146. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15147. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15148. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15149. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15150. vertices.push( vertex.x, vertex.y, vertex.z );
  15151. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15152. normal.subVectors( vertex, P1 ).normalize();
  15153. normals.push( normal.x, normal.y, normal.z );
  15154. // uv
  15155. uvs.push( i / tubularSegments );
  15156. uvs.push( j / radialSegments );
  15157. }
  15158. }
  15159. // generate indices
  15160. for ( j = 1; j <= tubularSegments; j ++ ) {
  15161. for ( i = 1; i <= radialSegments; i ++ ) {
  15162. // indices
  15163. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15164. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15165. var c = ( radialSegments + 1 ) * j + i;
  15166. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15167. // faces
  15168. indices.push( a, b, d );
  15169. indices.push( b, c, d );
  15170. }
  15171. }
  15172. // build geometry
  15173. this.setIndex( indices );
  15174. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15175. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15176. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15177. // this function calculates the current position on the torus curve
  15178. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15179. var cu = Math.cos( u );
  15180. var su = Math.sin( u );
  15181. var quOverP = q / p * u;
  15182. var cs = Math.cos( quOverP );
  15183. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15184. position.y = radius * ( 2 + cs ) * su * 0.5;
  15185. position.z = radius * Math.sin( quOverP ) * 0.5;
  15186. }
  15187. }
  15188. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15189. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15190. /**
  15191. * @author oosmoxiecode
  15192. * @author mrdoob / http://mrdoob.com/
  15193. * @author Mugen87 / https://github.com/Mugen87
  15194. */
  15195. // TorusGeometry
  15196. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15197. Geometry.call( this );
  15198. this.type = 'TorusGeometry';
  15199. this.parameters = {
  15200. radius: radius,
  15201. tube: tube,
  15202. radialSegments: radialSegments,
  15203. tubularSegments: tubularSegments,
  15204. arc: arc
  15205. };
  15206. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15207. this.mergeVertices();
  15208. }
  15209. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15210. TorusGeometry.prototype.constructor = TorusGeometry;
  15211. // TorusBufferGeometry
  15212. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15213. BufferGeometry.call( this );
  15214. this.type = 'TorusBufferGeometry';
  15215. this.parameters = {
  15216. radius: radius,
  15217. tube: tube,
  15218. radialSegments: radialSegments,
  15219. tubularSegments: tubularSegments,
  15220. arc: arc
  15221. };
  15222. radius = radius || 100;
  15223. tube = tube || 40;
  15224. radialSegments = Math.floor( radialSegments ) || 8;
  15225. tubularSegments = Math.floor( tubularSegments ) || 6;
  15226. arc = arc || Math.PI * 2;
  15227. // buffers
  15228. var indices = [];
  15229. var vertices = [];
  15230. var normals = [];
  15231. var uvs = [];
  15232. // helper variables
  15233. var center = new Vector3();
  15234. var vertex = new Vector3();
  15235. var normal = new Vector3();
  15236. var j, i;
  15237. // generate vertices, normals and uvs
  15238. for ( j = 0; j <= radialSegments; j ++ ) {
  15239. for ( i = 0; i <= tubularSegments; i ++ ) {
  15240. var u = i / tubularSegments * arc;
  15241. var v = j / radialSegments * Math.PI * 2;
  15242. // vertex
  15243. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15244. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15245. vertex.z = tube * Math.sin( v );
  15246. vertices.push( vertex.x, vertex.y, vertex.z );
  15247. // normal
  15248. center.x = radius * Math.cos( u );
  15249. center.y = radius * Math.sin( u );
  15250. normal.subVectors( vertex, center ).normalize();
  15251. normals.push( normal.x, normal.y, normal.z );
  15252. // uv
  15253. uvs.push( i / tubularSegments );
  15254. uvs.push( j / radialSegments );
  15255. }
  15256. }
  15257. // generate indices
  15258. for ( j = 1; j <= radialSegments; j ++ ) {
  15259. for ( i = 1; i <= tubularSegments; i ++ ) {
  15260. // indices
  15261. var a = ( tubularSegments + 1 ) * j + i - 1;
  15262. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15263. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15264. var d = ( tubularSegments + 1 ) * j + i;
  15265. // faces
  15266. indices.push( a, b, d );
  15267. indices.push( b, c, d );
  15268. }
  15269. }
  15270. // build geometry
  15271. this.setIndex( indices );
  15272. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15273. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15274. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15275. }
  15276. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15277. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15278. /**
  15279. * @author zz85 / http://www.lab4games.net/zz85/blog
  15280. */
  15281. var ShapeUtils = {
  15282. // calculate area of the contour polygon
  15283. area: function ( contour ) {
  15284. var n = contour.length;
  15285. var a = 0.0;
  15286. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15287. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15288. }
  15289. return a * 0.5;
  15290. },
  15291. triangulate: ( function () {
  15292. /**
  15293. * This code is a quick port of code written in C++ which was submitted to
  15294. * flipcode.com by John W. Ratcliff // July 22, 2000
  15295. * See original code and more information here:
  15296. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15297. *
  15298. * ported to actionscript by Zevan Rosser
  15299. * www.actionsnippet.com
  15300. *
  15301. * ported to javascript by Joshua Koo
  15302. * http://www.lab4games.net/zz85/blog
  15303. *
  15304. */
  15305. function snip( contour, u, v, w, n, verts ) {
  15306. var p;
  15307. var ax, ay, bx, by;
  15308. var cx, cy, px, py;
  15309. ax = contour[ verts[ u ] ].x;
  15310. ay = contour[ verts[ u ] ].y;
  15311. bx = contour[ verts[ v ] ].x;
  15312. by = contour[ verts[ v ] ].y;
  15313. cx = contour[ verts[ w ] ].x;
  15314. cy = contour[ verts[ w ] ].y;
  15315. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15316. var aX, aY, bX, bY, cX, cY;
  15317. var apx, apy, bpx, bpy, cpx, cpy;
  15318. var cCROSSap, bCROSScp, aCROSSbp;
  15319. aX = cx - bx; aY = cy - by;
  15320. bX = ax - cx; bY = ay - cy;
  15321. cX = bx - ax; cY = by - ay;
  15322. for ( p = 0; p < n; p ++ ) {
  15323. px = contour[ verts[ p ] ].x;
  15324. py = contour[ verts[ p ] ].y;
  15325. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15326. ( ( px === bx ) && ( py === by ) ) ||
  15327. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15328. apx = px - ax; apy = py - ay;
  15329. bpx = px - bx; bpy = py - by;
  15330. cpx = px - cx; cpy = py - cy;
  15331. // see if p is inside triangle abc
  15332. aCROSSbp = aX * bpy - aY * bpx;
  15333. cCROSSap = cX * apy - cY * apx;
  15334. bCROSScp = bX * cpy - bY * cpx;
  15335. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15336. }
  15337. return true;
  15338. }
  15339. // takes in an contour array and returns
  15340. return function triangulate( contour, indices ) {
  15341. var n = contour.length;
  15342. if ( n < 3 ) return null;
  15343. var result = [],
  15344. verts = [],
  15345. vertIndices = [];
  15346. /* we want a counter-clockwise polygon in verts */
  15347. var u, v, w;
  15348. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15349. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15350. } else {
  15351. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15352. }
  15353. var nv = n;
  15354. /* remove nv - 2 vertices, creating 1 triangle every time */
  15355. var count = 2 * nv; /* error detection */
  15356. for ( v = nv - 1; nv > 2; ) {
  15357. /* if we loop, it is probably a non-simple polygon */
  15358. if ( ( count -- ) <= 0 ) {
  15359. //** Triangulate: ERROR - probable bad polygon!
  15360. //throw ( "Warning, unable to triangulate polygon!" );
  15361. //return null;
  15362. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15363. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15364. if ( indices ) return vertIndices;
  15365. return result;
  15366. }
  15367. /* three consecutive vertices in current polygon, <u,v,w> */
  15368. u = v; if ( nv <= u ) u = 0; /* previous */
  15369. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15370. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15371. if ( snip( contour, u, v, w, nv, verts ) ) {
  15372. var a, b, c, s, t;
  15373. /* true names of the vertices */
  15374. a = verts[ u ];
  15375. b = verts[ v ];
  15376. c = verts[ w ];
  15377. /* output Triangle */
  15378. result.push( [ contour[ a ],
  15379. contour[ b ],
  15380. contour[ c ] ] );
  15381. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15382. /* remove v from the remaining polygon */
  15383. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15384. verts[ s ] = verts[ t ];
  15385. }
  15386. nv --;
  15387. /* reset error detection counter */
  15388. count = 2 * nv;
  15389. }
  15390. }
  15391. if ( indices ) return vertIndices;
  15392. return result;
  15393. }
  15394. } )(),
  15395. triangulateShape: function ( contour, holes ) {
  15396. function removeDupEndPts(points) {
  15397. var l = points.length;
  15398. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15399. points.pop();
  15400. }
  15401. }
  15402. removeDupEndPts( contour );
  15403. holes.forEach( removeDupEndPts );
  15404. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15405. // inOtherPt needs to be collinear to the inSegment
  15406. if ( inSegPt1.x !== inSegPt2.x ) {
  15407. if ( inSegPt1.x < inSegPt2.x ) {
  15408. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15409. } else {
  15410. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15411. }
  15412. } else {
  15413. if ( inSegPt1.y < inSegPt2.y ) {
  15414. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15415. } else {
  15416. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15417. }
  15418. }
  15419. }
  15420. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15421. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15422. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15423. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15424. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15425. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15426. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15427. if ( Math.abs( limit ) > Number.EPSILON ) {
  15428. // not parallel
  15429. var perpSeg2;
  15430. if ( limit > 0 ) {
  15431. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15432. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15433. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15434. } else {
  15435. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15436. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15437. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15438. }
  15439. // i.e. to reduce rounding errors
  15440. // intersection at endpoint of segment#1?
  15441. if ( perpSeg2 === 0 ) {
  15442. if ( ( inExcludeAdjacentSegs ) &&
  15443. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15444. return [ inSeg1Pt1 ];
  15445. }
  15446. if ( perpSeg2 === limit ) {
  15447. if ( ( inExcludeAdjacentSegs ) &&
  15448. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15449. return [ inSeg1Pt2 ];
  15450. }
  15451. // intersection at endpoint of segment#2?
  15452. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15453. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15454. // return real intersection point
  15455. var factorSeg1 = perpSeg2 / limit;
  15456. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15457. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15458. } else {
  15459. // parallel or collinear
  15460. if ( ( perpSeg1 !== 0 ) ||
  15461. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15462. // they are collinear or degenerate
  15463. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15464. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15465. // both segments are points
  15466. if ( seg1Pt && seg2Pt ) {
  15467. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15468. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15469. return [ inSeg1Pt1 ]; // they are the same point
  15470. }
  15471. // segment#1 is a single point
  15472. if ( seg1Pt ) {
  15473. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15474. return [ inSeg1Pt1 ];
  15475. }
  15476. // segment#2 is a single point
  15477. if ( seg2Pt ) {
  15478. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15479. return [ inSeg2Pt1 ];
  15480. }
  15481. // they are collinear segments, which might overlap
  15482. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15483. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15484. if ( seg1dx !== 0 ) {
  15485. // the segments are NOT on a vertical line
  15486. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15487. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15488. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15489. } else {
  15490. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15491. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15492. }
  15493. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15494. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15495. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15496. } else {
  15497. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15498. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15499. }
  15500. } else {
  15501. // the segments are on a vertical line
  15502. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15503. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15504. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15505. } else {
  15506. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15507. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15508. }
  15509. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15510. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15511. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15512. } else {
  15513. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15514. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15515. }
  15516. }
  15517. if ( seg1minVal <= seg2minVal ) {
  15518. if ( seg1maxVal < seg2minVal ) return [];
  15519. if ( seg1maxVal === seg2minVal ) {
  15520. if ( inExcludeAdjacentSegs ) return [];
  15521. return [ seg2min ];
  15522. }
  15523. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15524. return [ seg2min, seg2max ];
  15525. } else {
  15526. if ( seg1minVal > seg2maxVal ) return [];
  15527. if ( seg1minVal === seg2maxVal ) {
  15528. if ( inExcludeAdjacentSegs ) return [];
  15529. return [ seg1min ];
  15530. }
  15531. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15532. return [ seg1min, seg2max ];
  15533. }
  15534. }
  15535. }
  15536. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15537. // The order of legs is important
  15538. // translation of all points, so that Vertex is at (0,0)
  15539. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15540. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15541. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15542. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15543. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15544. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15545. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15546. // angle != 180 deg.
  15547. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15548. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15549. if ( from2toAngle > 0 ) {
  15550. // main angle < 180 deg.
  15551. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15552. } else {
  15553. // main angle > 180 deg.
  15554. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15555. }
  15556. } else {
  15557. // angle == 180 deg.
  15558. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15559. return ( from2otherAngle > 0 );
  15560. }
  15561. }
  15562. function removeHoles( contour, holes ) {
  15563. var shape = contour.concat(); // work on this shape
  15564. var hole;
  15565. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15566. // Check if hole point lies within angle around shape point
  15567. var lastShapeIdx = shape.length - 1;
  15568. var prevShapeIdx = inShapeIdx - 1;
  15569. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15570. var nextShapeIdx = inShapeIdx + 1;
  15571. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15572. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15573. if ( ! insideAngle ) {
  15574. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15575. return false;
  15576. }
  15577. // Check if shape point lies within angle around hole point
  15578. var lastHoleIdx = hole.length - 1;
  15579. var prevHoleIdx = inHoleIdx - 1;
  15580. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15581. var nextHoleIdx = inHoleIdx + 1;
  15582. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15583. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15584. if ( ! insideAngle ) {
  15585. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15586. return false;
  15587. }
  15588. return true;
  15589. }
  15590. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15591. // checks for intersections with shape edges
  15592. var sIdx, nextIdx, intersection;
  15593. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15594. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15595. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15596. if ( intersection.length > 0 ) return true;
  15597. }
  15598. return false;
  15599. }
  15600. var indepHoles = [];
  15601. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15602. // checks for intersections with hole edges
  15603. var ihIdx, chkHole,
  15604. hIdx, nextIdx, intersection;
  15605. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15606. chkHole = holes[ indepHoles[ ihIdx ]];
  15607. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15608. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15609. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15610. if ( intersection.length > 0 ) return true;
  15611. }
  15612. }
  15613. return false;
  15614. }
  15615. var holeIndex, shapeIndex,
  15616. shapePt, holePt,
  15617. holeIdx, cutKey, failedCuts = [],
  15618. tmpShape1, tmpShape2,
  15619. tmpHole1, tmpHole2;
  15620. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15621. indepHoles.push( h );
  15622. }
  15623. var minShapeIndex = 0;
  15624. var counter = indepHoles.length * 2;
  15625. while ( indepHoles.length > 0 ) {
  15626. counter --;
  15627. if ( counter < 0 ) {
  15628. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15629. break;
  15630. }
  15631. // search for shape-vertex and hole-vertex,
  15632. // which can be connected without intersections
  15633. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15634. shapePt = shape[ shapeIndex ];
  15635. holeIndex = - 1;
  15636. // search for hole which can be reached without intersections
  15637. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15638. holeIdx = indepHoles[ h ];
  15639. // prevent multiple checks
  15640. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15641. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15642. hole = holes[ holeIdx ];
  15643. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15644. holePt = hole[ h2 ];
  15645. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15646. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15647. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15648. holeIndex = h2;
  15649. indepHoles.splice( h, 1 );
  15650. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15651. tmpShape2 = shape.slice( shapeIndex );
  15652. tmpHole1 = hole.slice( holeIndex );
  15653. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15654. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15655. minShapeIndex = shapeIndex;
  15656. // Debug only, to show the selected cuts
  15657. // glob_CutLines.push( [ shapePt, holePt ] );
  15658. break;
  15659. }
  15660. if ( holeIndex >= 0 ) break; // hole-vertex found
  15661. failedCuts[ cutKey ] = true; // remember failure
  15662. }
  15663. if ( holeIndex >= 0 ) break; // hole-vertex found
  15664. }
  15665. }
  15666. return shape; /* shape with no holes */
  15667. }
  15668. var i, il, f, face,
  15669. key, index,
  15670. allPointsMap = {};
  15671. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  15672. var allpoints = contour.concat();
  15673. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15674. Array.prototype.push.apply( allpoints, holes[ h ] );
  15675. }
  15676. //console.log( "allpoints",allpoints, allpoints.length );
  15677. // prepare all points map
  15678. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15679. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15680. if ( allPointsMap[ key ] !== undefined ) {
  15681. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15682. }
  15683. allPointsMap[ key ] = i;
  15684. }
  15685. // remove holes by cutting paths to holes and adding them to the shape
  15686. var shapeWithoutHoles = removeHoles( contour, holes );
  15687. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15688. //console.log( "triangles",triangles, triangles.length );
  15689. // check all face vertices against all points map
  15690. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15691. face = triangles[ i ];
  15692. for ( f = 0; f < 3; f ++ ) {
  15693. key = face[ f ].x + ":" + face[ f ].y;
  15694. index = allPointsMap[ key ];
  15695. if ( index !== undefined ) {
  15696. face[ f ] = index;
  15697. }
  15698. }
  15699. }
  15700. return triangles.concat();
  15701. },
  15702. isClockWise: function ( pts ) {
  15703. return ShapeUtils.area( pts ) < 0;
  15704. }
  15705. };
  15706. /**
  15707. * @author zz85 / http://www.lab4games.net/zz85/blog
  15708. *
  15709. * Creates extruded geometry from a path shape.
  15710. *
  15711. * parameters = {
  15712. *
  15713. * curveSegments: <int>, // number of points on the curves
  15714. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15715. * amount: <int>, // Depth to extrude the shape
  15716. *
  15717. * bevelEnabled: <bool>, // turn on bevel
  15718. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15719. * bevelSize: <float>, // how far from shape outline is bevel
  15720. * bevelSegments: <int>, // number of bevel layers
  15721. *
  15722. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15723. * frames: <Object> // containing arrays of tangents, normals, binormals
  15724. *
  15725. * UVGenerator: <Object> // object that provides UV generator functions
  15726. *
  15727. * }
  15728. */
  15729. // ExtrudeGeometry
  15730. function ExtrudeGeometry( shapes, options ) {
  15731. Geometry.call( this );
  15732. this.type = 'ExtrudeGeometry';
  15733. this.parameters = {
  15734. shapes: shapes,
  15735. options: options
  15736. };
  15737. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  15738. this.mergeVertices();
  15739. }
  15740. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15741. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15742. // ExtrudeBufferGeometry
  15743. function ExtrudeBufferGeometry( shapes, options ) {
  15744. if ( typeof ( shapes ) === "undefined" ) {
  15745. shapes = [];
  15746. return;
  15747. }
  15748. BufferGeometry.call( this );
  15749. this.type = 'ExtrudeBufferGeometry';
  15750. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15751. this.addShapeList( shapes, options );
  15752. this.computeVertexNormals();
  15753. // can't really use automatic vertex normals
  15754. // as then front and back sides get smoothed too
  15755. // should do separate smoothing just for sides
  15756. //this.computeVertexNormals();
  15757. //console.log( "took", ( Date.now() - startTime ) );
  15758. }
  15759. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15760. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  15761. ExtrudeBufferGeometry.prototype.getArrays = function () {
  15762. var positionAttribute = this.getAttribute( "position" );
  15763. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  15764. var uvAttribute = this.getAttribute( "uv" );
  15765. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  15766. var IndexAttribute = this.index;
  15767. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  15768. return {
  15769. position: verticesArray,
  15770. uv: uvArray,
  15771. index: indicesArray
  15772. };
  15773. };
  15774. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  15775. var sl = shapes.length;
  15776. options.arrays = this.getArrays();
  15777. for ( var s = 0; s < sl; s ++ ) {
  15778. var shape = shapes[ s ];
  15779. this.addShape( shape, options );
  15780. }
  15781. this.setIndex( options.arrays.index );
  15782. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  15783. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  15784. };
  15785. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  15786. var arrays = options.arrays ? options.arrays : this.getArrays();
  15787. var verticesArray = arrays.position;
  15788. var indicesArray = arrays.index;
  15789. var uvArray = arrays.uv;
  15790. var placeholder = [];
  15791. var amount = options.amount !== undefined ? options.amount : 100;
  15792. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15793. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15794. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15795. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15796. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15797. var steps = options.steps !== undefined ? options.steps : 1;
  15798. var extrudePath = options.extrudePath;
  15799. var extrudePts, extrudeByPath = false;
  15800. // Use default WorldUVGenerator if no UV generators are specified.
  15801. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15802. var splineTube, binormal, normal, position2;
  15803. if ( extrudePath ) {
  15804. extrudePts = extrudePath.getSpacedPoints( steps );
  15805. extrudeByPath = true;
  15806. bevelEnabled = false; // bevels not supported for path extrusion
  15807. // SETUP TNB variables
  15808. // TODO1 - have a .isClosed in spline?
  15809. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15810. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15811. binormal = new Vector3();
  15812. normal = new Vector3();
  15813. position2 = new Vector3();
  15814. }
  15815. // Safeguards if bevels are not enabled
  15816. if ( ! bevelEnabled ) {
  15817. bevelSegments = 0;
  15818. bevelThickness = 0;
  15819. bevelSize = 0;
  15820. }
  15821. // Variables initialization
  15822. var ahole, h, hl; // looping of holes
  15823. var scope = this;
  15824. var shapePoints = shape.extractPoints( curveSegments );
  15825. var vertices = shapePoints.shape;
  15826. var holes = shapePoints.holes;
  15827. var reverse = ! ShapeUtils.isClockWise( vertices );
  15828. if ( reverse ) {
  15829. vertices = vertices.reverse();
  15830. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15831. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15832. ahole = holes[ h ];
  15833. if ( ShapeUtils.isClockWise( ahole ) ) {
  15834. holes[ h ] = ahole.reverse();
  15835. }
  15836. }
  15837. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15838. }
  15839. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15840. /* Vertices */
  15841. var contour = vertices; // vertices has all points but contour has only points of circumference
  15842. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15843. ahole = holes[ h ];
  15844. vertices = vertices.concat( ahole );
  15845. }
  15846. function scalePt2( pt, vec, size ) {
  15847. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15848. return vec.clone().multiplyScalar( size ).add( pt );
  15849. }
  15850. var b, bs, t, z,
  15851. vert, vlen = vertices.length,
  15852. face, flen = faces.length;
  15853. // Find directions for point movement
  15854. function getBevelVec( inPt, inPrev, inNext ) {
  15855. // computes for inPt the corresponding point inPt' on a new contour
  15856. // shifted by 1 unit (length of normalized vector) to the left
  15857. // if we walk along contour clockwise, this new contour is outside the old one
  15858. //
  15859. // inPt' is the intersection of the two lines parallel to the two
  15860. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15861. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15862. // good reading for geometry algorithms (here: line-line intersection)
  15863. // http://geomalgorithms.com/a05-_intersect-1.html
  15864. var v_prev_x = inPt.x - inPrev.x,
  15865. v_prev_y = inPt.y - inPrev.y;
  15866. var v_next_x = inNext.x - inPt.x,
  15867. v_next_y = inNext.y - inPt.y;
  15868. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15869. // check for collinear edges
  15870. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15871. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15872. // not collinear
  15873. // length of vectors for normalizing
  15874. var v_prev_len = Math.sqrt( v_prev_lensq );
  15875. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15876. // shift adjacent points by unit vectors to the left
  15877. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15878. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15879. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15880. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15881. // scaling factor for v_prev to intersection point
  15882. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15883. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15884. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15885. // vector from inPt to intersection point
  15886. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15887. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15888. // Don't normalize!, otherwise sharp corners become ugly
  15889. // but prevent crazy spikes
  15890. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15891. if ( v_trans_lensq <= 2 ) {
  15892. return new Vector2( v_trans_x, v_trans_y );
  15893. } else {
  15894. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15895. }
  15896. } else {
  15897. // handle special case of collinear edges
  15898. var direction_eq = false; // assumes: opposite
  15899. if ( v_prev_x > Number.EPSILON ) {
  15900. if ( v_next_x > Number.EPSILON ) {
  15901. direction_eq = true;
  15902. }
  15903. } else {
  15904. if ( v_prev_x < - Number.EPSILON ) {
  15905. if ( v_next_x < - Number.EPSILON ) {
  15906. direction_eq = true;
  15907. }
  15908. } else {
  15909. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15910. direction_eq = true;
  15911. }
  15912. }
  15913. }
  15914. if ( direction_eq ) {
  15915. // console.log("Warning: lines are a straight sequence");
  15916. v_trans_x = - v_prev_y;
  15917. v_trans_y = v_prev_x;
  15918. shrink_by = Math.sqrt( v_prev_lensq );
  15919. } else {
  15920. // console.log("Warning: lines are a straight spike");
  15921. v_trans_x = v_prev_x;
  15922. v_trans_y = v_prev_y;
  15923. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15924. }
  15925. }
  15926. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15927. }
  15928. var contourMovements = [];
  15929. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15930. if ( j === il ) j = 0;
  15931. if ( k === il ) k = 0;
  15932. // (j)---(i)---(k)
  15933. // console.log('i,j,k', i, j , k)
  15934. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15935. }
  15936. var holesMovements = [],
  15937. oneHoleMovements, verticesMovements = contourMovements.concat();
  15938. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15939. ahole = holes[ h ];
  15940. oneHoleMovements = [];
  15941. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15942. if ( j === il ) j = 0;
  15943. if ( k === il ) k = 0;
  15944. // (j)---(i)---(k)
  15945. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15946. }
  15947. holesMovements.push( oneHoleMovements );
  15948. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15949. }
  15950. // Loop bevelSegments, 1 for the front, 1 for the back
  15951. for ( b = 0; b < bevelSegments; b ++ ) {
  15952. //for ( b = bevelSegments; b > 0; b -- ) {
  15953. t = b / bevelSegments;
  15954. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15955. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15956. // contract shape
  15957. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15958. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15959. v( vert.x, vert.y, - z );
  15960. }
  15961. // expand holes
  15962. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15963. ahole = holes[ h ];
  15964. oneHoleMovements = holesMovements[ h ];
  15965. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15966. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15967. v( vert.x, vert.y, - z );
  15968. }
  15969. }
  15970. }
  15971. bs = bevelSize;
  15972. // Back facing vertices
  15973. for ( i = 0; i < vlen; i ++ ) {
  15974. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15975. if ( ! extrudeByPath ) {
  15976. v( vert.x, vert.y, 0 );
  15977. } else {
  15978. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15979. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15980. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15981. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15982. v( position2.x, position2.y, position2.z );
  15983. }
  15984. }
  15985. // Add stepped vertices...
  15986. // Including front facing vertices
  15987. var s;
  15988. for ( s = 1; s <= steps; s ++ ) {
  15989. for ( i = 0; i < vlen; i ++ ) {
  15990. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15991. if ( ! extrudeByPath ) {
  15992. v( vert.x, vert.y, amount / steps * s );
  15993. } else {
  15994. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15995. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15996. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15997. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15998. v( position2.x, position2.y, position2.z );
  15999. }
  16000. }
  16001. }
  16002. // Add bevel segments planes
  16003. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16004. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16005. t = b / bevelSegments;
  16006. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16007. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16008. // contract shape
  16009. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16010. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16011. v( vert.x, vert.y, amount + z );
  16012. }
  16013. // expand holes
  16014. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16015. ahole = holes[ h ];
  16016. oneHoleMovements = holesMovements[ h ];
  16017. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16018. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16019. if ( ! extrudeByPath ) {
  16020. v( vert.x, vert.y, amount + z );
  16021. } else {
  16022. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16023. }
  16024. }
  16025. }
  16026. }
  16027. /* Faces */
  16028. // Top and bottom faces
  16029. buildLidFaces();
  16030. // Sides faces
  16031. buildSideFaces();
  16032. ///// Internal functions
  16033. function buildLidFaces() {
  16034. var start = verticesArray.length/3;
  16035. if ( bevelEnabled ) {
  16036. var layer = 0; // steps + 1
  16037. var offset = vlen * layer;
  16038. // Bottom faces
  16039. for ( i = 0; i < flen; i ++ ) {
  16040. face = faces[ i ];
  16041. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16042. }
  16043. layer = steps + bevelSegments * 2;
  16044. offset = vlen * layer;
  16045. // Top faces
  16046. for ( i = 0; i < flen; i ++ ) {
  16047. face = faces[ i ];
  16048. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16049. }
  16050. } else {
  16051. // Bottom faces
  16052. for ( i = 0; i < flen; i ++ ) {
  16053. face = faces[ i ];
  16054. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16055. }
  16056. // Top faces
  16057. for ( i = 0; i < flen; i ++ ) {
  16058. face = faces[ i ];
  16059. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16060. }
  16061. }
  16062. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16063. }
  16064. // Create faces for the z-sides of the shape
  16065. function buildSideFaces() {
  16066. var start = verticesArray.length/3;
  16067. var layeroffset = 0;
  16068. sidewalls( contour, layeroffset );
  16069. layeroffset += contour.length;
  16070. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16071. ahole = holes[ h ];
  16072. sidewalls( ahole, layeroffset );
  16073. //, true
  16074. layeroffset += ahole.length;
  16075. }
  16076. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16077. }
  16078. function sidewalls( contour, layeroffset ) {
  16079. var j, k;
  16080. i = contour.length;
  16081. while ( -- i >= 0 ) {
  16082. j = i;
  16083. k = i - 1;
  16084. if ( k < 0 ) k = contour.length - 1;
  16085. //console.log('b', i,j, i-1, k,vertices.length);
  16086. var s = 0,
  16087. sl = steps + bevelSegments * 2;
  16088. for ( s = 0; s < sl; s ++ ) {
  16089. var slen1 = vlen * s;
  16090. var slen2 = vlen * ( s + 1 );
  16091. var a = layeroffset + j + slen1,
  16092. b = layeroffset + k + slen1,
  16093. c = layeroffset + k + slen2,
  16094. d = layeroffset + j + slen2;
  16095. f4( a, b, c, d, contour, s, sl, j, k );
  16096. }
  16097. }
  16098. }
  16099. function v( x, y, z ) {
  16100. placeholder.push( x );
  16101. placeholder.push( y );
  16102. placeholder.push( z );
  16103. }
  16104. function f3( a, b, c ) {
  16105. addVertex( a );
  16106. addVertex( b );
  16107. addVertex( c );
  16108. var nextIndex = verticesArray.length / 3;
  16109. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16110. addUV( uvs[ 0 ] );
  16111. addUV( uvs[ 1 ] );
  16112. addUV( uvs[ 2 ] );
  16113. }
  16114. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16115. addVertex( a );
  16116. addVertex( b );
  16117. addVertex( d );
  16118. addVertex( b );
  16119. addVertex( c );
  16120. addVertex( d );
  16121. var nextIndex = verticesArray.length / 3;
  16122. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16123. addUV( uvs[ 0 ] );
  16124. addUV( uvs[ 1 ] );
  16125. addUV( uvs[ 3 ] );
  16126. addUV( uvs[ 1 ] );
  16127. addUV( uvs[ 2 ] );
  16128. addUV( uvs[ 3 ] );
  16129. }
  16130. function addVertex( index ) {
  16131. indicesArray.push( verticesArray.length / 3 );
  16132. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16133. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16134. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16135. }
  16136. function addUV( vector2 ) {
  16137. uvArray.push( vector2.x );
  16138. uvArray.push( vector2.y );
  16139. }
  16140. if ( ! options.arrays ) {
  16141. this.setIndex( indicesArray );
  16142. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16143. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16144. }
  16145. };
  16146. ExtrudeGeometry.WorldUVGenerator = {
  16147. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16148. var a_x = vertices[ indexA * 3 ];
  16149. var a_y = vertices[ indexA * 3 + 1 ];
  16150. var b_x = vertices[ indexB * 3 ];
  16151. var b_y = vertices[ indexB * 3 + 1 ];
  16152. var c_x = vertices[ indexC * 3 ];
  16153. var c_y = vertices[ indexC * 3 + 1 ];
  16154. return [
  16155. new Vector2( a_x, a_y ),
  16156. new Vector2( b_x, b_y ),
  16157. new Vector2( c_x, c_y )
  16158. ];
  16159. },
  16160. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16161. var a_x = vertices[ indexA * 3 ];
  16162. var a_y = vertices[ indexA * 3 + 1 ];
  16163. var a_z = vertices[ indexA * 3 + 2 ];
  16164. var b_x = vertices[ indexB * 3 ];
  16165. var b_y = vertices[ indexB * 3 + 1 ];
  16166. var b_z = vertices[ indexB * 3 + 2 ];
  16167. var c_x = vertices[ indexC * 3 ];
  16168. var c_y = vertices[ indexC * 3 + 1 ];
  16169. var c_z = vertices[ indexC * 3 + 2 ];
  16170. var d_x = vertices[ indexD * 3 ];
  16171. var d_y = vertices[ indexD * 3 + 1 ];
  16172. var d_z = vertices[ indexD * 3 + 2 ];
  16173. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16174. return [
  16175. new Vector2( a_x, 1 - a_z ),
  16176. new Vector2( b_x, 1 - b_z ),
  16177. new Vector2( c_x, 1 - c_z ),
  16178. new Vector2( d_x, 1 - d_z )
  16179. ];
  16180. } else {
  16181. return [
  16182. new Vector2( a_y, 1 - a_z ),
  16183. new Vector2( b_y, 1 - b_z ),
  16184. new Vector2( c_y, 1 - c_z ),
  16185. new Vector2( d_y, 1 - d_z )
  16186. ];
  16187. }
  16188. }
  16189. };
  16190. /**
  16191. * @author zz85 / http://www.lab4games.net/zz85/blog
  16192. * @author alteredq / http://alteredqualia.com/
  16193. *
  16194. * Text = 3D Text
  16195. *
  16196. * parameters = {
  16197. * font: <THREE.Font>, // font
  16198. *
  16199. * size: <float>, // size of the text
  16200. * height: <float>, // thickness to extrude text
  16201. * curveSegments: <int>, // number of points on the curves
  16202. *
  16203. * bevelEnabled: <bool>, // turn on bevel
  16204. * bevelThickness: <float>, // how deep into text bevel goes
  16205. * bevelSize: <float> // how far from text outline is bevel
  16206. * }
  16207. */
  16208. // TextGeometry
  16209. function TextGeometry( text, parameters ) {
  16210. Geometry.call( this );
  16211. this.type = 'TextGeometry';
  16212. this.parameters = {
  16213. text: text,
  16214. parameters: parameters
  16215. };
  16216. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16217. this.mergeVertices();
  16218. }
  16219. TextGeometry.prototype = Object.create( Geometry.prototype );
  16220. TextGeometry.prototype.constructor = TextGeometry;
  16221. // TextBufferGeometry
  16222. function TextBufferGeometry( text, parameters ) {
  16223. parameters = parameters || {};
  16224. var font = parameters.font;
  16225. if ( ( font && font.isFont ) === false ) {
  16226. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16227. return new Geometry();
  16228. }
  16229. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16230. // translate parameters to ExtrudeGeometry API
  16231. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16232. // defaults
  16233. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16234. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16235. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16236. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16237. this.type = 'TextBufferGeometry';
  16238. }
  16239. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16240. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16241. /**
  16242. * @author mrdoob / http://mrdoob.com/
  16243. * @author benaadams / https://twitter.com/ben_a_adams
  16244. * @author Mugen87 / https://github.com/Mugen87
  16245. */
  16246. // SphereGeometry
  16247. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16248. Geometry.call( this );
  16249. this.type = 'SphereGeometry';
  16250. this.parameters = {
  16251. radius: radius,
  16252. widthSegments: widthSegments,
  16253. heightSegments: heightSegments,
  16254. phiStart: phiStart,
  16255. phiLength: phiLength,
  16256. thetaStart: thetaStart,
  16257. thetaLength: thetaLength
  16258. };
  16259. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16260. this.mergeVertices();
  16261. }
  16262. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16263. SphereGeometry.prototype.constructor = SphereGeometry;
  16264. // SphereBufferGeometry
  16265. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16266. BufferGeometry.call( this );
  16267. this.type = 'SphereBufferGeometry';
  16268. this.parameters = {
  16269. radius: radius,
  16270. widthSegments: widthSegments,
  16271. heightSegments: heightSegments,
  16272. phiStart: phiStart,
  16273. phiLength: phiLength,
  16274. thetaStart: thetaStart,
  16275. thetaLength: thetaLength
  16276. };
  16277. radius = radius || 50;
  16278. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16279. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16280. phiStart = phiStart !== undefined ? phiStart : 0;
  16281. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16282. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16283. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16284. var thetaEnd = thetaStart + thetaLength;
  16285. var ix, iy;
  16286. var index = 0;
  16287. var grid = [];
  16288. var vertex = new Vector3();
  16289. var normal = new Vector3();
  16290. // buffers
  16291. var indices = [];
  16292. var vertices = [];
  16293. var normals = [];
  16294. var uvs = [];
  16295. // generate vertices, normals and uvs
  16296. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16297. var verticesRow = [];
  16298. var v = iy / heightSegments;
  16299. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16300. var u = ix / widthSegments;
  16301. // vertex
  16302. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16303. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16304. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16305. vertices.push( vertex.x, vertex.y, vertex.z );
  16306. // normal
  16307. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16308. normals.push( normal.x, normal.y, normal.z );
  16309. // uv
  16310. uvs.push( u, 1 - v );
  16311. verticesRow.push( index ++ );
  16312. }
  16313. grid.push( verticesRow );
  16314. }
  16315. // indices
  16316. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16317. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16318. var a = grid[ iy ][ ix + 1 ];
  16319. var b = grid[ iy ][ ix ];
  16320. var c = grid[ iy + 1 ][ ix ];
  16321. var d = grid[ iy + 1 ][ ix + 1 ];
  16322. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16323. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16324. }
  16325. }
  16326. // build geometry
  16327. this.setIndex( indices );
  16328. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16329. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16330. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16331. }
  16332. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16333. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16334. /**
  16335. * @author Kaleb Murphy
  16336. * @author Mugen87 / https://github.com/Mugen87
  16337. */
  16338. // RingGeometry
  16339. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16340. Geometry.call( this );
  16341. this.type = 'RingGeometry';
  16342. this.parameters = {
  16343. innerRadius: innerRadius,
  16344. outerRadius: outerRadius,
  16345. thetaSegments: thetaSegments,
  16346. phiSegments: phiSegments,
  16347. thetaStart: thetaStart,
  16348. thetaLength: thetaLength
  16349. };
  16350. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16351. this.mergeVertices();
  16352. }
  16353. RingGeometry.prototype = Object.create( Geometry.prototype );
  16354. RingGeometry.prototype.constructor = RingGeometry;
  16355. // RingBufferGeometry
  16356. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16357. BufferGeometry.call( this );
  16358. this.type = 'RingBufferGeometry';
  16359. this.parameters = {
  16360. innerRadius: innerRadius,
  16361. outerRadius: outerRadius,
  16362. thetaSegments: thetaSegments,
  16363. phiSegments: phiSegments,
  16364. thetaStart: thetaStart,
  16365. thetaLength: thetaLength
  16366. };
  16367. innerRadius = innerRadius || 20;
  16368. outerRadius = outerRadius || 50;
  16369. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16370. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16371. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16372. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16373. // buffers
  16374. var indices = [];
  16375. var vertices = [];
  16376. var normals = [];
  16377. var uvs = [];
  16378. // some helper variables
  16379. var segment;
  16380. var radius = innerRadius;
  16381. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16382. var vertex = new Vector3();
  16383. var uv = new Vector2();
  16384. var j, i;
  16385. // generate vertices, normals and uvs
  16386. for ( j = 0; j <= phiSegments; j ++ ) {
  16387. for ( i = 0; i <= thetaSegments; i ++ ) {
  16388. // values are generate from the inside of the ring to the outside
  16389. segment = thetaStart + i / thetaSegments * thetaLength;
  16390. // vertex
  16391. vertex.x = radius * Math.cos( segment );
  16392. vertex.y = radius * Math.sin( segment );
  16393. vertices.push( vertex.x, vertex.y, vertex.z );
  16394. // normal
  16395. normals.push( 0, 0, 1 );
  16396. // uv
  16397. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16398. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16399. uvs.push( uv.x, uv.y );
  16400. }
  16401. // increase the radius for next row of vertices
  16402. radius += radiusStep;
  16403. }
  16404. // indices
  16405. for ( j = 0; j < phiSegments; j ++ ) {
  16406. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16407. for ( i = 0; i < thetaSegments; i ++ ) {
  16408. segment = i + thetaSegmentLevel;
  16409. var a = segment;
  16410. var b = segment + thetaSegments + 1;
  16411. var c = segment + thetaSegments + 2;
  16412. var d = segment + 1;
  16413. // faces
  16414. indices.push( a, b, d );
  16415. indices.push( b, c, d );
  16416. }
  16417. }
  16418. // build geometry
  16419. this.setIndex( indices );
  16420. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16421. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16422. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16423. }
  16424. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16425. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16426. /**
  16427. * @author astrodud / http://astrodud.isgreat.org/
  16428. * @author zz85 / https://github.com/zz85
  16429. * @author bhouston / http://clara.io
  16430. * @author Mugen87 / https://github.com/Mugen87
  16431. */
  16432. // LatheGeometry
  16433. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16434. Geometry.call( this );
  16435. this.type = 'LatheGeometry';
  16436. this.parameters = {
  16437. points: points,
  16438. segments: segments,
  16439. phiStart: phiStart,
  16440. phiLength: phiLength
  16441. };
  16442. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16443. this.mergeVertices();
  16444. }
  16445. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16446. LatheGeometry.prototype.constructor = LatheGeometry;
  16447. // LatheBufferGeometry
  16448. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16449. BufferGeometry.call( this );
  16450. this.type = 'LatheBufferGeometry';
  16451. this.parameters = {
  16452. points: points,
  16453. segments: segments,
  16454. phiStart: phiStart,
  16455. phiLength: phiLength
  16456. };
  16457. segments = Math.floor( segments ) || 12;
  16458. phiStart = phiStart || 0;
  16459. phiLength = phiLength || Math.PI * 2;
  16460. // clamp phiLength so it's in range of [ 0, 2PI ]
  16461. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16462. // buffers
  16463. var indices = [];
  16464. var vertices = [];
  16465. var uvs = [];
  16466. // helper variables
  16467. var base;
  16468. var inverseSegments = 1.0 / segments;
  16469. var vertex = new Vector3();
  16470. var uv = new Vector2();
  16471. var i, j;
  16472. // generate vertices and uvs
  16473. for ( i = 0; i <= segments; i ++ ) {
  16474. var phi = phiStart + i * inverseSegments * phiLength;
  16475. var sin = Math.sin( phi );
  16476. var cos = Math.cos( phi );
  16477. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16478. // vertex
  16479. vertex.x = points[ j ].x * sin;
  16480. vertex.y = points[ j ].y;
  16481. vertex.z = points[ j ].x * cos;
  16482. vertices.push( vertex.x, vertex.y, vertex.z );
  16483. // uv
  16484. uv.x = i / segments;
  16485. uv.y = j / ( points.length - 1 );
  16486. uvs.push( uv.x, uv.y );
  16487. }
  16488. }
  16489. // indices
  16490. for ( i = 0; i < segments; i ++ ) {
  16491. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16492. base = j + i * points.length;
  16493. var a = base;
  16494. var b = base + points.length;
  16495. var c = base + points.length + 1;
  16496. var d = base + 1;
  16497. // faces
  16498. indices.push( a, b, d );
  16499. indices.push( b, c, d );
  16500. }
  16501. }
  16502. // build geometry
  16503. this.setIndex( indices );
  16504. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16505. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16506. // generate normals
  16507. this.computeVertexNormals();
  16508. // if the geometry is closed, we need to average the normals along the seam.
  16509. // because the corresponding vertices are identical (but still have different UVs).
  16510. if ( phiLength === Math.PI * 2 ) {
  16511. var normals = this.attributes.normal.array;
  16512. var n1 = new Vector3();
  16513. var n2 = new Vector3();
  16514. var n = new Vector3();
  16515. // this is the buffer offset for the last line of vertices
  16516. base = segments * points.length * 3;
  16517. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16518. // select the normal of the vertex in the first line
  16519. n1.x = normals[ j + 0 ];
  16520. n1.y = normals[ j + 1 ];
  16521. n1.z = normals[ j + 2 ];
  16522. // select the normal of the vertex in the last line
  16523. n2.x = normals[ base + j + 0 ];
  16524. n2.y = normals[ base + j + 1 ];
  16525. n2.z = normals[ base + j + 2 ];
  16526. // average normals
  16527. n.addVectors( n1, n2 ).normalize();
  16528. // assign the new values to both normals
  16529. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16530. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16531. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16532. }
  16533. }
  16534. }
  16535. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16536. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16537. /**
  16538. * @author jonobr1 / http://jonobr1.com
  16539. * @author Mugen87 / https://github.com/Mugen87
  16540. */
  16541. // ShapeGeometry
  16542. function ShapeGeometry( shapes, curveSegments ) {
  16543. Geometry.call( this );
  16544. this.type = 'ShapeGeometry';
  16545. if ( typeof curveSegments === 'object' ) {
  16546. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16547. curveSegments = curveSegments.curveSegments;
  16548. }
  16549. this.parameters = {
  16550. shapes: shapes,
  16551. curveSegments: curveSegments
  16552. };
  16553. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16554. this.mergeVertices();
  16555. }
  16556. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16557. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16558. // ShapeBufferGeometry
  16559. function ShapeBufferGeometry( shapes, curveSegments ) {
  16560. BufferGeometry.call( this );
  16561. this.type = 'ShapeBufferGeometry';
  16562. this.parameters = {
  16563. shapes: shapes,
  16564. curveSegments: curveSegments
  16565. };
  16566. curveSegments = curveSegments || 12;
  16567. // buffers
  16568. var indices = [];
  16569. var vertices = [];
  16570. var normals = [];
  16571. var uvs = [];
  16572. // helper variables
  16573. var groupStart = 0;
  16574. var groupCount = 0;
  16575. // allow single and array values for "shapes" parameter
  16576. if ( Array.isArray( shapes ) === false ) {
  16577. addShape( shapes );
  16578. } else {
  16579. for ( var i = 0; i < shapes.length; i ++ ) {
  16580. addShape( shapes[ i ] );
  16581. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16582. groupStart += groupCount;
  16583. groupCount = 0;
  16584. }
  16585. }
  16586. // build geometry
  16587. this.setIndex( indices );
  16588. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16589. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16590. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16591. // helper functions
  16592. function addShape( shape ) {
  16593. var i, l, shapeHole;
  16594. var indexOffset = vertices.length / 3;
  16595. var points = shape.extractPoints( curveSegments );
  16596. var shapeVertices = points.shape;
  16597. var shapeHoles = points.holes;
  16598. // check direction of vertices
  16599. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16600. shapeVertices = shapeVertices.reverse();
  16601. // also check if holes are in the opposite direction
  16602. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16603. shapeHole = shapeHoles[ i ];
  16604. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16605. shapeHoles[ i ] = shapeHole.reverse();
  16606. }
  16607. }
  16608. }
  16609. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16610. // join vertices of inner and outer paths to a single array
  16611. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16612. shapeHole = shapeHoles[ i ];
  16613. shapeVertices = shapeVertices.concat( shapeHole );
  16614. }
  16615. // vertices, normals, uvs
  16616. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16617. var vertex = shapeVertices[ i ];
  16618. vertices.push( vertex.x, vertex.y, 0 );
  16619. normals.push( 0, 0, 1 );
  16620. uvs.push( vertex.x, vertex.y ); // world uvs
  16621. }
  16622. // incides
  16623. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16624. var face = faces[ i ];
  16625. var a = face[ 0 ] + indexOffset;
  16626. var b = face[ 1 ] + indexOffset;
  16627. var c = face[ 2 ] + indexOffset;
  16628. indices.push( a, b, c );
  16629. groupCount += 3;
  16630. }
  16631. }
  16632. }
  16633. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16634. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16635. /**
  16636. * @author WestLangley / http://github.com/WestLangley
  16637. * @author Mugen87 / https://github.com/Mugen87
  16638. */
  16639. function EdgesGeometry( geometry, thresholdAngle ) {
  16640. BufferGeometry.call( this );
  16641. this.type = 'EdgesGeometry';
  16642. this.parameters = {
  16643. thresholdAngle: thresholdAngle
  16644. };
  16645. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16646. // buffer
  16647. var vertices = [];
  16648. // helper variables
  16649. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16650. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16651. var key, keys = [ 'a', 'b', 'c' ];
  16652. // prepare source geometry
  16653. var geometry2;
  16654. if ( geometry.isBufferGeometry ) {
  16655. geometry2 = new Geometry();
  16656. geometry2.fromBufferGeometry( geometry );
  16657. } else {
  16658. geometry2 = geometry.clone();
  16659. }
  16660. geometry2.mergeVertices();
  16661. geometry2.computeFaceNormals();
  16662. var sourceVertices = geometry2.vertices;
  16663. var faces = geometry2.faces;
  16664. // now create a data structure where each entry represents an edge with its adjoining faces
  16665. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16666. var face = faces[ i ];
  16667. for ( var j = 0; j < 3; j ++ ) {
  16668. edge1 = face[ keys[ j ] ];
  16669. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16670. edge[ 0 ] = Math.min( edge1, edge2 );
  16671. edge[ 1 ] = Math.max( edge1, edge2 );
  16672. key = edge[ 0 ] + ',' + edge[ 1 ];
  16673. if ( edges[ key ] === undefined ) {
  16674. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16675. } else {
  16676. edges[ key ].face2 = i;
  16677. }
  16678. }
  16679. }
  16680. // generate vertices
  16681. for ( key in edges ) {
  16682. var e = edges[ key ];
  16683. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16684. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16685. var vertex = sourceVertices[ e.index1 ];
  16686. vertices.push( vertex.x, vertex.y, vertex.z );
  16687. vertex = sourceVertices[ e.index2 ];
  16688. vertices.push( vertex.x, vertex.y, vertex.z );
  16689. }
  16690. }
  16691. // build geometry
  16692. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16693. }
  16694. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16695. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16696. /**
  16697. * @author mrdoob / http://mrdoob.com/
  16698. * @author Mugen87 / https://github.com/Mugen87
  16699. */
  16700. // CylinderGeometry
  16701. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16702. Geometry.call( this );
  16703. this.type = 'CylinderGeometry';
  16704. this.parameters = {
  16705. radiusTop: radiusTop,
  16706. radiusBottom: radiusBottom,
  16707. height: height,
  16708. radialSegments: radialSegments,
  16709. heightSegments: heightSegments,
  16710. openEnded: openEnded,
  16711. thetaStart: thetaStart,
  16712. thetaLength: thetaLength
  16713. };
  16714. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16715. this.mergeVertices();
  16716. }
  16717. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16718. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16719. // CylinderBufferGeometry
  16720. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16721. BufferGeometry.call( this );
  16722. this.type = 'CylinderBufferGeometry';
  16723. this.parameters = {
  16724. radiusTop: radiusTop,
  16725. radiusBottom: radiusBottom,
  16726. height: height,
  16727. radialSegments: radialSegments,
  16728. heightSegments: heightSegments,
  16729. openEnded: openEnded,
  16730. thetaStart: thetaStart,
  16731. thetaLength: thetaLength
  16732. };
  16733. var scope = this;
  16734. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16735. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16736. height = height !== undefined ? height : 100;
  16737. radialSegments = Math.floor( radialSegments ) || 8;
  16738. heightSegments = Math.floor( heightSegments ) || 1;
  16739. openEnded = openEnded !== undefined ? openEnded : false;
  16740. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16741. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16742. // buffers
  16743. var indices = [];
  16744. var vertices = [];
  16745. var normals = [];
  16746. var uvs = [];
  16747. // helper variables
  16748. var index = 0;
  16749. var indexArray = [];
  16750. var halfHeight = height / 2;
  16751. var groupStart = 0;
  16752. // generate geometry
  16753. generateTorso();
  16754. if ( openEnded === false ) {
  16755. if ( radiusTop > 0 ) generateCap( true );
  16756. if ( radiusBottom > 0 ) generateCap( false );
  16757. }
  16758. // build geometry
  16759. this.setIndex( indices );
  16760. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16761. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16762. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16763. function generateTorso() {
  16764. var x, y;
  16765. var normal = new Vector3();
  16766. var vertex = new Vector3();
  16767. var groupCount = 0;
  16768. // this will be used to calculate the normal
  16769. var slope = ( radiusBottom - radiusTop ) / height;
  16770. // generate vertices, normals and uvs
  16771. for ( y = 0; y <= heightSegments; y ++ ) {
  16772. var indexRow = [];
  16773. var v = y / heightSegments;
  16774. // calculate the radius of the current row
  16775. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16776. for ( x = 0; x <= radialSegments; x ++ ) {
  16777. var u = x / radialSegments;
  16778. var theta = u * thetaLength + thetaStart;
  16779. var sinTheta = Math.sin( theta );
  16780. var cosTheta = Math.cos( theta );
  16781. // vertex
  16782. vertex.x = radius * sinTheta;
  16783. vertex.y = - v * height + halfHeight;
  16784. vertex.z = radius * cosTheta;
  16785. vertices.push( vertex.x, vertex.y, vertex.z );
  16786. // normal
  16787. normal.set( sinTheta, slope, cosTheta ).normalize();
  16788. normals.push( normal.x, normal.y, normal.z );
  16789. // uv
  16790. uvs.push( u, 1 - v );
  16791. // save index of vertex in respective row
  16792. indexRow.push( index ++ );
  16793. }
  16794. // now save vertices of the row in our index array
  16795. indexArray.push( indexRow );
  16796. }
  16797. // generate indices
  16798. for ( x = 0; x < radialSegments; x ++ ) {
  16799. for ( y = 0; y < heightSegments; y ++ ) {
  16800. // we use the index array to access the correct indices
  16801. var a = indexArray[ y ][ x ];
  16802. var b = indexArray[ y + 1 ][ x ];
  16803. var c = indexArray[ y + 1 ][ x + 1 ];
  16804. var d = indexArray[ y ][ x + 1 ];
  16805. // faces
  16806. indices.push( a, b, d );
  16807. indices.push( b, c, d );
  16808. // update group counter
  16809. groupCount += 6;
  16810. }
  16811. }
  16812. // add a group to the geometry. this will ensure multi material support
  16813. scope.addGroup( groupStart, groupCount, 0 );
  16814. // calculate new start value for groups
  16815. groupStart += groupCount;
  16816. }
  16817. function generateCap( top ) {
  16818. var x, centerIndexStart, centerIndexEnd;
  16819. var uv = new Vector2();
  16820. var vertex = new Vector3();
  16821. var groupCount = 0;
  16822. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16823. var sign = ( top === true ) ? 1 : - 1;
  16824. // save the index of the first center vertex
  16825. centerIndexStart = index;
  16826. // first we generate the center vertex data of the cap.
  16827. // because the geometry needs one set of uvs per face,
  16828. // we must generate a center vertex per face/segment
  16829. for ( x = 1; x <= radialSegments; x ++ ) {
  16830. // vertex
  16831. vertices.push( 0, halfHeight * sign, 0 );
  16832. // normal
  16833. normals.push( 0, sign, 0 );
  16834. // uv
  16835. uvs.push( 0.5, 0.5 );
  16836. // increase index
  16837. index ++;
  16838. }
  16839. // save the index of the last center vertex
  16840. centerIndexEnd = index;
  16841. // now we generate the surrounding vertices, normals and uvs
  16842. for ( x = 0; x <= radialSegments; x ++ ) {
  16843. var u = x / radialSegments;
  16844. var theta = u * thetaLength + thetaStart;
  16845. var cosTheta = Math.cos( theta );
  16846. var sinTheta = Math.sin( theta );
  16847. // vertex
  16848. vertex.x = radius * sinTheta;
  16849. vertex.y = halfHeight * sign;
  16850. vertex.z = radius * cosTheta;
  16851. vertices.push( vertex.x, vertex.y, vertex.z );
  16852. // normal
  16853. normals.push( 0, sign, 0 );
  16854. // uv
  16855. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16856. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16857. uvs.push( uv.x, uv.y );
  16858. // increase index
  16859. index ++;
  16860. }
  16861. // generate indices
  16862. for ( x = 0; x < radialSegments; x ++ ) {
  16863. var c = centerIndexStart + x;
  16864. var i = centerIndexEnd + x;
  16865. if ( top === true ) {
  16866. // face top
  16867. indices.push( i, i + 1, c );
  16868. } else {
  16869. // face bottom
  16870. indices.push( i + 1, i, c );
  16871. }
  16872. groupCount += 3;
  16873. }
  16874. // add a group to the geometry. this will ensure multi material support
  16875. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16876. // calculate new start value for groups
  16877. groupStart += groupCount;
  16878. }
  16879. }
  16880. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16881. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16882. /**
  16883. * @author abelnation / http://github.com/abelnation
  16884. */
  16885. // ConeGeometry
  16886. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16887. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16888. this.type = 'ConeGeometry';
  16889. this.parameters = {
  16890. radius: radius,
  16891. height: height,
  16892. radialSegments: radialSegments,
  16893. heightSegments: heightSegments,
  16894. openEnded: openEnded,
  16895. thetaStart: thetaStart,
  16896. thetaLength: thetaLength
  16897. };
  16898. }
  16899. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16900. ConeGeometry.prototype.constructor = ConeGeometry;
  16901. // ConeBufferGeometry
  16902. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16903. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16904. this.type = 'ConeBufferGeometry';
  16905. this.parameters = {
  16906. radius: radius,
  16907. height: height,
  16908. radialSegments: radialSegments,
  16909. heightSegments: heightSegments,
  16910. openEnded: openEnded,
  16911. thetaStart: thetaStart,
  16912. thetaLength: thetaLength
  16913. };
  16914. }
  16915. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16916. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16917. /**
  16918. * @author benaadams / https://twitter.com/ben_a_adams
  16919. * @author Mugen87 / https://github.com/Mugen87
  16920. * @author hughes
  16921. */
  16922. // CircleGeometry
  16923. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16924. Geometry.call( this );
  16925. this.type = 'CircleGeometry';
  16926. this.parameters = {
  16927. radius: radius,
  16928. segments: segments,
  16929. thetaStart: thetaStart,
  16930. thetaLength: thetaLength
  16931. };
  16932. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16933. this.mergeVertices();
  16934. }
  16935. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16936. CircleGeometry.prototype.constructor = CircleGeometry;
  16937. // CircleBufferGeometry
  16938. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16939. BufferGeometry.call( this );
  16940. this.type = 'CircleBufferGeometry';
  16941. this.parameters = {
  16942. radius: radius,
  16943. segments: segments,
  16944. thetaStart: thetaStart,
  16945. thetaLength: thetaLength
  16946. };
  16947. radius = radius || 50;
  16948. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16949. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16950. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16951. // buffers
  16952. var indices = [];
  16953. var vertices = [];
  16954. var normals = [];
  16955. var uvs = [];
  16956. // helper variables
  16957. var i, s;
  16958. var vertex = new Vector3();
  16959. var uv = new Vector2();
  16960. // center point
  16961. vertices.push( 0, 0, 0 );
  16962. normals.push( 0, 0, 1 );
  16963. uvs.push( 0.5, 0.5 );
  16964. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  16965. var segment = thetaStart + s / segments * thetaLength;
  16966. // vertex
  16967. vertex.x = radius * Math.cos( segment );
  16968. vertex.y = radius * Math.sin( segment );
  16969. vertices.push( vertex.x, vertex.y, vertex.z );
  16970. // normal
  16971. normals.push( 0, 0, 1 );
  16972. // uvs
  16973. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  16974. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  16975. uvs.push( uv.x, uv.y );
  16976. }
  16977. // indices
  16978. for ( i = 1; i <= segments; i ++ ) {
  16979. indices.push( i, i + 1, 0 );
  16980. }
  16981. // build geometry
  16982. this.setIndex( indices );
  16983. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16984. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16985. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16986. }
  16987. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16988. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16989. var Geometries = Object.freeze({
  16990. WireframeGeometry: WireframeGeometry,
  16991. ParametricGeometry: ParametricGeometry,
  16992. ParametricBufferGeometry: ParametricBufferGeometry,
  16993. TetrahedronGeometry: TetrahedronGeometry,
  16994. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16995. OctahedronGeometry: OctahedronGeometry,
  16996. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16997. IcosahedronGeometry: IcosahedronGeometry,
  16998. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16999. DodecahedronGeometry: DodecahedronGeometry,
  17000. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17001. PolyhedronGeometry: PolyhedronGeometry,
  17002. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17003. TubeGeometry: TubeGeometry,
  17004. TubeBufferGeometry: TubeBufferGeometry,
  17005. TorusKnotGeometry: TorusKnotGeometry,
  17006. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17007. TorusGeometry: TorusGeometry,
  17008. TorusBufferGeometry: TorusBufferGeometry,
  17009. TextGeometry: TextGeometry,
  17010. TextBufferGeometry: TextBufferGeometry,
  17011. SphereGeometry: SphereGeometry,
  17012. SphereBufferGeometry: SphereBufferGeometry,
  17013. RingGeometry: RingGeometry,
  17014. RingBufferGeometry: RingBufferGeometry,
  17015. PlaneGeometry: PlaneGeometry,
  17016. PlaneBufferGeometry: PlaneBufferGeometry,
  17017. LatheGeometry: LatheGeometry,
  17018. LatheBufferGeometry: LatheBufferGeometry,
  17019. ShapeGeometry: ShapeGeometry,
  17020. ShapeBufferGeometry: ShapeBufferGeometry,
  17021. ExtrudeGeometry: ExtrudeGeometry,
  17022. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17023. EdgesGeometry: EdgesGeometry,
  17024. ConeGeometry: ConeGeometry,
  17025. ConeBufferGeometry: ConeBufferGeometry,
  17026. CylinderGeometry: CylinderGeometry,
  17027. CylinderBufferGeometry: CylinderBufferGeometry,
  17028. CircleGeometry: CircleGeometry,
  17029. CircleBufferGeometry: CircleBufferGeometry,
  17030. BoxGeometry: BoxGeometry,
  17031. BoxBufferGeometry: BoxBufferGeometry
  17032. });
  17033. /**
  17034. * @author mrdoob / http://mrdoob.com/
  17035. *
  17036. * parameters = {
  17037. * opacity: <float>
  17038. * }
  17039. */
  17040. function ShadowMaterial( parameters ) {
  17041. ShaderMaterial.call( this, {
  17042. uniforms: UniformsUtils.merge( [
  17043. UniformsLib.lights,
  17044. {
  17045. opacity: { value: 1.0 }
  17046. }
  17047. ] ),
  17048. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17049. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17050. } );
  17051. this.lights = true;
  17052. this.transparent = true;
  17053. Object.defineProperties( this, {
  17054. opacity: {
  17055. enumerable: true,
  17056. get: function () {
  17057. return this.uniforms.opacity.value;
  17058. },
  17059. set: function ( value ) {
  17060. this.uniforms.opacity.value = value;
  17061. }
  17062. }
  17063. } );
  17064. this.setValues( parameters );
  17065. }
  17066. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17067. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17068. ShadowMaterial.prototype.isShadowMaterial = true;
  17069. /**
  17070. * @author mrdoob / http://mrdoob.com/
  17071. */
  17072. function RawShaderMaterial( parameters ) {
  17073. ShaderMaterial.call( this, parameters );
  17074. this.type = 'RawShaderMaterial';
  17075. }
  17076. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17077. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17078. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17079. /**
  17080. * @author WestLangley / http://github.com/WestLangley
  17081. *
  17082. * parameters = {
  17083. * color: <hex>,
  17084. * roughness: <float>,
  17085. * metalness: <float>,
  17086. * opacity: <float>,
  17087. *
  17088. * map: new THREE.Texture( <Image> ),
  17089. *
  17090. * lightMap: new THREE.Texture( <Image> ),
  17091. * lightMapIntensity: <float>
  17092. *
  17093. * aoMap: new THREE.Texture( <Image> ),
  17094. * aoMapIntensity: <float>
  17095. *
  17096. * emissive: <hex>,
  17097. * emissiveIntensity: <float>
  17098. * emissiveMap: new THREE.Texture( <Image> ),
  17099. *
  17100. * bumpMap: new THREE.Texture( <Image> ),
  17101. * bumpScale: <float>,
  17102. *
  17103. * normalMap: new THREE.Texture( <Image> ),
  17104. * normalScale: <Vector2>,
  17105. *
  17106. * displacementMap: new THREE.Texture( <Image> ),
  17107. * displacementScale: <float>,
  17108. * displacementBias: <float>,
  17109. *
  17110. * roughnessMap: new THREE.Texture( <Image> ),
  17111. *
  17112. * metalnessMap: new THREE.Texture( <Image> ),
  17113. *
  17114. * alphaMap: new THREE.Texture( <Image> ),
  17115. *
  17116. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17117. * envMapIntensity: <float>
  17118. *
  17119. * refractionRatio: <float>,
  17120. *
  17121. * wireframe: <boolean>,
  17122. * wireframeLinewidth: <float>,
  17123. *
  17124. * skinning: <bool>,
  17125. * morphTargets: <bool>,
  17126. * morphNormals: <bool>
  17127. * }
  17128. */
  17129. function MeshStandardMaterial( parameters ) {
  17130. Material.call( this );
  17131. this.defines = { 'STANDARD': '' };
  17132. this.type = 'MeshStandardMaterial';
  17133. this.color = new Color( 0xffffff ); // diffuse
  17134. this.roughness = 0.5;
  17135. this.metalness = 0.5;
  17136. this.map = null;
  17137. this.lightMap = null;
  17138. this.lightMapIntensity = 1.0;
  17139. this.aoMap = null;
  17140. this.aoMapIntensity = 1.0;
  17141. this.emissive = new Color( 0x000000 );
  17142. this.emissiveIntensity = 1.0;
  17143. this.emissiveMap = null;
  17144. this.bumpMap = null;
  17145. this.bumpScale = 1;
  17146. this.normalMap = null;
  17147. this.normalScale = new Vector2( 1, 1 );
  17148. this.displacementMap = null;
  17149. this.displacementScale = 1;
  17150. this.displacementBias = 0;
  17151. this.roughnessMap = null;
  17152. this.metalnessMap = null;
  17153. this.alphaMap = null;
  17154. this.envMap = null;
  17155. this.envMapIntensity = 1.0;
  17156. this.refractionRatio = 0.98;
  17157. this.wireframe = false;
  17158. this.wireframeLinewidth = 1;
  17159. this.wireframeLinecap = 'round';
  17160. this.wireframeLinejoin = 'round';
  17161. this.skinning = false;
  17162. this.morphTargets = false;
  17163. this.morphNormals = false;
  17164. this.setValues( parameters );
  17165. }
  17166. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17167. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17168. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17169. MeshStandardMaterial.prototype.copy = function ( source ) {
  17170. Material.prototype.copy.call( this, source );
  17171. this.defines = { 'STANDARD': '' };
  17172. this.color.copy( source.color );
  17173. this.roughness = source.roughness;
  17174. this.metalness = source.metalness;
  17175. this.map = source.map;
  17176. this.lightMap = source.lightMap;
  17177. this.lightMapIntensity = source.lightMapIntensity;
  17178. this.aoMap = source.aoMap;
  17179. this.aoMapIntensity = source.aoMapIntensity;
  17180. this.emissive.copy( source.emissive );
  17181. this.emissiveMap = source.emissiveMap;
  17182. this.emissiveIntensity = source.emissiveIntensity;
  17183. this.bumpMap = source.bumpMap;
  17184. this.bumpScale = source.bumpScale;
  17185. this.normalMap = source.normalMap;
  17186. this.normalScale.copy( source.normalScale );
  17187. this.displacementMap = source.displacementMap;
  17188. this.displacementScale = source.displacementScale;
  17189. this.displacementBias = source.displacementBias;
  17190. this.roughnessMap = source.roughnessMap;
  17191. this.metalnessMap = source.metalnessMap;
  17192. this.alphaMap = source.alphaMap;
  17193. this.envMap = source.envMap;
  17194. this.envMapIntensity = source.envMapIntensity;
  17195. this.refractionRatio = source.refractionRatio;
  17196. this.wireframe = source.wireframe;
  17197. this.wireframeLinewidth = source.wireframeLinewidth;
  17198. this.wireframeLinecap = source.wireframeLinecap;
  17199. this.wireframeLinejoin = source.wireframeLinejoin;
  17200. this.skinning = source.skinning;
  17201. this.morphTargets = source.morphTargets;
  17202. this.morphNormals = source.morphNormals;
  17203. return this;
  17204. };
  17205. /**
  17206. * @author WestLangley / http://github.com/WestLangley
  17207. *
  17208. * parameters = {
  17209. * reflectivity: <float>
  17210. * }
  17211. */
  17212. function MeshPhysicalMaterial( parameters ) {
  17213. MeshStandardMaterial.call( this );
  17214. this.defines = { 'PHYSICAL': '' };
  17215. this.type = 'MeshPhysicalMaterial';
  17216. this.reflectivity = 0.5; // maps to F0 = 0.04
  17217. this.clearCoat = 0.0;
  17218. this.clearCoatRoughness = 0.0;
  17219. this.setValues( parameters );
  17220. }
  17221. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17222. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17223. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17224. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17225. MeshStandardMaterial.prototype.copy.call( this, source );
  17226. this.defines = { 'PHYSICAL': '' };
  17227. this.reflectivity = source.reflectivity;
  17228. this.clearCoat = source.clearCoat;
  17229. this.clearCoatRoughness = source.clearCoatRoughness;
  17230. return this;
  17231. };
  17232. /**
  17233. * @author mrdoob / http://mrdoob.com/
  17234. * @author alteredq / http://alteredqualia.com/
  17235. *
  17236. * parameters = {
  17237. * color: <hex>,
  17238. * specular: <hex>,
  17239. * shininess: <float>,
  17240. * opacity: <float>,
  17241. *
  17242. * map: new THREE.Texture( <Image> ),
  17243. *
  17244. * lightMap: new THREE.Texture( <Image> ),
  17245. * lightMapIntensity: <float>
  17246. *
  17247. * aoMap: new THREE.Texture( <Image> ),
  17248. * aoMapIntensity: <float>
  17249. *
  17250. * emissive: <hex>,
  17251. * emissiveIntensity: <float>
  17252. * emissiveMap: new THREE.Texture( <Image> ),
  17253. *
  17254. * bumpMap: new THREE.Texture( <Image> ),
  17255. * bumpScale: <float>,
  17256. *
  17257. * normalMap: new THREE.Texture( <Image> ),
  17258. * normalScale: <Vector2>,
  17259. *
  17260. * displacementMap: new THREE.Texture( <Image> ),
  17261. * displacementScale: <float>,
  17262. * displacementBias: <float>,
  17263. *
  17264. * specularMap: new THREE.Texture( <Image> ),
  17265. *
  17266. * alphaMap: new THREE.Texture( <Image> ),
  17267. *
  17268. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17269. * combine: THREE.Multiply,
  17270. * reflectivity: <float>,
  17271. * refractionRatio: <float>,
  17272. *
  17273. * wireframe: <boolean>,
  17274. * wireframeLinewidth: <float>,
  17275. *
  17276. * skinning: <bool>,
  17277. * morphTargets: <bool>,
  17278. * morphNormals: <bool>
  17279. * }
  17280. */
  17281. function MeshPhongMaterial( parameters ) {
  17282. Material.call( this );
  17283. this.type = 'MeshPhongMaterial';
  17284. this.color = new Color( 0xffffff ); // diffuse
  17285. this.specular = new Color( 0x111111 );
  17286. this.shininess = 30;
  17287. this.map = null;
  17288. this.lightMap = null;
  17289. this.lightMapIntensity = 1.0;
  17290. this.aoMap = null;
  17291. this.aoMapIntensity = 1.0;
  17292. this.emissive = new Color( 0x000000 );
  17293. this.emissiveIntensity = 1.0;
  17294. this.emissiveMap = null;
  17295. this.bumpMap = null;
  17296. this.bumpScale = 1;
  17297. this.normalMap = null;
  17298. this.normalScale = new Vector2( 1, 1 );
  17299. this.displacementMap = null;
  17300. this.displacementScale = 1;
  17301. this.displacementBias = 0;
  17302. this.specularMap = null;
  17303. this.alphaMap = null;
  17304. this.envMap = null;
  17305. this.combine = MultiplyOperation;
  17306. this.reflectivity = 1;
  17307. this.refractionRatio = 0.98;
  17308. this.wireframe = false;
  17309. this.wireframeLinewidth = 1;
  17310. this.wireframeLinecap = 'round';
  17311. this.wireframeLinejoin = 'round';
  17312. this.skinning = false;
  17313. this.morphTargets = false;
  17314. this.morphNormals = false;
  17315. this.setValues( parameters );
  17316. }
  17317. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17318. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17319. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17320. MeshPhongMaterial.prototype.copy = function ( source ) {
  17321. Material.prototype.copy.call( this, source );
  17322. this.color.copy( source.color );
  17323. this.specular.copy( source.specular );
  17324. this.shininess = source.shininess;
  17325. this.map = source.map;
  17326. this.lightMap = source.lightMap;
  17327. this.lightMapIntensity = source.lightMapIntensity;
  17328. this.aoMap = source.aoMap;
  17329. this.aoMapIntensity = source.aoMapIntensity;
  17330. this.emissive.copy( source.emissive );
  17331. this.emissiveMap = source.emissiveMap;
  17332. this.emissiveIntensity = source.emissiveIntensity;
  17333. this.bumpMap = source.bumpMap;
  17334. this.bumpScale = source.bumpScale;
  17335. this.normalMap = source.normalMap;
  17336. this.normalScale.copy( source.normalScale );
  17337. this.displacementMap = source.displacementMap;
  17338. this.displacementScale = source.displacementScale;
  17339. this.displacementBias = source.displacementBias;
  17340. this.specularMap = source.specularMap;
  17341. this.alphaMap = source.alphaMap;
  17342. this.envMap = source.envMap;
  17343. this.combine = source.combine;
  17344. this.reflectivity = source.reflectivity;
  17345. this.refractionRatio = source.refractionRatio;
  17346. this.wireframe = source.wireframe;
  17347. this.wireframeLinewidth = source.wireframeLinewidth;
  17348. this.wireframeLinecap = source.wireframeLinecap;
  17349. this.wireframeLinejoin = source.wireframeLinejoin;
  17350. this.skinning = source.skinning;
  17351. this.morphTargets = source.morphTargets;
  17352. this.morphNormals = source.morphNormals;
  17353. return this;
  17354. };
  17355. /**
  17356. * @author takahirox / http://github.com/takahirox
  17357. *
  17358. * parameters = {
  17359. * gradientMap: new THREE.Texture( <Image> )
  17360. * }
  17361. */
  17362. function MeshToonMaterial( parameters ) {
  17363. MeshPhongMaterial.call( this );
  17364. this.defines = { 'TOON': '' };
  17365. this.type = 'MeshToonMaterial';
  17366. this.gradientMap = null;
  17367. this.setValues( parameters );
  17368. }
  17369. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17370. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17371. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17372. MeshToonMaterial.prototype.copy = function ( source ) {
  17373. MeshPhongMaterial.prototype.copy.call( this, source );
  17374. this.gradientMap = source.gradientMap;
  17375. return this;
  17376. };
  17377. /**
  17378. * @author mrdoob / http://mrdoob.com/
  17379. * @author WestLangley / http://github.com/WestLangley
  17380. *
  17381. * parameters = {
  17382. * opacity: <float>,
  17383. *
  17384. * bumpMap: new THREE.Texture( <Image> ),
  17385. * bumpScale: <float>,
  17386. *
  17387. * normalMap: new THREE.Texture( <Image> ),
  17388. * normalScale: <Vector2>,
  17389. *
  17390. * displacementMap: new THREE.Texture( <Image> ),
  17391. * displacementScale: <float>,
  17392. * displacementBias: <float>,
  17393. *
  17394. * wireframe: <boolean>,
  17395. * wireframeLinewidth: <float>
  17396. *
  17397. * skinning: <bool>,
  17398. * morphTargets: <bool>,
  17399. * morphNormals: <bool>
  17400. * }
  17401. */
  17402. function MeshNormalMaterial( parameters ) {
  17403. Material.call( this, parameters );
  17404. this.type = 'MeshNormalMaterial';
  17405. this.bumpMap = null;
  17406. this.bumpScale = 1;
  17407. this.normalMap = null;
  17408. this.normalScale = new Vector2( 1, 1 );
  17409. this.displacementMap = null;
  17410. this.displacementScale = 1;
  17411. this.displacementBias = 0;
  17412. this.wireframe = false;
  17413. this.wireframeLinewidth = 1;
  17414. this.fog = false;
  17415. this.lights = false;
  17416. this.skinning = false;
  17417. this.morphTargets = false;
  17418. this.morphNormals = false;
  17419. this.setValues( parameters );
  17420. }
  17421. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17422. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17423. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17424. MeshNormalMaterial.prototype.copy = function ( source ) {
  17425. Material.prototype.copy.call( this, source );
  17426. this.bumpMap = source.bumpMap;
  17427. this.bumpScale = source.bumpScale;
  17428. this.normalMap = source.normalMap;
  17429. this.normalScale.copy( source.normalScale );
  17430. this.displacementMap = source.displacementMap;
  17431. this.displacementScale = source.displacementScale;
  17432. this.displacementBias = source.displacementBias;
  17433. this.wireframe = source.wireframe;
  17434. this.wireframeLinewidth = source.wireframeLinewidth;
  17435. this.skinning = source.skinning;
  17436. this.morphTargets = source.morphTargets;
  17437. this.morphNormals = source.morphNormals;
  17438. return this;
  17439. };
  17440. /**
  17441. * @author mrdoob / http://mrdoob.com/
  17442. * @author alteredq / http://alteredqualia.com/
  17443. *
  17444. * parameters = {
  17445. * color: <hex>,
  17446. * opacity: <float>,
  17447. *
  17448. * map: new THREE.Texture( <Image> ),
  17449. *
  17450. * lightMap: new THREE.Texture( <Image> ),
  17451. * lightMapIntensity: <float>
  17452. *
  17453. * aoMap: new THREE.Texture( <Image> ),
  17454. * aoMapIntensity: <float>
  17455. *
  17456. * emissive: <hex>,
  17457. * emissiveIntensity: <float>
  17458. * emissiveMap: new THREE.Texture( <Image> ),
  17459. *
  17460. * specularMap: new THREE.Texture( <Image> ),
  17461. *
  17462. * alphaMap: new THREE.Texture( <Image> ),
  17463. *
  17464. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17465. * combine: THREE.Multiply,
  17466. * reflectivity: <float>,
  17467. * refractionRatio: <float>,
  17468. *
  17469. * wireframe: <boolean>,
  17470. * wireframeLinewidth: <float>,
  17471. *
  17472. * skinning: <bool>,
  17473. * morphTargets: <bool>,
  17474. * morphNormals: <bool>
  17475. * }
  17476. */
  17477. function MeshLambertMaterial( parameters ) {
  17478. Material.call( this );
  17479. this.type = 'MeshLambertMaterial';
  17480. this.color = new Color( 0xffffff ); // diffuse
  17481. this.map = null;
  17482. this.lightMap = null;
  17483. this.lightMapIntensity = 1.0;
  17484. this.aoMap = null;
  17485. this.aoMapIntensity = 1.0;
  17486. this.emissive = new Color( 0x000000 );
  17487. this.emissiveIntensity = 1.0;
  17488. this.emissiveMap = null;
  17489. this.specularMap = null;
  17490. this.alphaMap = null;
  17491. this.envMap = null;
  17492. this.combine = MultiplyOperation;
  17493. this.reflectivity = 1;
  17494. this.refractionRatio = 0.98;
  17495. this.wireframe = false;
  17496. this.wireframeLinewidth = 1;
  17497. this.wireframeLinecap = 'round';
  17498. this.wireframeLinejoin = 'round';
  17499. this.skinning = false;
  17500. this.morphTargets = false;
  17501. this.morphNormals = false;
  17502. this.setValues( parameters );
  17503. }
  17504. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17505. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17506. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17507. MeshLambertMaterial.prototype.copy = function ( source ) {
  17508. Material.prototype.copy.call( this, source );
  17509. this.color.copy( source.color );
  17510. this.map = source.map;
  17511. this.lightMap = source.lightMap;
  17512. this.lightMapIntensity = source.lightMapIntensity;
  17513. this.aoMap = source.aoMap;
  17514. this.aoMapIntensity = source.aoMapIntensity;
  17515. this.emissive.copy( source.emissive );
  17516. this.emissiveMap = source.emissiveMap;
  17517. this.emissiveIntensity = source.emissiveIntensity;
  17518. this.specularMap = source.specularMap;
  17519. this.alphaMap = source.alphaMap;
  17520. this.envMap = source.envMap;
  17521. this.combine = source.combine;
  17522. this.reflectivity = source.reflectivity;
  17523. this.refractionRatio = source.refractionRatio;
  17524. this.wireframe = source.wireframe;
  17525. this.wireframeLinewidth = source.wireframeLinewidth;
  17526. this.wireframeLinecap = source.wireframeLinecap;
  17527. this.wireframeLinejoin = source.wireframeLinejoin;
  17528. this.skinning = source.skinning;
  17529. this.morphTargets = source.morphTargets;
  17530. this.morphNormals = source.morphNormals;
  17531. return this;
  17532. };
  17533. /**
  17534. * @author alteredq / http://alteredqualia.com/
  17535. *
  17536. * parameters = {
  17537. * color: <hex>,
  17538. * opacity: <float>,
  17539. *
  17540. * linewidth: <float>,
  17541. *
  17542. * scale: <float>,
  17543. * dashSize: <float>,
  17544. * gapSize: <float>
  17545. * }
  17546. */
  17547. function LineDashedMaterial( parameters ) {
  17548. Material.call( this );
  17549. this.type = 'LineDashedMaterial';
  17550. this.color = new Color( 0xffffff );
  17551. this.linewidth = 1;
  17552. this.scale = 1;
  17553. this.dashSize = 3;
  17554. this.gapSize = 1;
  17555. this.lights = false;
  17556. this.setValues( parameters );
  17557. }
  17558. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17559. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17560. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17561. LineDashedMaterial.prototype.copy = function ( source ) {
  17562. Material.prototype.copy.call( this, source );
  17563. this.color.copy( source.color );
  17564. this.linewidth = source.linewidth;
  17565. this.scale = source.scale;
  17566. this.dashSize = source.dashSize;
  17567. this.gapSize = source.gapSize;
  17568. return this;
  17569. };
  17570. var Materials = Object.freeze({
  17571. ShadowMaterial: ShadowMaterial,
  17572. SpriteMaterial: SpriteMaterial,
  17573. RawShaderMaterial: RawShaderMaterial,
  17574. ShaderMaterial: ShaderMaterial,
  17575. PointsMaterial: PointsMaterial,
  17576. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17577. MeshStandardMaterial: MeshStandardMaterial,
  17578. MeshPhongMaterial: MeshPhongMaterial,
  17579. MeshToonMaterial: MeshToonMaterial,
  17580. MeshNormalMaterial: MeshNormalMaterial,
  17581. MeshLambertMaterial: MeshLambertMaterial,
  17582. MeshDepthMaterial: MeshDepthMaterial,
  17583. MeshBasicMaterial: MeshBasicMaterial,
  17584. LineDashedMaterial: LineDashedMaterial,
  17585. LineBasicMaterial: LineBasicMaterial,
  17586. Material: Material
  17587. });
  17588. /**
  17589. * @author mrdoob / http://mrdoob.com/
  17590. */
  17591. var Cache = {
  17592. enabled: false,
  17593. files: {},
  17594. add: function ( key, file ) {
  17595. if ( this.enabled === false ) return;
  17596. // console.log( 'THREE.Cache', 'Adding key:', key );
  17597. this.files[ key ] = file;
  17598. },
  17599. get: function ( key ) {
  17600. if ( this.enabled === false ) return;
  17601. // console.log( 'THREE.Cache', 'Checking key:', key );
  17602. return this.files[ key ];
  17603. },
  17604. remove: function ( key ) {
  17605. delete this.files[ key ];
  17606. },
  17607. clear: function () {
  17608. this.files = {};
  17609. }
  17610. };
  17611. /**
  17612. * @author mrdoob / http://mrdoob.com/
  17613. */
  17614. function LoadingManager( onLoad, onProgress, onError ) {
  17615. var scope = this;
  17616. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17617. this.onStart = undefined;
  17618. this.onLoad = onLoad;
  17619. this.onProgress = onProgress;
  17620. this.onError = onError;
  17621. this.itemStart = function ( url ) {
  17622. itemsTotal ++;
  17623. if ( isLoading === false ) {
  17624. if ( scope.onStart !== undefined ) {
  17625. scope.onStart( url, itemsLoaded, itemsTotal );
  17626. }
  17627. }
  17628. isLoading = true;
  17629. };
  17630. this.itemEnd = function ( url ) {
  17631. itemsLoaded ++;
  17632. if ( scope.onProgress !== undefined ) {
  17633. scope.onProgress( url, itemsLoaded, itemsTotal );
  17634. }
  17635. if ( itemsLoaded === itemsTotal ) {
  17636. isLoading = false;
  17637. if ( scope.onLoad !== undefined ) {
  17638. scope.onLoad();
  17639. }
  17640. }
  17641. };
  17642. this.itemError = function ( url ) {
  17643. if ( scope.onError !== undefined ) {
  17644. scope.onError( url );
  17645. }
  17646. };
  17647. }
  17648. var DefaultLoadingManager = new LoadingManager();
  17649. /**
  17650. * @author mrdoob / http://mrdoob.com/
  17651. */
  17652. function FileLoader( manager ) {
  17653. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17654. }
  17655. Object.assign( FileLoader.prototype, {
  17656. load: function ( url, onLoad, onProgress, onError ) {
  17657. if ( url === undefined ) url = '';
  17658. if ( this.path !== undefined ) url = this.path + url;
  17659. var scope = this;
  17660. var cached = Cache.get( url );
  17661. if ( cached !== undefined ) {
  17662. scope.manager.itemStart( url );
  17663. setTimeout( function () {
  17664. if ( onLoad ) onLoad( cached );
  17665. scope.manager.itemEnd( url );
  17666. }, 0 );
  17667. return cached;
  17668. }
  17669. // Check for data: URI
  17670. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17671. var dataUriRegexResult = url.match( dataUriRegex );
  17672. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17673. if ( dataUriRegexResult ) {
  17674. var mimeType = dataUriRegexResult[ 1 ];
  17675. var isBase64 = !! dataUriRegexResult[ 2 ];
  17676. var data = dataUriRegexResult[ 3 ];
  17677. data = window.decodeURIComponent( data );
  17678. if ( isBase64 ) data = window.atob( data );
  17679. try {
  17680. var response;
  17681. var responseType = ( this.responseType || '' ).toLowerCase();
  17682. switch ( responseType ) {
  17683. case 'arraybuffer':
  17684. case 'blob':
  17685. response = new ArrayBuffer( data.length );
  17686. var view = new Uint8Array( response );
  17687. for ( var i = 0; i < data.length; i ++ ) {
  17688. view[ i ] = data.charCodeAt( i );
  17689. }
  17690. if ( responseType === 'blob' ) {
  17691. response = new Blob( [ response ], { type: mimeType } );
  17692. }
  17693. break;
  17694. case 'document':
  17695. var parser = new DOMParser();
  17696. response = parser.parseFromString( data, mimeType );
  17697. break;
  17698. case 'json':
  17699. response = JSON.parse( data );
  17700. break;
  17701. default: // 'text' or other
  17702. response = data;
  17703. break;
  17704. }
  17705. // Wait for next browser tick
  17706. window.setTimeout( function () {
  17707. if ( onLoad ) onLoad( response );
  17708. scope.manager.itemEnd( url );
  17709. }, 0 );
  17710. } catch ( error ) {
  17711. // Wait for next browser tick
  17712. window.setTimeout( function () {
  17713. if ( onError ) onError( error );
  17714. scope.manager.itemEnd( url );
  17715. scope.manager.itemError( url );
  17716. }, 0 );
  17717. }
  17718. } else {
  17719. var request = new XMLHttpRequest();
  17720. request.open( 'GET', url, true );
  17721. request.addEventListener( 'load', function ( event ) {
  17722. var response = event.target.response;
  17723. Cache.add( url, response );
  17724. if ( this.status === 200 ) {
  17725. if ( onLoad ) onLoad( response );
  17726. scope.manager.itemEnd( url );
  17727. } else if ( this.status === 0 ) {
  17728. // Some browsers return HTTP Status 0 when using non-http protocol
  17729. // e.g. 'file://' or 'data://'. Handle as success.
  17730. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17731. if ( onLoad ) onLoad( response );
  17732. scope.manager.itemEnd( url );
  17733. } else {
  17734. if ( onError ) onError( event );
  17735. scope.manager.itemEnd( url );
  17736. scope.manager.itemError( url );
  17737. }
  17738. }, false );
  17739. if ( onProgress !== undefined ) {
  17740. request.addEventListener( 'progress', function ( event ) {
  17741. onProgress( event );
  17742. }, false );
  17743. }
  17744. request.addEventListener( 'error', function ( event ) {
  17745. if ( onError ) onError( event );
  17746. scope.manager.itemEnd( url );
  17747. scope.manager.itemError( url );
  17748. }, false );
  17749. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17750. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17751. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17752. for ( var header in this.requestHeader ) {
  17753. request.setRequestHeader( header, this.requestHeader[ header ] );
  17754. }
  17755. request.send( null );
  17756. }
  17757. scope.manager.itemStart( url );
  17758. return request;
  17759. },
  17760. setPath: function ( value ) {
  17761. this.path = value;
  17762. return this;
  17763. },
  17764. setResponseType: function ( value ) {
  17765. this.responseType = value;
  17766. return this;
  17767. },
  17768. setWithCredentials: function ( value ) {
  17769. this.withCredentials = value;
  17770. return this;
  17771. },
  17772. setMimeType: function ( value ) {
  17773. this.mimeType = value;
  17774. return this;
  17775. },
  17776. setRequestHeader: function ( value ) {
  17777. this.requestHeader = value;
  17778. return this;
  17779. }
  17780. } );
  17781. /**
  17782. * @author mrdoob / http://mrdoob.com/
  17783. *
  17784. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17785. */
  17786. function CompressedTextureLoader( manager ) {
  17787. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17788. // override in sub classes
  17789. this._parser = null;
  17790. }
  17791. Object.assign( CompressedTextureLoader.prototype, {
  17792. load: function ( url, onLoad, onProgress, onError ) {
  17793. var scope = this;
  17794. var images = [];
  17795. var texture = new CompressedTexture();
  17796. texture.image = images;
  17797. var loader = new FileLoader( this.manager );
  17798. loader.setPath( this.path );
  17799. loader.setResponseType( 'arraybuffer' );
  17800. function loadTexture( i ) {
  17801. loader.load( url[ i ], function ( buffer ) {
  17802. var texDatas = scope._parser( buffer, true );
  17803. images[ i ] = {
  17804. width: texDatas.width,
  17805. height: texDatas.height,
  17806. format: texDatas.format,
  17807. mipmaps: texDatas.mipmaps
  17808. };
  17809. loaded += 1;
  17810. if ( loaded === 6 ) {
  17811. if ( texDatas.mipmapCount === 1 )
  17812. texture.minFilter = LinearFilter;
  17813. texture.format = texDatas.format;
  17814. texture.needsUpdate = true;
  17815. if ( onLoad ) onLoad( texture );
  17816. }
  17817. }, onProgress, onError );
  17818. }
  17819. if ( Array.isArray( url ) ) {
  17820. var loaded = 0;
  17821. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17822. loadTexture( i );
  17823. }
  17824. } else {
  17825. // compressed cubemap texture stored in a single DDS file
  17826. loader.load( url, function ( buffer ) {
  17827. var texDatas = scope._parser( buffer, true );
  17828. if ( texDatas.isCubemap ) {
  17829. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17830. for ( var f = 0; f < faces; f ++ ) {
  17831. images[ f ] = { mipmaps : [] };
  17832. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17833. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17834. images[ f ].format = texDatas.format;
  17835. images[ f ].width = texDatas.width;
  17836. images[ f ].height = texDatas.height;
  17837. }
  17838. }
  17839. } else {
  17840. texture.image.width = texDatas.width;
  17841. texture.image.height = texDatas.height;
  17842. texture.mipmaps = texDatas.mipmaps;
  17843. }
  17844. if ( texDatas.mipmapCount === 1 ) {
  17845. texture.minFilter = LinearFilter;
  17846. }
  17847. texture.format = texDatas.format;
  17848. texture.needsUpdate = true;
  17849. if ( onLoad ) onLoad( texture );
  17850. }, onProgress, onError );
  17851. }
  17852. return texture;
  17853. },
  17854. setPath: function ( value ) {
  17855. this.path = value;
  17856. return this;
  17857. }
  17858. } );
  17859. /**
  17860. * @author Nikos M. / https://github.com/foo123/
  17861. *
  17862. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17863. */
  17864. function DataTextureLoader( manager ) {
  17865. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17866. // override in sub classes
  17867. this._parser = null;
  17868. }
  17869. Object.assign( DataTextureLoader.prototype, {
  17870. load: function ( url, onLoad, onProgress, onError ) {
  17871. var scope = this;
  17872. var texture = new DataTexture();
  17873. var loader = new FileLoader( this.manager );
  17874. loader.setResponseType( 'arraybuffer' );
  17875. loader.load( url, function ( buffer ) {
  17876. var texData = scope._parser( buffer );
  17877. if ( ! texData ) return;
  17878. if ( undefined !== texData.image ) {
  17879. texture.image = texData.image;
  17880. } else if ( undefined !== texData.data ) {
  17881. texture.image.width = texData.width;
  17882. texture.image.height = texData.height;
  17883. texture.image.data = texData.data;
  17884. }
  17885. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17886. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17887. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17888. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17889. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17890. if ( undefined !== texData.format ) {
  17891. texture.format = texData.format;
  17892. }
  17893. if ( undefined !== texData.type ) {
  17894. texture.type = texData.type;
  17895. }
  17896. if ( undefined !== texData.mipmaps ) {
  17897. texture.mipmaps = texData.mipmaps;
  17898. }
  17899. if ( 1 === texData.mipmapCount ) {
  17900. texture.minFilter = LinearFilter;
  17901. }
  17902. texture.needsUpdate = true;
  17903. if ( onLoad ) onLoad( texture, texData );
  17904. }, onProgress, onError );
  17905. return texture;
  17906. }
  17907. } );
  17908. /**
  17909. * @author mrdoob / http://mrdoob.com/
  17910. */
  17911. function ImageLoader( manager ) {
  17912. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17913. }
  17914. Object.assign( ImageLoader.prototype, {
  17915. load: function ( url, onLoad, onProgress, onError ) {
  17916. if ( url === undefined ) url = '';
  17917. if ( this.path !== undefined ) url = this.path + url;
  17918. var scope = this;
  17919. var cached = Cache.get( url );
  17920. if ( cached !== undefined ) {
  17921. scope.manager.itemStart( url );
  17922. setTimeout( function () {
  17923. if ( onLoad ) onLoad( cached );
  17924. scope.manager.itemEnd( url );
  17925. }, 0 );
  17926. return cached;
  17927. }
  17928. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17929. image.addEventListener( 'load', function () {
  17930. Cache.add( url, this );
  17931. if ( onLoad ) onLoad( this );
  17932. scope.manager.itemEnd( url );
  17933. }, false );
  17934. /*
  17935. image.addEventListener( 'progress', function ( event ) {
  17936. if ( onProgress ) onProgress( event );
  17937. }, false );
  17938. */
  17939. image.addEventListener( 'error', function ( event ) {
  17940. if ( onError ) onError( event );
  17941. scope.manager.itemEnd( url );
  17942. scope.manager.itemError( url );
  17943. }, false );
  17944. if ( url.substr( 0, 5 ) !== 'data:' ) {
  17945. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  17946. }
  17947. scope.manager.itemStart( url );
  17948. image.src = url;
  17949. return image;
  17950. },
  17951. setCrossOrigin: function ( value ) {
  17952. this.crossOrigin = value;
  17953. return this;
  17954. },
  17955. setPath: function ( value ) {
  17956. this.path = value;
  17957. return this;
  17958. }
  17959. } );
  17960. /**
  17961. * @author mrdoob / http://mrdoob.com/
  17962. */
  17963. function CubeTextureLoader( manager ) {
  17964. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17965. }
  17966. Object.assign( CubeTextureLoader.prototype, {
  17967. load: function ( urls, onLoad, onProgress, onError ) {
  17968. var texture = new CubeTexture();
  17969. var loader = new ImageLoader( this.manager );
  17970. loader.setCrossOrigin( this.crossOrigin );
  17971. loader.setPath( this.path );
  17972. var loaded = 0;
  17973. function loadTexture( i ) {
  17974. loader.load( urls[ i ], function ( image ) {
  17975. texture.images[ i ] = image;
  17976. loaded ++;
  17977. if ( loaded === 6 ) {
  17978. texture.needsUpdate = true;
  17979. if ( onLoad ) onLoad( texture );
  17980. }
  17981. }, undefined, onError );
  17982. }
  17983. for ( var i = 0; i < urls.length; ++ i ) {
  17984. loadTexture( i );
  17985. }
  17986. return texture;
  17987. },
  17988. setCrossOrigin: function ( value ) {
  17989. this.crossOrigin = value;
  17990. return this;
  17991. },
  17992. setPath: function ( value ) {
  17993. this.path = value;
  17994. return this;
  17995. }
  17996. } );
  17997. /**
  17998. * @author mrdoob / http://mrdoob.com/
  17999. */
  18000. function TextureLoader( manager ) {
  18001. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18002. }
  18003. Object.assign( TextureLoader.prototype, {
  18004. load: function ( url, onLoad, onProgress, onError ) {
  18005. var loader = new ImageLoader( this.manager );
  18006. loader.setCrossOrigin( this.crossOrigin );
  18007. loader.setPath( this.path );
  18008. var texture = new Texture();
  18009. texture.image = loader.load( url, function () {
  18010. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18011. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18012. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18013. texture.needsUpdate = true;
  18014. if ( onLoad !== undefined ) {
  18015. onLoad( texture );
  18016. }
  18017. }, onProgress, onError );
  18018. return texture;
  18019. },
  18020. setCrossOrigin: function ( value ) {
  18021. this.crossOrigin = value;
  18022. return this;
  18023. },
  18024. setPath: function ( value ) {
  18025. this.path = value;
  18026. return this;
  18027. }
  18028. } );
  18029. /**
  18030. * @author mrdoob / http://mrdoob.com/
  18031. * @author alteredq / http://alteredqualia.com/
  18032. */
  18033. function Light( color, intensity ) {
  18034. Object3D.call( this );
  18035. this.type = 'Light';
  18036. this.color = new Color( color );
  18037. this.intensity = intensity !== undefined ? intensity : 1;
  18038. this.receiveShadow = undefined;
  18039. }
  18040. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18041. constructor: Light,
  18042. isLight: true,
  18043. copy: function ( source ) {
  18044. Object3D.prototype.copy.call( this, source );
  18045. this.color.copy( source.color );
  18046. this.intensity = source.intensity;
  18047. return this;
  18048. },
  18049. toJSON: function ( meta ) {
  18050. var data = Object3D.prototype.toJSON.call( this, meta );
  18051. data.object.color = this.color.getHex();
  18052. data.object.intensity = this.intensity;
  18053. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18054. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18055. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18056. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18057. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18058. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18059. return data;
  18060. }
  18061. } );
  18062. /**
  18063. * @author alteredq / http://alteredqualia.com/
  18064. */
  18065. function HemisphereLight( skyColor, groundColor, intensity ) {
  18066. Light.call( this, skyColor, intensity );
  18067. this.type = 'HemisphereLight';
  18068. this.castShadow = undefined;
  18069. this.position.copy( Object3D.DefaultUp );
  18070. this.updateMatrix();
  18071. this.groundColor = new Color( groundColor );
  18072. }
  18073. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18074. constructor: HemisphereLight,
  18075. isHemisphereLight: true,
  18076. copy: function ( source ) {
  18077. Light.prototype.copy.call( this, source );
  18078. this.groundColor.copy( source.groundColor );
  18079. return this;
  18080. }
  18081. } );
  18082. /**
  18083. * @author mrdoob / http://mrdoob.com/
  18084. */
  18085. function LightShadow( camera ) {
  18086. this.camera = camera;
  18087. this.bias = 0;
  18088. this.radius = 1;
  18089. this.mapSize = new Vector2( 512, 512 );
  18090. this.map = null;
  18091. this.matrix = new Matrix4();
  18092. }
  18093. Object.assign( LightShadow.prototype, {
  18094. copy: function ( source ) {
  18095. this.camera = source.camera.clone();
  18096. this.bias = source.bias;
  18097. this.radius = source.radius;
  18098. this.mapSize.copy( source.mapSize );
  18099. return this;
  18100. },
  18101. clone: function () {
  18102. return new this.constructor().copy( this );
  18103. },
  18104. toJSON: function () {
  18105. var object = {};
  18106. if ( this.bias !== 0 ) object.bias = this.bias;
  18107. if ( this.radius !== 1 ) object.radius = this.radius;
  18108. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18109. object.camera = this.camera.toJSON( false ).object;
  18110. delete object.camera.matrix;
  18111. return object;
  18112. }
  18113. } );
  18114. /**
  18115. * @author mrdoob / http://mrdoob.com/
  18116. */
  18117. function SpotLightShadow() {
  18118. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18119. }
  18120. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18121. constructor: SpotLightShadow,
  18122. isSpotLightShadow: true,
  18123. update: function ( light ) {
  18124. var camera = this.camera;
  18125. var fov = _Math.RAD2DEG * 2 * light.angle;
  18126. var aspect = this.mapSize.width / this.mapSize.height;
  18127. var far = light.distance || camera.far;
  18128. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18129. camera.fov = fov;
  18130. camera.aspect = aspect;
  18131. camera.far = far;
  18132. camera.updateProjectionMatrix();
  18133. }
  18134. }
  18135. } );
  18136. /**
  18137. * @author alteredq / http://alteredqualia.com/
  18138. */
  18139. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18140. Light.call( this, color, intensity );
  18141. this.type = 'SpotLight';
  18142. this.position.copy( Object3D.DefaultUp );
  18143. this.updateMatrix();
  18144. this.target = new Object3D();
  18145. Object.defineProperty( this, 'power', {
  18146. get: function () {
  18147. // intensity = power per solid angle.
  18148. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18149. return this.intensity * Math.PI;
  18150. },
  18151. set: function ( power ) {
  18152. // intensity = power per solid angle.
  18153. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18154. this.intensity = power / Math.PI;
  18155. }
  18156. } );
  18157. this.distance = ( distance !== undefined ) ? distance : 0;
  18158. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18159. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18160. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18161. this.shadow = new SpotLightShadow();
  18162. }
  18163. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18164. constructor: SpotLight,
  18165. isSpotLight: true,
  18166. copy: function ( source ) {
  18167. Light.prototype.copy.call( this, source );
  18168. this.distance = source.distance;
  18169. this.angle = source.angle;
  18170. this.penumbra = source.penumbra;
  18171. this.decay = source.decay;
  18172. this.target = source.target.clone();
  18173. this.shadow = source.shadow.clone();
  18174. return this;
  18175. }
  18176. } );
  18177. /**
  18178. * @author mrdoob / http://mrdoob.com/
  18179. */
  18180. function PointLight( color, intensity, distance, decay ) {
  18181. Light.call( this, color, intensity );
  18182. this.type = 'PointLight';
  18183. Object.defineProperty( this, 'power', {
  18184. get: function () {
  18185. // intensity = power per solid angle.
  18186. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18187. return this.intensity * 4 * Math.PI;
  18188. },
  18189. set: function ( power ) {
  18190. // intensity = power per solid angle.
  18191. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18192. this.intensity = power / ( 4 * Math.PI );
  18193. }
  18194. } );
  18195. this.distance = ( distance !== undefined ) ? distance : 0;
  18196. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18197. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18198. }
  18199. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18200. constructor: PointLight,
  18201. isPointLight: true,
  18202. copy: function ( source ) {
  18203. Light.prototype.copy.call( this, source );
  18204. this.distance = source.distance;
  18205. this.decay = source.decay;
  18206. this.shadow = source.shadow.clone();
  18207. return this;
  18208. }
  18209. } );
  18210. /**
  18211. * @author mrdoob / http://mrdoob.com/
  18212. */
  18213. function DirectionalLightShadow( ) {
  18214. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18215. }
  18216. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18217. constructor: DirectionalLightShadow
  18218. } );
  18219. /**
  18220. * @author mrdoob / http://mrdoob.com/
  18221. * @author alteredq / http://alteredqualia.com/
  18222. */
  18223. function DirectionalLight( color, intensity ) {
  18224. Light.call( this, color, intensity );
  18225. this.type = 'DirectionalLight';
  18226. this.position.copy( Object3D.DefaultUp );
  18227. this.updateMatrix();
  18228. this.target = new Object3D();
  18229. this.shadow = new DirectionalLightShadow();
  18230. }
  18231. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18232. constructor: DirectionalLight,
  18233. isDirectionalLight: true,
  18234. copy: function ( source ) {
  18235. Light.prototype.copy.call( this, source );
  18236. this.target = source.target.clone();
  18237. this.shadow = source.shadow.clone();
  18238. return this;
  18239. }
  18240. } );
  18241. /**
  18242. * @author mrdoob / http://mrdoob.com/
  18243. */
  18244. function AmbientLight( color, intensity ) {
  18245. Light.call( this, color, intensity );
  18246. this.type = 'AmbientLight';
  18247. this.castShadow = undefined;
  18248. }
  18249. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18250. constructor: AmbientLight,
  18251. isAmbientLight: true
  18252. } );
  18253. /**
  18254. * @author abelnation / http://github.com/abelnation
  18255. */
  18256. function RectAreaLight( color, intensity, width, height ) {
  18257. Light.call( this, color, intensity );
  18258. this.type = 'RectAreaLight';
  18259. this.position.set( 0, 1, 0 );
  18260. this.updateMatrix();
  18261. this.width = ( width !== undefined ) ? width : 10;
  18262. this.height = ( height !== undefined ) ? height : 10;
  18263. // TODO (abelnation): distance/decay
  18264. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18265. // TODO (abelnation): shadows
  18266. }
  18267. // TODO (abelnation): RectAreaLight update when light shape is changed
  18268. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18269. constructor: RectAreaLight,
  18270. isRectAreaLight: true,
  18271. copy: function ( source ) {
  18272. Light.prototype.copy.call( this, source );
  18273. this.width = source.width;
  18274. this.height = source.height;
  18275. return this;
  18276. },
  18277. toJSON: function ( meta ) {
  18278. var data = Light.prototype.toJSON.call( this, meta );
  18279. data.object.width = this.width;
  18280. data.object.height = this.height;
  18281. return data;
  18282. }
  18283. } );
  18284. /**
  18285. * @author tschw
  18286. * @author Ben Houston / http://clara.io/
  18287. * @author David Sarno / http://lighthaus.us/
  18288. */
  18289. var AnimationUtils = {
  18290. // same as Array.prototype.slice, but also works on typed arrays
  18291. arraySlice: function ( array, from, to ) {
  18292. if ( AnimationUtils.isTypedArray( array ) ) {
  18293. // in ios9 array.subarray(from, undefined) will return empty array
  18294. // but array.subarray(from) or array.subarray(from, len) is correct
  18295. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18296. }
  18297. return array.slice( from, to );
  18298. },
  18299. // converts an array to a specific type
  18300. convertArray: function ( array, type, forceClone ) {
  18301. if ( ! array || // let 'undefined' and 'null' pass
  18302. ! forceClone && array.constructor === type ) return array;
  18303. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18304. return new type( array ); // create typed array
  18305. }
  18306. return Array.prototype.slice.call( array ); // create Array
  18307. },
  18308. isTypedArray: function ( object ) {
  18309. return ArrayBuffer.isView( object ) &&
  18310. ! ( object instanceof DataView );
  18311. },
  18312. // returns an array by which times and values can be sorted
  18313. getKeyframeOrder: function ( times ) {
  18314. function compareTime( i, j ) {
  18315. return times[ i ] - times[ j ];
  18316. }
  18317. var n = times.length;
  18318. var result = new Array( n );
  18319. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18320. result.sort( compareTime );
  18321. return result;
  18322. },
  18323. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18324. sortedArray: function ( values, stride, order ) {
  18325. var nValues = values.length;
  18326. var result = new values.constructor( nValues );
  18327. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18328. var srcOffset = order[ i ] * stride;
  18329. for ( var j = 0; j !== stride; ++ j ) {
  18330. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18331. }
  18332. }
  18333. return result;
  18334. },
  18335. // function for parsing AOS keyframe formats
  18336. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18337. var i = 1, key = jsonKeys[ 0 ];
  18338. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18339. key = jsonKeys[ i ++ ];
  18340. }
  18341. if ( key === undefined ) return; // no data
  18342. var value = key[ valuePropertyName ];
  18343. if ( value === undefined ) return; // no data
  18344. if ( Array.isArray( value ) ) {
  18345. do {
  18346. value = key[ valuePropertyName ];
  18347. if ( value !== undefined ) {
  18348. times.push( key.time );
  18349. values.push.apply( values, value ); // push all elements
  18350. }
  18351. key = jsonKeys[ i ++ ];
  18352. } while ( key !== undefined );
  18353. } else if ( value.toArray !== undefined ) {
  18354. // ...assume THREE.Math-ish
  18355. do {
  18356. value = key[ valuePropertyName ];
  18357. if ( value !== undefined ) {
  18358. times.push( key.time );
  18359. value.toArray( values, values.length );
  18360. }
  18361. key = jsonKeys[ i ++ ];
  18362. } while ( key !== undefined );
  18363. } else {
  18364. // otherwise push as-is
  18365. do {
  18366. value = key[ valuePropertyName ];
  18367. if ( value !== undefined ) {
  18368. times.push( key.time );
  18369. values.push( value );
  18370. }
  18371. key = jsonKeys[ i ++ ];
  18372. } while ( key !== undefined );
  18373. }
  18374. }
  18375. };
  18376. /**
  18377. * Abstract base class of interpolants over parametric samples.
  18378. *
  18379. * The parameter domain is one dimensional, typically the time or a path
  18380. * along a curve defined by the data.
  18381. *
  18382. * The sample values can have any dimensionality and derived classes may
  18383. * apply special interpretations to the data.
  18384. *
  18385. * This class provides the interval seek in a Template Method, deferring
  18386. * the actual interpolation to derived classes.
  18387. *
  18388. * Time complexity is O(1) for linear access crossing at most two points
  18389. * and O(log N) for random access, where N is the number of positions.
  18390. *
  18391. * References:
  18392. *
  18393. * http://www.oodesign.com/template-method-pattern.html
  18394. *
  18395. * @author tschw
  18396. */
  18397. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18398. this.parameterPositions = parameterPositions;
  18399. this._cachedIndex = 0;
  18400. this.resultBuffer = resultBuffer !== undefined ?
  18401. resultBuffer : new sampleValues.constructor( sampleSize );
  18402. this.sampleValues = sampleValues;
  18403. this.valueSize = sampleSize;
  18404. }
  18405. Object.assign( Interpolant.prototype, {
  18406. evaluate: function( t ) {
  18407. var pp = this.parameterPositions,
  18408. i1 = this._cachedIndex,
  18409. t1 = pp[ i1 ],
  18410. t0 = pp[ i1 - 1 ];
  18411. validate_interval: {
  18412. seek: {
  18413. var right;
  18414. linear_scan: {
  18415. //- See http://jsperf.com/comparison-to-undefined/3
  18416. //- slower code:
  18417. //-
  18418. //- if ( t >= t1 || t1 === undefined ) {
  18419. forward_scan: if ( ! ( t < t1 ) ) {
  18420. for ( var giveUpAt = i1 + 2; ;) {
  18421. if ( t1 === undefined ) {
  18422. if ( t < t0 ) break forward_scan;
  18423. // after end
  18424. i1 = pp.length;
  18425. this._cachedIndex = i1;
  18426. return this.afterEnd_( i1 - 1, t, t0 );
  18427. }
  18428. if ( i1 === giveUpAt ) break; // this loop
  18429. t0 = t1;
  18430. t1 = pp[ ++ i1 ];
  18431. if ( t < t1 ) {
  18432. // we have arrived at the sought interval
  18433. break seek;
  18434. }
  18435. }
  18436. // prepare binary search on the right side of the index
  18437. right = pp.length;
  18438. break linear_scan;
  18439. }
  18440. //- slower code:
  18441. //- if ( t < t0 || t0 === undefined ) {
  18442. if ( ! ( t >= t0 ) ) {
  18443. // looping?
  18444. var t1global = pp[ 1 ];
  18445. if ( t < t1global ) {
  18446. i1 = 2; // + 1, using the scan for the details
  18447. t0 = t1global;
  18448. }
  18449. // linear reverse scan
  18450. for ( var giveUpAt = i1 - 2; ;) {
  18451. if ( t0 === undefined ) {
  18452. // before start
  18453. this._cachedIndex = 0;
  18454. return this.beforeStart_( 0, t, t1 );
  18455. }
  18456. if ( i1 === giveUpAt ) break; // this loop
  18457. t1 = t0;
  18458. t0 = pp[ -- i1 - 1 ];
  18459. if ( t >= t0 ) {
  18460. // we have arrived at the sought interval
  18461. break seek;
  18462. }
  18463. }
  18464. // prepare binary search on the left side of the index
  18465. right = i1;
  18466. i1 = 0;
  18467. break linear_scan;
  18468. }
  18469. // the interval is valid
  18470. break validate_interval;
  18471. } // linear scan
  18472. // binary search
  18473. while ( i1 < right ) {
  18474. var mid = ( i1 + right ) >>> 1;
  18475. if ( t < pp[ mid ] ) {
  18476. right = mid;
  18477. } else {
  18478. i1 = mid + 1;
  18479. }
  18480. }
  18481. t1 = pp[ i1 ];
  18482. t0 = pp[ i1 - 1 ];
  18483. // check boundary cases, again
  18484. if ( t0 === undefined ) {
  18485. this._cachedIndex = 0;
  18486. return this.beforeStart_( 0, t, t1 );
  18487. }
  18488. if ( t1 === undefined ) {
  18489. i1 = pp.length;
  18490. this._cachedIndex = i1;
  18491. return this.afterEnd_( i1 - 1, t0, t );
  18492. }
  18493. } // seek
  18494. this._cachedIndex = i1;
  18495. this.intervalChanged_( i1, t0, t1 );
  18496. } // validate_interval
  18497. return this.interpolate_( i1, t0, t, t1 );
  18498. },
  18499. settings: null, // optional, subclass-specific settings structure
  18500. // Note: The indirection allows central control of many interpolants.
  18501. // --- Protected interface
  18502. DefaultSettings_: {},
  18503. getSettings_: function() {
  18504. return this.settings || this.DefaultSettings_;
  18505. },
  18506. copySampleValue_: function( index ) {
  18507. // copies a sample value to the result buffer
  18508. var result = this.resultBuffer,
  18509. values = this.sampleValues,
  18510. stride = this.valueSize,
  18511. offset = index * stride;
  18512. for ( var i = 0; i !== stride; ++ i ) {
  18513. result[ i ] = values[ offset + i ];
  18514. }
  18515. return result;
  18516. },
  18517. // Template methods for derived classes:
  18518. interpolate_: function( i1, t0, t, t1 ) {
  18519. throw new Error( "call to abstract method" );
  18520. // implementations shall return this.resultBuffer
  18521. },
  18522. intervalChanged_: function( i1, t0, t1 ) {
  18523. // empty
  18524. }
  18525. } );
  18526. //!\ DECLARE ALIAS AFTER assign prototype !
  18527. Object.assign( Interpolant.prototype, {
  18528. //( 0, t, t0 ), returns this.resultBuffer
  18529. beforeStart_: Interpolant.prototype.copySampleValue_,
  18530. //( N-1, tN-1, t ), returns this.resultBuffer
  18531. afterEnd_: Interpolant.prototype.copySampleValue_,
  18532. } );
  18533. /**
  18534. * Fast and simple cubic spline interpolant.
  18535. *
  18536. * It was derived from a Hermitian construction setting the first derivative
  18537. * at each sample position to the linear slope between neighboring positions
  18538. * over their parameter interval.
  18539. *
  18540. * @author tschw
  18541. */
  18542. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18543. Interpolant.call(
  18544. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18545. this._weightPrev = -0;
  18546. this._offsetPrev = -0;
  18547. this._weightNext = -0;
  18548. this._offsetNext = -0;
  18549. }
  18550. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18551. constructor: CubicInterpolant,
  18552. DefaultSettings_: {
  18553. endingStart: ZeroCurvatureEnding,
  18554. endingEnd: ZeroCurvatureEnding
  18555. },
  18556. intervalChanged_: function( i1, t0, t1 ) {
  18557. var pp = this.parameterPositions,
  18558. iPrev = i1 - 2,
  18559. iNext = i1 + 1,
  18560. tPrev = pp[ iPrev ],
  18561. tNext = pp[ iNext ];
  18562. if ( tPrev === undefined ) {
  18563. switch ( this.getSettings_().endingStart ) {
  18564. case ZeroSlopeEnding:
  18565. // f'(t0) = 0
  18566. iPrev = i1;
  18567. tPrev = 2 * t0 - t1;
  18568. break;
  18569. case WrapAroundEnding:
  18570. // use the other end of the curve
  18571. iPrev = pp.length - 2;
  18572. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18573. break;
  18574. default: // ZeroCurvatureEnding
  18575. // f''(t0) = 0 a.k.a. Natural Spline
  18576. iPrev = i1;
  18577. tPrev = t1;
  18578. }
  18579. }
  18580. if ( tNext === undefined ) {
  18581. switch ( this.getSettings_().endingEnd ) {
  18582. case ZeroSlopeEnding:
  18583. // f'(tN) = 0
  18584. iNext = i1;
  18585. tNext = 2 * t1 - t0;
  18586. break;
  18587. case WrapAroundEnding:
  18588. // use the other end of the curve
  18589. iNext = 1;
  18590. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18591. break;
  18592. default: // ZeroCurvatureEnding
  18593. // f''(tN) = 0, a.k.a. Natural Spline
  18594. iNext = i1 - 1;
  18595. tNext = t0;
  18596. }
  18597. }
  18598. var halfDt = ( t1 - t0 ) * 0.5,
  18599. stride = this.valueSize;
  18600. this._weightPrev = halfDt / ( t0 - tPrev );
  18601. this._weightNext = halfDt / ( tNext - t1 );
  18602. this._offsetPrev = iPrev * stride;
  18603. this._offsetNext = iNext * stride;
  18604. },
  18605. interpolate_: function( i1, t0, t, t1 ) {
  18606. var result = this.resultBuffer,
  18607. values = this.sampleValues,
  18608. stride = this.valueSize,
  18609. o1 = i1 * stride, o0 = o1 - stride,
  18610. oP = this._offsetPrev, oN = this._offsetNext,
  18611. wP = this._weightPrev, wN = this._weightNext,
  18612. p = ( t - t0 ) / ( t1 - t0 ),
  18613. pp = p * p,
  18614. ppp = pp * p;
  18615. // evaluate polynomials
  18616. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18617. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18618. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18619. var sN = wN * ppp - wN * pp;
  18620. // combine data linearly
  18621. for ( var i = 0; i !== stride; ++ i ) {
  18622. result[ i ] =
  18623. sP * values[ oP + i ] +
  18624. s0 * values[ o0 + i ] +
  18625. s1 * values[ o1 + i ] +
  18626. sN * values[ oN + i ];
  18627. }
  18628. return result;
  18629. }
  18630. } );
  18631. /**
  18632. * @author tschw
  18633. */
  18634. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18635. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18636. }
  18637. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18638. constructor: LinearInterpolant,
  18639. interpolate_: function( i1, t0, t, t1 ) {
  18640. var result = this.resultBuffer,
  18641. values = this.sampleValues,
  18642. stride = this.valueSize,
  18643. offset1 = i1 * stride,
  18644. offset0 = offset1 - stride,
  18645. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18646. weight0 = 1 - weight1;
  18647. for ( var i = 0; i !== stride; ++ i ) {
  18648. result[ i ] =
  18649. values[ offset0 + i ] * weight0 +
  18650. values[ offset1 + i ] * weight1;
  18651. }
  18652. return result;
  18653. }
  18654. } );
  18655. /**
  18656. *
  18657. * Interpolant that evaluates to the sample value at the position preceeding
  18658. * the parameter.
  18659. *
  18660. * @author tschw
  18661. */
  18662. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18663. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18664. }
  18665. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18666. constructor: DiscreteInterpolant,
  18667. interpolate_: function( i1, t0, t, t1 ) {
  18668. return this.copySampleValue_( i1 - 1 );
  18669. }
  18670. } );
  18671. var KeyframeTrackPrototype;
  18672. KeyframeTrackPrototype = {
  18673. TimeBufferType: Float32Array,
  18674. ValueBufferType: Float32Array,
  18675. DefaultInterpolation: InterpolateLinear,
  18676. InterpolantFactoryMethodDiscrete: function ( result ) {
  18677. return new DiscreteInterpolant(
  18678. this.times, this.values, this.getValueSize(), result );
  18679. },
  18680. InterpolantFactoryMethodLinear: function ( result ) {
  18681. return new LinearInterpolant(
  18682. this.times, this.values, this.getValueSize(), result );
  18683. },
  18684. InterpolantFactoryMethodSmooth: function ( result ) {
  18685. return new CubicInterpolant(
  18686. this.times, this.values, this.getValueSize(), result );
  18687. },
  18688. setInterpolation: function ( interpolation ) {
  18689. var factoryMethod;
  18690. switch ( interpolation ) {
  18691. case InterpolateDiscrete:
  18692. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18693. break;
  18694. case InterpolateLinear:
  18695. factoryMethod = this.InterpolantFactoryMethodLinear;
  18696. break;
  18697. case InterpolateSmooth:
  18698. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18699. break;
  18700. }
  18701. if ( factoryMethod === undefined ) {
  18702. var message = "unsupported interpolation for " +
  18703. this.ValueTypeName + " keyframe track named " + this.name;
  18704. if ( this.createInterpolant === undefined ) {
  18705. // fall back to default, unless the default itself is messed up
  18706. if ( interpolation !== this.DefaultInterpolation ) {
  18707. this.setInterpolation( this.DefaultInterpolation );
  18708. } else {
  18709. throw new Error( message ); // fatal, in this case
  18710. }
  18711. }
  18712. console.warn( message );
  18713. return;
  18714. }
  18715. this.createInterpolant = factoryMethod;
  18716. },
  18717. getInterpolation: function () {
  18718. switch ( this.createInterpolant ) {
  18719. case this.InterpolantFactoryMethodDiscrete:
  18720. return InterpolateDiscrete;
  18721. case this.InterpolantFactoryMethodLinear:
  18722. return InterpolateLinear;
  18723. case this.InterpolantFactoryMethodSmooth:
  18724. return InterpolateSmooth;
  18725. }
  18726. },
  18727. getValueSize: function () {
  18728. return this.values.length / this.times.length;
  18729. },
  18730. // move all keyframes either forwards or backwards in time
  18731. shift: function ( timeOffset ) {
  18732. if ( timeOffset !== 0.0 ) {
  18733. var times = this.times;
  18734. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18735. times[ i ] += timeOffset;
  18736. }
  18737. }
  18738. return this;
  18739. },
  18740. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18741. scale: function ( timeScale ) {
  18742. if ( timeScale !== 1.0 ) {
  18743. var times = this.times;
  18744. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18745. times[ i ] *= timeScale;
  18746. }
  18747. }
  18748. return this;
  18749. },
  18750. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18751. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18752. trim: function ( startTime, endTime ) {
  18753. var times = this.times,
  18754. nKeys = times.length,
  18755. from = 0,
  18756. to = nKeys - 1;
  18757. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18758. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18759. ++ to; // inclusive -> exclusive bound
  18760. if ( from !== 0 || to !== nKeys ) {
  18761. // empty tracks are forbidden, so keep at least one keyframe
  18762. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18763. var stride = this.getValueSize();
  18764. this.times = AnimationUtils.arraySlice( times, from, to );
  18765. this.values = AnimationUtils.
  18766. arraySlice( this.values, from * stride, to * stride );
  18767. }
  18768. return this;
  18769. },
  18770. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18771. validate: function () {
  18772. var valid = true;
  18773. var valueSize = this.getValueSize();
  18774. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18775. console.error( "invalid value size in track", this );
  18776. valid = false;
  18777. }
  18778. var times = this.times,
  18779. values = this.values,
  18780. nKeys = times.length;
  18781. if ( nKeys === 0 ) {
  18782. console.error( "track is empty", this );
  18783. valid = false;
  18784. }
  18785. var prevTime = null;
  18786. for ( var i = 0; i !== nKeys; i ++ ) {
  18787. var currTime = times[ i ];
  18788. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18789. console.error( "time is not a valid number", this, i, currTime );
  18790. valid = false;
  18791. break;
  18792. }
  18793. if ( prevTime !== null && prevTime > currTime ) {
  18794. console.error( "out of order keys", this, i, currTime, prevTime );
  18795. valid = false;
  18796. break;
  18797. }
  18798. prevTime = currTime;
  18799. }
  18800. if ( values !== undefined ) {
  18801. if ( AnimationUtils.isTypedArray( values ) ) {
  18802. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18803. var value = values[ i ];
  18804. if ( isNaN( value ) ) {
  18805. console.error( "value is not a valid number", this, i, value );
  18806. valid = false;
  18807. break;
  18808. }
  18809. }
  18810. }
  18811. }
  18812. return valid;
  18813. },
  18814. // removes equivalent sequential keys as common in morph target sequences
  18815. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18816. optimize: function () {
  18817. var times = this.times,
  18818. values = this.values,
  18819. stride = this.getValueSize(),
  18820. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18821. writeIndex = 1,
  18822. lastIndex = times.length - 1;
  18823. for ( var i = 1; i < lastIndex; ++ i ) {
  18824. var keep = false;
  18825. var time = times[ i ];
  18826. var timeNext = times[ i + 1 ];
  18827. // remove adjacent keyframes scheduled at the same time
  18828. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18829. if ( ! smoothInterpolation ) {
  18830. // remove unnecessary keyframes same as their neighbors
  18831. var offset = i * stride,
  18832. offsetP = offset - stride,
  18833. offsetN = offset + stride;
  18834. for ( var j = 0; j !== stride; ++ j ) {
  18835. var value = values[ offset + j ];
  18836. if ( value !== values[ offsetP + j ] ||
  18837. value !== values[ offsetN + j ] ) {
  18838. keep = true;
  18839. break;
  18840. }
  18841. }
  18842. } else keep = true;
  18843. }
  18844. // in-place compaction
  18845. if ( keep ) {
  18846. if ( i !== writeIndex ) {
  18847. times[ writeIndex ] = times[ i ];
  18848. var readOffset = i * stride,
  18849. writeOffset = writeIndex * stride;
  18850. for ( var j = 0; j !== stride; ++ j )
  18851. values[ writeOffset + j ] = values[ readOffset + j ];
  18852. }
  18853. ++ writeIndex;
  18854. }
  18855. }
  18856. // flush last keyframe (compaction looks ahead)
  18857. if ( lastIndex > 0 ) {
  18858. times[ writeIndex ] = times[ lastIndex ];
  18859. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18860. values[ writeOffset + j ] = values[ readOffset + j ];
  18861. ++ writeIndex;
  18862. }
  18863. if ( writeIndex !== times.length ) {
  18864. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18865. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18866. }
  18867. return this;
  18868. }
  18869. };
  18870. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18871. if ( name === undefined ) throw new Error( "track name is undefined" );
  18872. if ( times === undefined || times.length === 0 ) {
  18873. throw new Error( "no keyframes in track named " + name );
  18874. }
  18875. this.name = name;
  18876. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18877. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18878. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18879. this.validate();
  18880. this.optimize();
  18881. }
  18882. /**
  18883. *
  18884. * A Track of vectored keyframe values.
  18885. *
  18886. *
  18887. * @author Ben Houston / http://clara.io/
  18888. * @author David Sarno / http://lighthaus.us/
  18889. * @author tschw
  18890. */
  18891. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18892. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18893. }
  18894. VectorKeyframeTrack.prototype =
  18895. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18896. constructor: VectorKeyframeTrack,
  18897. ValueTypeName: 'vector'
  18898. // ValueBufferType is inherited
  18899. // DefaultInterpolation is inherited
  18900. } );
  18901. /**
  18902. * Spherical linear unit quaternion interpolant.
  18903. *
  18904. * @author tschw
  18905. */
  18906. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18907. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18908. }
  18909. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18910. constructor: QuaternionLinearInterpolant,
  18911. interpolate_: function( i1, t0, t, t1 ) {
  18912. var result = this.resultBuffer,
  18913. values = this.sampleValues,
  18914. stride = this.valueSize,
  18915. offset = i1 * stride,
  18916. alpha = ( t - t0 ) / ( t1 - t0 );
  18917. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18918. Quaternion.slerpFlat( result, 0,
  18919. values, offset - stride, values, offset, alpha );
  18920. }
  18921. return result;
  18922. }
  18923. } );
  18924. /**
  18925. *
  18926. * A Track of quaternion keyframe values.
  18927. *
  18928. * @author Ben Houston / http://clara.io/
  18929. * @author David Sarno / http://lighthaus.us/
  18930. * @author tschw
  18931. */
  18932. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18933. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18934. }
  18935. QuaternionKeyframeTrack.prototype =
  18936. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18937. constructor: QuaternionKeyframeTrack,
  18938. ValueTypeName: 'quaternion',
  18939. // ValueBufferType is inherited
  18940. DefaultInterpolation: InterpolateLinear,
  18941. InterpolantFactoryMethodLinear: function( result ) {
  18942. return new QuaternionLinearInterpolant(
  18943. this.times, this.values, this.getValueSize(), result );
  18944. },
  18945. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18946. } );
  18947. /**
  18948. *
  18949. * A Track of numeric keyframe values.
  18950. *
  18951. * @author Ben Houston / http://clara.io/
  18952. * @author David Sarno / http://lighthaus.us/
  18953. * @author tschw
  18954. */
  18955. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18956. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18957. }
  18958. NumberKeyframeTrack.prototype =
  18959. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18960. constructor: NumberKeyframeTrack,
  18961. ValueTypeName: 'number'
  18962. // ValueBufferType is inherited
  18963. // DefaultInterpolation is inherited
  18964. } );
  18965. /**
  18966. *
  18967. * A Track that interpolates Strings
  18968. *
  18969. *
  18970. * @author Ben Houston / http://clara.io/
  18971. * @author David Sarno / http://lighthaus.us/
  18972. * @author tschw
  18973. */
  18974. function StringKeyframeTrack( name, times, values, interpolation ) {
  18975. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18976. }
  18977. StringKeyframeTrack.prototype =
  18978. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18979. constructor: StringKeyframeTrack,
  18980. ValueTypeName: 'string',
  18981. ValueBufferType: Array,
  18982. DefaultInterpolation: InterpolateDiscrete,
  18983. InterpolantFactoryMethodLinear: undefined,
  18984. InterpolantFactoryMethodSmooth: undefined
  18985. } );
  18986. /**
  18987. *
  18988. * A Track of Boolean keyframe values.
  18989. *
  18990. *
  18991. * @author Ben Houston / http://clara.io/
  18992. * @author David Sarno / http://lighthaus.us/
  18993. * @author tschw
  18994. */
  18995. function BooleanKeyframeTrack( name, times, values ) {
  18996. KeyframeTrackConstructor.call( this, name, times, values );
  18997. }
  18998. BooleanKeyframeTrack.prototype =
  18999. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19000. constructor: BooleanKeyframeTrack,
  19001. ValueTypeName: 'bool',
  19002. ValueBufferType: Array,
  19003. DefaultInterpolation: InterpolateDiscrete,
  19004. InterpolantFactoryMethodLinear: undefined,
  19005. InterpolantFactoryMethodSmooth: undefined
  19006. // Note: Actually this track could have a optimized / compressed
  19007. // representation of a single value and a custom interpolant that
  19008. // computes "firstValue ^ isOdd( index )".
  19009. } );
  19010. /**
  19011. *
  19012. * A Track of keyframe values that represent color.
  19013. *
  19014. *
  19015. * @author Ben Houston / http://clara.io/
  19016. * @author David Sarno / http://lighthaus.us/
  19017. * @author tschw
  19018. */
  19019. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19020. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19021. }
  19022. ColorKeyframeTrack.prototype =
  19023. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19024. constructor: ColorKeyframeTrack,
  19025. ValueTypeName: 'color'
  19026. // ValueBufferType is inherited
  19027. // DefaultInterpolation is inherited
  19028. // Note: Very basic implementation and nothing special yet.
  19029. // However, this is the place for color space parameterization.
  19030. } );
  19031. /**
  19032. *
  19033. * A timed sequence of keyframes for a specific property.
  19034. *
  19035. *
  19036. * @author Ben Houston / http://clara.io/
  19037. * @author David Sarno / http://lighthaus.us/
  19038. * @author tschw
  19039. */
  19040. function KeyframeTrack( name, times, values, interpolation ) {
  19041. KeyframeTrackConstructor.apply( this, arguments );
  19042. }
  19043. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19044. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19045. // Static methods:
  19046. Object.assign( KeyframeTrack, {
  19047. // Serialization (in static context, because of constructor invocation
  19048. // and automatic invocation of .toJSON):
  19049. parse: function( json ) {
  19050. if( json.type === undefined ) {
  19051. throw new Error( "track type undefined, can not parse" );
  19052. }
  19053. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19054. if ( json.times === undefined ) {
  19055. var times = [], values = [];
  19056. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19057. json.times = times;
  19058. json.values = values;
  19059. }
  19060. // derived classes can define a static parse method
  19061. if ( trackType.parse !== undefined ) {
  19062. return trackType.parse( json );
  19063. } else {
  19064. // by default, we asssume a constructor compatible with the base
  19065. return new trackType(
  19066. json.name, json.times, json.values, json.interpolation );
  19067. }
  19068. },
  19069. toJSON: function( track ) {
  19070. var trackType = track.constructor;
  19071. var json;
  19072. // derived classes can define a static toJSON method
  19073. if ( trackType.toJSON !== undefined ) {
  19074. json = trackType.toJSON( track );
  19075. } else {
  19076. // by default, we assume the data can be serialized as-is
  19077. json = {
  19078. 'name': track.name,
  19079. 'times': AnimationUtils.convertArray( track.times, Array ),
  19080. 'values': AnimationUtils.convertArray( track.values, Array )
  19081. };
  19082. var interpolation = track.getInterpolation();
  19083. if ( interpolation !== track.DefaultInterpolation ) {
  19084. json.interpolation = interpolation;
  19085. }
  19086. }
  19087. json.type = track.ValueTypeName; // mandatory
  19088. return json;
  19089. },
  19090. _getTrackTypeForValueTypeName: function( typeName ) {
  19091. switch( typeName.toLowerCase() ) {
  19092. case "scalar":
  19093. case "double":
  19094. case "float":
  19095. case "number":
  19096. case "integer":
  19097. return NumberKeyframeTrack;
  19098. case "vector":
  19099. case "vector2":
  19100. case "vector3":
  19101. case "vector4":
  19102. return VectorKeyframeTrack;
  19103. case "color":
  19104. return ColorKeyframeTrack;
  19105. case "quaternion":
  19106. return QuaternionKeyframeTrack;
  19107. case "bool":
  19108. case "boolean":
  19109. return BooleanKeyframeTrack;
  19110. case "string":
  19111. return StringKeyframeTrack;
  19112. }
  19113. throw new Error( "Unsupported typeName: " + typeName );
  19114. }
  19115. } );
  19116. /**
  19117. *
  19118. * Reusable set of Tracks that represent an animation.
  19119. *
  19120. * @author Ben Houston / http://clara.io/
  19121. * @author David Sarno / http://lighthaus.us/
  19122. */
  19123. function AnimationClip( name, duration, tracks ) {
  19124. this.name = name;
  19125. this.tracks = tracks;
  19126. this.duration = ( duration !== undefined ) ? duration : - 1;
  19127. this.uuid = _Math.generateUUID();
  19128. // this means it should figure out its duration by scanning the tracks
  19129. if ( this.duration < 0 ) {
  19130. this.resetDuration();
  19131. }
  19132. this.optimize();
  19133. }
  19134. Object.assign( AnimationClip, {
  19135. parse: function ( json ) {
  19136. var tracks = [],
  19137. jsonTracks = json.tracks,
  19138. frameTime = 1.0 / ( json.fps || 1.0 );
  19139. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19140. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19141. }
  19142. return new AnimationClip( json.name, json.duration, tracks );
  19143. },
  19144. toJSON: function ( clip ) {
  19145. var tracks = [],
  19146. clipTracks = clip.tracks;
  19147. var json = {
  19148. 'name': clip.name,
  19149. 'duration': clip.duration,
  19150. 'tracks': tracks
  19151. };
  19152. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19153. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19154. }
  19155. return json;
  19156. },
  19157. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19158. var numMorphTargets = morphTargetSequence.length;
  19159. var tracks = [];
  19160. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19161. var times = [];
  19162. var values = [];
  19163. times.push(
  19164. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19165. i,
  19166. ( i + 1 ) % numMorphTargets );
  19167. values.push( 0, 1, 0 );
  19168. var order = AnimationUtils.getKeyframeOrder( times );
  19169. times = AnimationUtils.sortedArray( times, 1, order );
  19170. values = AnimationUtils.sortedArray( values, 1, order );
  19171. // if there is a key at the first frame, duplicate it as the
  19172. // last frame as well for perfect loop.
  19173. if ( ! noLoop && times[ 0 ] === 0 ) {
  19174. times.push( numMorphTargets );
  19175. values.push( values[ 0 ] );
  19176. }
  19177. tracks.push(
  19178. new NumberKeyframeTrack(
  19179. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19180. times, values
  19181. ).scale( 1.0 / fps ) );
  19182. }
  19183. return new AnimationClip( name, - 1, tracks );
  19184. },
  19185. findByName: function ( objectOrClipArray, name ) {
  19186. var clipArray = objectOrClipArray;
  19187. if ( ! Array.isArray( objectOrClipArray ) ) {
  19188. var o = objectOrClipArray;
  19189. clipArray = o.geometry && o.geometry.animations || o.animations;
  19190. }
  19191. for ( var i = 0; i < clipArray.length; i ++ ) {
  19192. if ( clipArray[ i ].name === name ) {
  19193. return clipArray[ i ];
  19194. }
  19195. }
  19196. return null;
  19197. },
  19198. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19199. var animationToMorphTargets = {};
  19200. // tested with https://regex101.com/ on trick sequences
  19201. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19202. var pattern = /^([\w-]*?)([\d]+)$/;
  19203. // sort morph target names into animation groups based
  19204. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19205. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19206. var morphTarget = morphTargets[ i ];
  19207. var parts = morphTarget.name.match( pattern );
  19208. if ( parts && parts.length > 1 ) {
  19209. var name = parts[ 1 ];
  19210. var animationMorphTargets = animationToMorphTargets[ name ];
  19211. if ( ! animationMorphTargets ) {
  19212. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19213. }
  19214. animationMorphTargets.push( morphTarget );
  19215. }
  19216. }
  19217. var clips = [];
  19218. for ( var name in animationToMorphTargets ) {
  19219. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19220. }
  19221. return clips;
  19222. },
  19223. // parse the animation.hierarchy format
  19224. parseAnimation: function ( animation, bones ) {
  19225. if ( ! animation ) {
  19226. console.error( " no animation in JSONLoader data" );
  19227. return null;
  19228. }
  19229. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19230. // only return track if there are actually keys.
  19231. if ( animationKeys.length !== 0 ) {
  19232. var times = [];
  19233. var values = [];
  19234. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19235. // empty keys are filtered out, so check again
  19236. if ( times.length !== 0 ) {
  19237. destTracks.push( new trackType( trackName, times, values ) );
  19238. }
  19239. }
  19240. };
  19241. var tracks = [];
  19242. var clipName = animation.name || 'default';
  19243. // automatic length determination in AnimationClip.
  19244. var duration = animation.length || - 1;
  19245. var fps = animation.fps || 30;
  19246. var hierarchyTracks = animation.hierarchy || [];
  19247. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19248. var animationKeys = hierarchyTracks[ h ].keys;
  19249. // skip empty tracks
  19250. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19251. // process morph targets
  19252. if ( animationKeys[ 0 ].morphTargets ) {
  19253. // figure out all morph targets used in this track
  19254. var morphTargetNames = {};
  19255. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19256. if ( animationKeys[ k ].morphTargets ) {
  19257. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19258. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19259. }
  19260. }
  19261. }
  19262. // create a track for each morph target with all zero
  19263. // morphTargetInfluences except for the keys in which
  19264. // the morphTarget is named.
  19265. for ( var morphTargetName in morphTargetNames ) {
  19266. var times = [];
  19267. var values = [];
  19268. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19269. var animationKey = animationKeys[ k ];
  19270. times.push( animationKey.time );
  19271. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19272. }
  19273. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19274. }
  19275. duration = morphTargetNames.length * ( fps || 1.0 );
  19276. } else {
  19277. // ...assume skeletal animation
  19278. var boneName = '.bones[' + bones[ h ].name + ']';
  19279. addNonemptyTrack(
  19280. VectorKeyframeTrack, boneName + '.position',
  19281. animationKeys, 'pos', tracks );
  19282. addNonemptyTrack(
  19283. QuaternionKeyframeTrack, boneName + '.quaternion',
  19284. animationKeys, 'rot', tracks );
  19285. addNonemptyTrack(
  19286. VectorKeyframeTrack, boneName + '.scale',
  19287. animationKeys, 'scl', tracks );
  19288. }
  19289. }
  19290. if ( tracks.length === 0 ) {
  19291. return null;
  19292. }
  19293. var clip = new AnimationClip( clipName, duration, tracks );
  19294. return clip;
  19295. }
  19296. } );
  19297. Object.assign( AnimationClip.prototype, {
  19298. resetDuration: function () {
  19299. var tracks = this.tracks, duration = 0;
  19300. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19301. var track = this.tracks[ i ];
  19302. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19303. }
  19304. this.duration = duration;
  19305. },
  19306. trim: function () {
  19307. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19308. this.tracks[ i ].trim( 0, this.duration );
  19309. }
  19310. return this;
  19311. },
  19312. optimize: function () {
  19313. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19314. this.tracks[ i ].optimize();
  19315. }
  19316. return this;
  19317. }
  19318. } );
  19319. /**
  19320. * @author mrdoob / http://mrdoob.com/
  19321. */
  19322. function MaterialLoader( manager ) {
  19323. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19324. this.textures = {};
  19325. }
  19326. Object.assign( MaterialLoader.prototype, {
  19327. load: function ( url, onLoad, onProgress, onError ) {
  19328. var scope = this;
  19329. var loader = new FileLoader( scope.manager );
  19330. loader.setResponseType( 'json' );
  19331. loader.load( url, function ( json ) {
  19332. onLoad( scope.parse( json ) );
  19333. }, onProgress, onError );
  19334. },
  19335. setTextures: function ( value ) {
  19336. this.textures = value;
  19337. },
  19338. parse: function ( json ) {
  19339. var textures = this.textures;
  19340. function getTexture( name ) {
  19341. if ( textures[ name ] === undefined ) {
  19342. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19343. }
  19344. return textures[ name ];
  19345. }
  19346. var material = new Materials[ json.type ]();
  19347. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19348. if ( json.name !== undefined ) material.name = json.name;
  19349. if ( json.color !== undefined ) material.color.setHex( json.color );
  19350. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19351. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19352. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19353. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19354. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19355. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19356. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19357. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19358. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19359. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19360. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19361. if ( json.fog !== undefined ) material.fog = json.fog;
  19362. if ( json.shading !== undefined ) material.shading = json.shading;
  19363. if ( json.blending !== undefined ) material.blending = json.blending;
  19364. if ( json.side !== undefined ) material.side = json.side;
  19365. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19366. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19367. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19368. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19369. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19370. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19371. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19372. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19373. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19374. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19375. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19376. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19377. // for PointsMaterial
  19378. if ( json.size !== undefined ) material.size = json.size;
  19379. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19380. // maps
  19381. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19382. if ( json.alphaMap !== undefined ) {
  19383. material.alphaMap = getTexture( json.alphaMap );
  19384. material.transparent = true;
  19385. }
  19386. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19387. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19388. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19389. if ( json.normalScale !== undefined ) {
  19390. var normalScale = json.normalScale;
  19391. if ( Array.isArray( normalScale ) === false ) {
  19392. // Blender exporter used to export a scalar. See #7459
  19393. normalScale = [ normalScale, normalScale ];
  19394. }
  19395. material.normalScale = new Vector2().fromArray( normalScale );
  19396. }
  19397. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19398. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19399. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19400. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19401. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19402. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19403. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19404. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19405. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19406. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19407. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19408. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19409. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19410. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19411. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19412. return material;
  19413. }
  19414. } );
  19415. /**
  19416. * @author mrdoob / http://mrdoob.com/
  19417. */
  19418. function BufferGeometryLoader( manager ) {
  19419. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19420. }
  19421. Object.assign( BufferGeometryLoader.prototype, {
  19422. load: function ( url, onLoad, onProgress, onError ) {
  19423. var scope = this;
  19424. var loader = new FileLoader( scope.manager );
  19425. loader.setResponseType( 'json' );
  19426. loader.load( url, function ( json ) {
  19427. onLoad( scope.parse( json ) );
  19428. }, onProgress, onError );
  19429. },
  19430. parse: function ( json ) {
  19431. var geometry = new BufferGeometry();
  19432. var index = json.data.index;
  19433. if ( index !== undefined ) {
  19434. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19435. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19436. }
  19437. var attributes = json.data.attributes;
  19438. for ( var key in attributes ) {
  19439. var attribute = attributes[ key ];
  19440. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19441. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19442. }
  19443. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19444. if ( groups !== undefined ) {
  19445. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19446. var group = groups[ i ];
  19447. geometry.addGroup( group.start, group.count, group.materialIndex );
  19448. }
  19449. }
  19450. var boundingSphere = json.data.boundingSphere;
  19451. if ( boundingSphere !== undefined ) {
  19452. var center = new Vector3();
  19453. if ( boundingSphere.center !== undefined ) {
  19454. center.fromArray( boundingSphere.center );
  19455. }
  19456. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19457. }
  19458. return geometry;
  19459. }
  19460. } );
  19461. var TYPED_ARRAYS = {
  19462. Int8Array: Int8Array,
  19463. Uint8Array: Uint8Array,
  19464. Uint8ClampedArray: Uint8ClampedArray,
  19465. Int16Array: Int16Array,
  19466. Uint16Array: Uint16Array,
  19467. Int32Array: Int32Array,
  19468. Uint32Array: Uint32Array,
  19469. Float32Array: Float32Array,
  19470. Float64Array: Float64Array
  19471. };
  19472. /**
  19473. * @author alteredq / http://alteredqualia.com/
  19474. */
  19475. function Loader() {
  19476. this.onLoadStart = function () {};
  19477. this.onLoadProgress = function () {};
  19478. this.onLoadComplete = function () {};
  19479. }
  19480. Loader.Handlers = {
  19481. handlers: [],
  19482. add: function ( regex, loader ) {
  19483. this.handlers.push( regex, loader );
  19484. },
  19485. get: function ( file ) {
  19486. var handlers = this.handlers;
  19487. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19488. var regex = handlers[ i ];
  19489. var loader = handlers[ i + 1 ];
  19490. if ( regex.test( file ) ) {
  19491. return loader;
  19492. }
  19493. }
  19494. return null;
  19495. }
  19496. };
  19497. Object.assign( Loader.prototype, {
  19498. crossOrigin: undefined,
  19499. extractUrlBase: function ( url ) {
  19500. var parts = url.split( '/' );
  19501. if ( parts.length === 1 ) return './';
  19502. parts.pop();
  19503. return parts.join( '/' ) + '/';
  19504. },
  19505. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19506. var array = [];
  19507. for ( var i = 0; i < materials.length; ++ i ) {
  19508. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19509. }
  19510. return array;
  19511. },
  19512. createMaterial: ( function () {
  19513. var BlendingMode = {
  19514. NoBlending: NoBlending,
  19515. NormalBlending: NormalBlending,
  19516. AdditiveBlending: AdditiveBlending,
  19517. SubtractiveBlending: SubtractiveBlending,
  19518. MultiplyBlending: MultiplyBlending,
  19519. CustomBlending: CustomBlending
  19520. };
  19521. var color, textureLoader, materialLoader;
  19522. return function createMaterial( m, texturePath, crossOrigin ) {
  19523. if ( color === undefined ) color = new Color();
  19524. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  19525. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  19526. // convert from old material format
  19527. var textures = {};
  19528. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19529. var fullPath = texturePath + path;
  19530. var loader = Loader.Handlers.get( fullPath );
  19531. var texture;
  19532. if ( loader !== null ) {
  19533. texture = loader.load( fullPath );
  19534. } else {
  19535. textureLoader.setCrossOrigin( crossOrigin );
  19536. texture = textureLoader.load( fullPath );
  19537. }
  19538. if ( repeat !== undefined ) {
  19539. texture.repeat.fromArray( repeat );
  19540. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19541. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19542. }
  19543. if ( offset !== undefined ) {
  19544. texture.offset.fromArray( offset );
  19545. }
  19546. if ( wrap !== undefined ) {
  19547. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19548. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19549. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19550. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19551. }
  19552. if ( anisotropy !== undefined ) {
  19553. texture.anisotropy = anisotropy;
  19554. }
  19555. var uuid = _Math.generateUUID();
  19556. textures[ uuid ] = texture;
  19557. return uuid;
  19558. }
  19559. //
  19560. var json = {
  19561. uuid: _Math.generateUUID(),
  19562. type: 'MeshLambertMaterial'
  19563. };
  19564. for ( var name in m ) {
  19565. var value = m[ name ];
  19566. switch ( name ) {
  19567. case 'DbgColor':
  19568. case 'DbgIndex':
  19569. case 'opticalDensity':
  19570. case 'illumination':
  19571. break;
  19572. case 'DbgName':
  19573. json.name = value;
  19574. break;
  19575. case 'blending':
  19576. json.blending = BlendingMode[ value ];
  19577. break;
  19578. case 'colorAmbient':
  19579. case 'mapAmbient':
  19580. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19581. break;
  19582. case 'colorDiffuse':
  19583. json.color = color.fromArray( value ).getHex();
  19584. break;
  19585. case 'colorSpecular':
  19586. json.specular = color.fromArray( value ).getHex();
  19587. break;
  19588. case 'colorEmissive':
  19589. json.emissive = color.fromArray( value ).getHex();
  19590. break;
  19591. case 'specularCoef':
  19592. json.shininess = value;
  19593. break;
  19594. case 'shading':
  19595. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19596. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19597. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19598. break;
  19599. case 'mapDiffuse':
  19600. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19601. break;
  19602. case 'mapDiffuseRepeat':
  19603. case 'mapDiffuseOffset':
  19604. case 'mapDiffuseWrap':
  19605. case 'mapDiffuseAnisotropy':
  19606. break;
  19607. case 'mapEmissive':
  19608. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19609. break;
  19610. case 'mapEmissiveRepeat':
  19611. case 'mapEmissiveOffset':
  19612. case 'mapEmissiveWrap':
  19613. case 'mapEmissiveAnisotropy':
  19614. break;
  19615. case 'mapLight':
  19616. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19617. break;
  19618. case 'mapLightRepeat':
  19619. case 'mapLightOffset':
  19620. case 'mapLightWrap':
  19621. case 'mapLightAnisotropy':
  19622. break;
  19623. case 'mapAO':
  19624. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19625. break;
  19626. case 'mapAORepeat':
  19627. case 'mapAOOffset':
  19628. case 'mapAOWrap':
  19629. case 'mapAOAnisotropy':
  19630. break;
  19631. case 'mapBump':
  19632. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19633. break;
  19634. case 'mapBumpScale':
  19635. json.bumpScale = value;
  19636. break;
  19637. case 'mapBumpRepeat':
  19638. case 'mapBumpOffset':
  19639. case 'mapBumpWrap':
  19640. case 'mapBumpAnisotropy':
  19641. break;
  19642. case 'mapNormal':
  19643. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19644. break;
  19645. case 'mapNormalFactor':
  19646. json.normalScale = [ value, value ];
  19647. break;
  19648. case 'mapNormalRepeat':
  19649. case 'mapNormalOffset':
  19650. case 'mapNormalWrap':
  19651. case 'mapNormalAnisotropy':
  19652. break;
  19653. case 'mapSpecular':
  19654. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19655. break;
  19656. case 'mapSpecularRepeat':
  19657. case 'mapSpecularOffset':
  19658. case 'mapSpecularWrap':
  19659. case 'mapSpecularAnisotropy':
  19660. break;
  19661. case 'mapMetalness':
  19662. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19663. break;
  19664. case 'mapMetalnessRepeat':
  19665. case 'mapMetalnessOffset':
  19666. case 'mapMetalnessWrap':
  19667. case 'mapMetalnessAnisotropy':
  19668. break;
  19669. case 'mapRoughness':
  19670. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19671. break;
  19672. case 'mapRoughnessRepeat':
  19673. case 'mapRoughnessOffset':
  19674. case 'mapRoughnessWrap':
  19675. case 'mapRoughnessAnisotropy':
  19676. break;
  19677. case 'mapAlpha':
  19678. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19679. break;
  19680. case 'mapAlphaRepeat':
  19681. case 'mapAlphaOffset':
  19682. case 'mapAlphaWrap':
  19683. case 'mapAlphaAnisotropy':
  19684. break;
  19685. case 'flipSided':
  19686. json.side = BackSide;
  19687. break;
  19688. case 'doubleSided':
  19689. json.side = DoubleSide;
  19690. break;
  19691. case 'transparency':
  19692. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19693. json.opacity = value;
  19694. break;
  19695. case 'depthTest':
  19696. case 'depthWrite':
  19697. case 'colorWrite':
  19698. case 'opacity':
  19699. case 'reflectivity':
  19700. case 'transparent':
  19701. case 'visible':
  19702. case 'wireframe':
  19703. json[ name ] = value;
  19704. break;
  19705. case 'vertexColors':
  19706. if ( value === true ) json.vertexColors = VertexColors;
  19707. if ( value === 'face' ) json.vertexColors = FaceColors;
  19708. break;
  19709. default:
  19710. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19711. break;
  19712. }
  19713. }
  19714. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19715. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19716. if ( json.opacity < 1 ) json.transparent = true;
  19717. materialLoader.setTextures( textures );
  19718. return materialLoader.parse( json );
  19719. };
  19720. } )()
  19721. } );
  19722. /**
  19723. * @author mrdoob / http://mrdoob.com/
  19724. * @author alteredq / http://alteredqualia.com/
  19725. */
  19726. function JSONLoader( manager ) {
  19727. if ( typeof manager === 'boolean' ) {
  19728. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19729. manager = undefined;
  19730. }
  19731. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19732. this.withCredentials = false;
  19733. }
  19734. Object.assign( JSONLoader.prototype, {
  19735. load: function ( url, onLoad, onProgress, onError ) {
  19736. var scope = this;
  19737. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19738. var loader = new FileLoader( this.manager );
  19739. loader.setResponseType( 'json' );
  19740. loader.setWithCredentials( this.withCredentials );
  19741. loader.load( url, function ( json ) {
  19742. var metadata = json.metadata;
  19743. if ( metadata !== undefined ) {
  19744. var type = metadata.type;
  19745. if ( type !== undefined ) {
  19746. if ( type.toLowerCase() === 'object' ) {
  19747. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19748. return;
  19749. }
  19750. if ( type.toLowerCase() === 'scene' ) {
  19751. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19752. return;
  19753. }
  19754. }
  19755. }
  19756. var object = scope.parse( json, texturePath );
  19757. onLoad( object.geometry, object.materials );
  19758. }, onProgress, onError );
  19759. },
  19760. setTexturePath: function ( value ) {
  19761. this.texturePath = value;
  19762. },
  19763. parse: ( function () {
  19764. function parseModel( json, geometry ) {
  19765. function isBitSet( value, position ) {
  19766. return value & ( 1 << position );
  19767. }
  19768. var i, j, fi,
  19769. offset, zLength,
  19770. colorIndex, normalIndex, uvIndex, materialIndex,
  19771. type,
  19772. isQuad,
  19773. hasMaterial,
  19774. hasFaceVertexUv,
  19775. hasFaceNormal, hasFaceVertexNormal,
  19776. hasFaceColor, hasFaceVertexColor,
  19777. vertex, face, faceA, faceB, hex, normal,
  19778. uvLayer, uv, u, v,
  19779. faces = json.faces,
  19780. vertices = json.vertices,
  19781. normals = json.normals,
  19782. colors = json.colors,
  19783. scale = json.scale,
  19784. nUvLayers = 0;
  19785. if ( json.uvs !== undefined ) {
  19786. // disregard empty arrays
  19787. for ( i = 0; i < json.uvs.length; i ++ ) {
  19788. if ( json.uvs[ i ].length ) nUvLayers ++;
  19789. }
  19790. for ( i = 0; i < nUvLayers; i ++ ) {
  19791. geometry.faceVertexUvs[ i ] = [];
  19792. }
  19793. }
  19794. offset = 0;
  19795. zLength = vertices.length;
  19796. while ( offset < zLength ) {
  19797. vertex = new Vector3();
  19798. vertex.x = vertices[ offset ++ ] * scale;
  19799. vertex.y = vertices[ offset ++ ] * scale;
  19800. vertex.z = vertices[ offset ++ ] * scale;
  19801. geometry.vertices.push( vertex );
  19802. }
  19803. offset = 0;
  19804. zLength = faces.length;
  19805. while ( offset < zLength ) {
  19806. type = faces[ offset ++ ];
  19807. isQuad = isBitSet( type, 0 );
  19808. hasMaterial = isBitSet( type, 1 );
  19809. hasFaceVertexUv = isBitSet( type, 3 );
  19810. hasFaceNormal = isBitSet( type, 4 );
  19811. hasFaceVertexNormal = isBitSet( type, 5 );
  19812. hasFaceColor = isBitSet( type, 6 );
  19813. hasFaceVertexColor = isBitSet( type, 7 );
  19814. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19815. if ( isQuad ) {
  19816. faceA = new Face3();
  19817. faceA.a = faces[ offset ];
  19818. faceA.b = faces[ offset + 1 ];
  19819. faceA.c = faces[ offset + 3 ];
  19820. faceB = new Face3();
  19821. faceB.a = faces[ offset + 1 ];
  19822. faceB.b = faces[ offset + 2 ];
  19823. faceB.c = faces[ offset + 3 ];
  19824. offset += 4;
  19825. if ( hasMaterial ) {
  19826. materialIndex = faces[ offset ++ ];
  19827. faceA.materialIndex = materialIndex;
  19828. faceB.materialIndex = materialIndex;
  19829. }
  19830. // to get face <=> uv index correspondence
  19831. fi = geometry.faces.length;
  19832. if ( hasFaceVertexUv ) {
  19833. for ( i = 0; i < nUvLayers; i ++ ) {
  19834. uvLayer = json.uvs[ i ];
  19835. geometry.faceVertexUvs[ i ][ fi ] = [];
  19836. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19837. for ( j = 0; j < 4; j ++ ) {
  19838. uvIndex = faces[ offset ++ ];
  19839. u = uvLayer[ uvIndex * 2 ];
  19840. v = uvLayer[ uvIndex * 2 + 1 ];
  19841. uv = new Vector2( u, v );
  19842. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19843. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19844. }
  19845. }
  19846. }
  19847. if ( hasFaceNormal ) {
  19848. normalIndex = faces[ offset ++ ] * 3;
  19849. faceA.normal.set(
  19850. normals[ normalIndex ++ ],
  19851. normals[ normalIndex ++ ],
  19852. normals[ normalIndex ]
  19853. );
  19854. faceB.normal.copy( faceA.normal );
  19855. }
  19856. if ( hasFaceVertexNormal ) {
  19857. for ( i = 0; i < 4; i ++ ) {
  19858. normalIndex = faces[ offset ++ ] * 3;
  19859. normal = new Vector3(
  19860. normals[ normalIndex ++ ],
  19861. normals[ normalIndex ++ ],
  19862. normals[ normalIndex ]
  19863. );
  19864. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19865. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19866. }
  19867. }
  19868. if ( hasFaceColor ) {
  19869. colorIndex = faces[ offset ++ ];
  19870. hex = colors[ colorIndex ];
  19871. faceA.color.setHex( hex );
  19872. faceB.color.setHex( hex );
  19873. }
  19874. if ( hasFaceVertexColor ) {
  19875. for ( i = 0; i < 4; i ++ ) {
  19876. colorIndex = faces[ offset ++ ];
  19877. hex = colors[ colorIndex ];
  19878. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19879. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19880. }
  19881. }
  19882. geometry.faces.push( faceA );
  19883. geometry.faces.push( faceB );
  19884. } else {
  19885. face = new Face3();
  19886. face.a = faces[ offset ++ ];
  19887. face.b = faces[ offset ++ ];
  19888. face.c = faces[ offset ++ ];
  19889. if ( hasMaterial ) {
  19890. materialIndex = faces[ offset ++ ];
  19891. face.materialIndex = materialIndex;
  19892. }
  19893. // to get face <=> uv index correspondence
  19894. fi = geometry.faces.length;
  19895. if ( hasFaceVertexUv ) {
  19896. for ( i = 0; i < nUvLayers; i ++ ) {
  19897. uvLayer = json.uvs[ i ];
  19898. geometry.faceVertexUvs[ i ][ fi ] = [];
  19899. for ( j = 0; j < 3; j ++ ) {
  19900. uvIndex = faces[ offset ++ ];
  19901. u = uvLayer[ uvIndex * 2 ];
  19902. v = uvLayer[ uvIndex * 2 + 1 ];
  19903. uv = new Vector2( u, v );
  19904. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19905. }
  19906. }
  19907. }
  19908. if ( hasFaceNormal ) {
  19909. normalIndex = faces[ offset ++ ] * 3;
  19910. face.normal.set(
  19911. normals[ normalIndex ++ ],
  19912. normals[ normalIndex ++ ],
  19913. normals[ normalIndex ]
  19914. );
  19915. }
  19916. if ( hasFaceVertexNormal ) {
  19917. for ( i = 0; i < 3; i ++ ) {
  19918. normalIndex = faces[ offset ++ ] * 3;
  19919. normal = new Vector3(
  19920. normals[ normalIndex ++ ],
  19921. normals[ normalIndex ++ ],
  19922. normals[ normalIndex ]
  19923. );
  19924. face.vertexNormals.push( normal );
  19925. }
  19926. }
  19927. if ( hasFaceColor ) {
  19928. colorIndex = faces[ offset ++ ];
  19929. face.color.setHex( colors[ colorIndex ] );
  19930. }
  19931. if ( hasFaceVertexColor ) {
  19932. for ( i = 0; i < 3; i ++ ) {
  19933. colorIndex = faces[ offset ++ ];
  19934. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19935. }
  19936. }
  19937. geometry.faces.push( face );
  19938. }
  19939. }
  19940. }
  19941. function parseSkin( json, geometry ) {
  19942. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19943. if ( json.skinWeights ) {
  19944. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19945. var x = json.skinWeights[ i ];
  19946. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19947. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19948. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19949. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19950. }
  19951. }
  19952. if ( json.skinIndices ) {
  19953. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19954. var a = json.skinIndices[ i ];
  19955. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19956. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19957. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19958. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19959. }
  19960. }
  19961. geometry.bones = json.bones;
  19962. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19963. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19964. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19965. }
  19966. }
  19967. function parseMorphing( json, geometry ) {
  19968. var scale = json.scale;
  19969. if ( json.morphTargets !== undefined ) {
  19970. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19971. geometry.morphTargets[ i ] = {};
  19972. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19973. geometry.morphTargets[ i ].vertices = [];
  19974. var dstVertices = geometry.morphTargets[ i ].vertices;
  19975. var srcVertices = json.morphTargets[ i ].vertices;
  19976. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19977. var vertex = new Vector3();
  19978. vertex.x = srcVertices[ v ] * scale;
  19979. vertex.y = srcVertices[ v + 1 ] * scale;
  19980. vertex.z = srcVertices[ v + 2 ] * scale;
  19981. dstVertices.push( vertex );
  19982. }
  19983. }
  19984. }
  19985. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19986. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19987. var faces = geometry.faces;
  19988. var morphColors = json.morphColors[ 0 ].colors;
  19989. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19990. faces[ i ].color.fromArray( morphColors, i * 3 );
  19991. }
  19992. }
  19993. }
  19994. function parseAnimations( json, geometry ) {
  19995. var outputAnimations = [];
  19996. // parse old style Bone/Hierarchy animations
  19997. var animations = [];
  19998. if ( json.animation !== undefined ) {
  19999. animations.push( json.animation );
  20000. }
  20001. if ( json.animations !== undefined ) {
  20002. if ( json.animations.length ) {
  20003. animations = animations.concat( json.animations );
  20004. } else {
  20005. animations.push( json.animations );
  20006. }
  20007. }
  20008. for ( var i = 0; i < animations.length; i ++ ) {
  20009. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20010. if ( clip ) outputAnimations.push( clip );
  20011. }
  20012. // parse implicit morph animations
  20013. if ( geometry.morphTargets ) {
  20014. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20015. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20016. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20017. }
  20018. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20019. }
  20020. return function ( json, texturePath ) {
  20021. if ( json.data !== undefined ) {
  20022. // Geometry 4.0 spec
  20023. json = json.data;
  20024. }
  20025. if ( json.scale !== undefined ) {
  20026. json.scale = 1.0 / json.scale;
  20027. } else {
  20028. json.scale = 1.0;
  20029. }
  20030. var geometry = new Geometry();
  20031. parseModel( json, geometry );
  20032. parseSkin( json, geometry );
  20033. parseMorphing( json, geometry );
  20034. parseAnimations( json, geometry );
  20035. geometry.computeFaceNormals();
  20036. geometry.computeBoundingSphere();
  20037. if ( json.materials === undefined || json.materials.length === 0 ) {
  20038. return { geometry: geometry };
  20039. } else {
  20040. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20041. return { geometry: geometry, materials: materials };
  20042. }
  20043. };
  20044. } )()
  20045. } );
  20046. /**
  20047. * @author mrdoob / http://mrdoob.com/
  20048. */
  20049. function ObjectLoader( manager ) {
  20050. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20051. this.texturePath = '';
  20052. }
  20053. Object.assign( ObjectLoader.prototype, {
  20054. load: function ( url, onLoad, onProgress, onError ) {
  20055. if ( this.texturePath === '' ) {
  20056. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20057. }
  20058. var scope = this;
  20059. var loader = new FileLoader( scope.manager );
  20060. loader.load( url, function ( text ) {
  20061. var json = null;
  20062. try {
  20063. json = JSON.parse( text );
  20064. } catch ( error ) {
  20065. if ( onError !== undefined ) onError( error );
  20066. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20067. return;
  20068. }
  20069. var metadata = json.metadata;
  20070. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20071. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20072. return;
  20073. }
  20074. scope.parse( json, onLoad );
  20075. }, onProgress, onError );
  20076. },
  20077. setTexturePath: function ( value ) {
  20078. this.texturePath = value;
  20079. },
  20080. setCrossOrigin: function ( value ) {
  20081. this.crossOrigin = value;
  20082. },
  20083. parse: function ( json, onLoad ) {
  20084. var geometries = this.parseGeometries( json.geometries );
  20085. var images = this.parseImages( json.images, function () {
  20086. if ( onLoad !== undefined ) onLoad( object );
  20087. } );
  20088. var textures = this.parseTextures( json.textures, images );
  20089. var materials = this.parseMaterials( json.materials, textures );
  20090. var object = this.parseObject( json.object, geometries, materials );
  20091. if ( json.animations ) {
  20092. object.animations = this.parseAnimations( json.animations );
  20093. }
  20094. if ( json.images === undefined || json.images.length === 0 ) {
  20095. if ( onLoad !== undefined ) onLoad( object );
  20096. }
  20097. return object;
  20098. },
  20099. parseGeometries: function ( json ) {
  20100. var geometries = {};
  20101. if ( json !== undefined ) {
  20102. var geometryLoader = new JSONLoader();
  20103. var bufferGeometryLoader = new BufferGeometryLoader();
  20104. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20105. var geometry;
  20106. var data = json[ i ];
  20107. switch ( data.type ) {
  20108. case 'PlaneGeometry':
  20109. case 'PlaneBufferGeometry':
  20110. geometry = new Geometries[ data.type ](
  20111. data.width,
  20112. data.height,
  20113. data.widthSegments,
  20114. data.heightSegments
  20115. );
  20116. break;
  20117. case 'BoxGeometry':
  20118. case 'BoxBufferGeometry':
  20119. case 'CubeGeometry': // backwards compatible
  20120. geometry = new Geometries[ data.type ](
  20121. data.width,
  20122. data.height,
  20123. data.depth,
  20124. data.widthSegments,
  20125. data.heightSegments,
  20126. data.depthSegments
  20127. );
  20128. break;
  20129. case 'CircleGeometry':
  20130. case 'CircleBufferGeometry':
  20131. geometry = new Geometries[ data.type ](
  20132. data.radius,
  20133. data.segments,
  20134. data.thetaStart,
  20135. data.thetaLength
  20136. );
  20137. break;
  20138. case 'CylinderGeometry':
  20139. case 'CylinderBufferGeometry':
  20140. geometry = new Geometries[ data.type ](
  20141. data.radiusTop,
  20142. data.radiusBottom,
  20143. data.height,
  20144. data.radialSegments,
  20145. data.heightSegments,
  20146. data.openEnded,
  20147. data.thetaStart,
  20148. data.thetaLength
  20149. );
  20150. break;
  20151. case 'ConeGeometry':
  20152. case 'ConeBufferGeometry':
  20153. geometry = new Geometries[ data.type ](
  20154. data.radius,
  20155. data.height,
  20156. data.radialSegments,
  20157. data.heightSegments,
  20158. data.openEnded,
  20159. data.thetaStart,
  20160. data.thetaLength
  20161. );
  20162. break;
  20163. case 'SphereGeometry':
  20164. case 'SphereBufferGeometry':
  20165. geometry = new Geometries[ data.type ](
  20166. data.radius,
  20167. data.widthSegments,
  20168. data.heightSegments,
  20169. data.phiStart,
  20170. data.phiLength,
  20171. data.thetaStart,
  20172. data.thetaLength
  20173. );
  20174. break;
  20175. case 'DodecahedronGeometry':
  20176. case 'IcosahedronGeometry':
  20177. case 'OctahedronGeometry':
  20178. case 'TetrahedronGeometry':
  20179. geometry = new Geometries[ data.type ](
  20180. data.radius,
  20181. data.detail
  20182. );
  20183. break;
  20184. case 'RingGeometry':
  20185. case 'RingBufferGeometry':
  20186. geometry = new Geometries[ data.type ](
  20187. data.innerRadius,
  20188. data.outerRadius,
  20189. data.thetaSegments,
  20190. data.phiSegments,
  20191. data.thetaStart,
  20192. data.thetaLength
  20193. );
  20194. break;
  20195. case 'TorusGeometry':
  20196. case 'TorusBufferGeometry':
  20197. geometry = new Geometries[ data.type ](
  20198. data.radius,
  20199. data.tube,
  20200. data.radialSegments,
  20201. data.tubularSegments,
  20202. data.arc
  20203. );
  20204. break;
  20205. case 'TorusKnotGeometry':
  20206. case 'TorusKnotBufferGeometry':
  20207. geometry = new Geometries[ data.type ](
  20208. data.radius,
  20209. data.tube,
  20210. data.tubularSegments,
  20211. data.radialSegments,
  20212. data.p,
  20213. data.q
  20214. );
  20215. break;
  20216. case 'LatheGeometry':
  20217. case 'LatheBufferGeometry':
  20218. geometry = new Geometries[ data.type ](
  20219. data.points,
  20220. data.segments,
  20221. data.phiStart,
  20222. data.phiLength
  20223. );
  20224. break;
  20225. case 'BufferGeometry':
  20226. geometry = bufferGeometryLoader.parse( data );
  20227. break;
  20228. case 'Geometry':
  20229. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20230. break;
  20231. default:
  20232. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20233. continue;
  20234. }
  20235. geometry.uuid = data.uuid;
  20236. if ( data.name !== undefined ) geometry.name = data.name;
  20237. geometries[ data.uuid ] = geometry;
  20238. }
  20239. }
  20240. return geometries;
  20241. },
  20242. parseMaterials: function ( json, textures ) {
  20243. var materials = {};
  20244. if ( json !== undefined ) {
  20245. var loader = new MaterialLoader();
  20246. loader.setTextures( textures );
  20247. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20248. var data = json[ i ];
  20249. if ( data.type === 'MultiMaterial' ) {
  20250. // Deprecated
  20251. var array = [];
  20252. for ( var j = 0; j < data.materials.length; j ++ ) {
  20253. array.push( loader.parse( data.materials[ j ] ) );
  20254. }
  20255. materials[ data.uuid ] = array;
  20256. } else {
  20257. materials[ data.uuid ] = loader.parse( data );
  20258. }
  20259. }
  20260. }
  20261. return materials;
  20262. },
  20263. parseAnimations: function ( json ) {
  20264. var animations = [];
  20265. for ( var i = 0; i < json.length; i ++ ) {
  20266. var clip = AnimationClip.parse( json[ i ] );
  20267. animations.push( clip );
  20268. }
  20269. return animations;
  20270. },
  20271. parseImages: function ( json, onLoad ) {
  20272. var scope = this;
  20273. var images = {};
  20274. function loadImage( url ) {
  20275. scope.manager.itemStart( url );
  20276. return loader.load( url, function () {
  20277. scope.manager.itemEnd( url );
  20278. }, undefined, function () {
  20279. scope.manager.itemEnd( url );
  20280. scope.manager.itemError( url );
  20281. } );
  20282. }
  20283. if ( json !== undefined && json.length > 0 ) {
  20284. var manager = new LoadingManager( onLoad );
  20285. var loader = new ImageLoader( manager );
  20286. loader.setCrossOrigin( this.crossOrigin );
  20287. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20288. var image = json[ i ];
  20289. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20290. images[ image.uuid ] = loadImage( path );
  20291. }
  20292. }
  20293. return images;
  20294. },
  20295. parseTextures: function ( json, images ) {
  20296. function parseConstant( value, type ) {
  20297. if ( typeof( value ) === 'number' ) return value;
  20298. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20299. return type[ value ];
  20300. }
  20301. var textures = {};
  20302. if ( json !== undefined ) {
  20303. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20304. var data = json[ i ];
  20305. if ( data.image === undefined ) {
  20306. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20307. }
  20308. if ( images[ data.image ] === undefined ) {
  20309. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20310. }
  20311. var texture = new Texture( images[ data.image ] );
  20312. texture.needsUpdate = true;
  20313. texture.uuid = data.uuid;
  20314. if ( data.name !== undefined ) texture.name = data.name;
  20315. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20316. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20317. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20318. if ( data.wrap !== undefined ) {
  20319. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20320. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20321. }
  20322. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20323. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20324. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20325. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20326. textures[ data.uuid ] = texture;
  20327. }
  20328. }
  20329. return textures;
  20330. },
  20331. parseObject: function () {
  20332. var matrix = new Matrix4();
  20333. return function parseObject( data, geometries, materials ) {
  20334. var object;
  20335. function getGeometry( name ) {
  20336. if ( geometries[ name ] === undefined ) {
  20337. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20338. }
  20339. return geometries[ name ];
  20340. }
  20341. function getMaterial( name ) {
  20342. if ( name === undefined ) return undefined;
  20343. if ( Array.isArray( name ) ) {
  20344. var array = [];
  20345. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20346. var uuid = name[ i ];
  20347. if ( materials[ uuid ] === undefined ) {
  20348. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20349. }
  20350. array.push( materials[ uuid ] );
  20351. }
  20352. return array;
  20353. }
  20354. if ( materials[ name ] === undefined ) {
  20355. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20356. }
  20357. return materials[ name ];
  20358. }
  20359. switch ( data.type ) {
  20360. case 'Scene':
  20361. object = new Scene();
  20362. if ( data.background !== undefined ) {
  20363. if ( Number.isInteger( data.background ) ) {
  20364. object.background = new Color( data.background );
  20365. }
  20366. }
  20367. if ( data.fog !== undefined ) {
  20368. if ( data.fog.type === 'Fog' ) {
  20369. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20370. } else if ( data.fog.type === 'FogExp2' ) {
  20371. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20372. }
  20373. }
  20374. break;
  20375. case 'PerspectiveCamera':
  20376. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20377. if ( data.focus !== undefined ) object.focus = data.focus;
  20378. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20379. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20380. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20381. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20382. break;
  20383. case 'OrthographicCamera':
  20384. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20385. break;
  20386. case 'AmbientLight':
  20387. object = new AmbientLight( data.color, data.intensity );
  20388. break;
  20389. case 'DirectionalLight':
  20390. object = new DirectionalLight( data.color, data.intensity );
  20391. break;
  20392. case 'PointLight':
  20393. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20394. break;
  20395. case 'RectAreaLight':
  20396. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20397. break;
  20398. case 'SpotLight':
  20399. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20400. break;
  20401. case 'HemisphereLight':
  20402. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20403. break;
  20404. case 'SkinnedMesh':
  20405. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20406. case 'Mesh':
  20407. var geometry = getGeometry( data.geometry );
  20408. var material = getMaterial( data.material );
  20409. if ( geometry.bones && geometry.bones.length > 0 ) {
  20410. object = new SkinnedMesh( geometry, material );
  20411. } else {
  20412. object = new Mesh( geometry, material );
  20413. }
  20414. break;
  20415. case 'LOD':
  20416. object = new LOD();
  20417. break;
  20418. case 'Line':
  20419. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20420. break;
  20421. case 'LineLoop':
  20422. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20423. break;
  20424. case 'LineSegments':
  20425. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20426. break;
  20427. case 'PointCloud':
  20428. case 'Points':
  20429. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20430. break;
  20431. case 'Sprite':
  20432. object = new Sprite( getMaterial( data.material ) );
  20433. break;
  20434. case 'Group':
  20435. object = new Group();
  20436. break;
  20437. default:
  20438. object = new Object3D();
  20439. }
  20440. object.uuid = data.uuid;
  20441. if ( data.name !== undefined ) object.name = data.name;
  20442. if ( data.matrix !== undefined ) {
  20443. matrix.fromArray( data.matrix );
  20444. matrix.decompose( object.position, object.quaternion, object.scale );
  20445. } else {
  20446. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20447. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20448. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20449. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20450. }
  20451. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20452. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20453. if ( data.shadow ) {
  20454. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20455. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20456. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20457. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20458. }
  20459. if ( data.visible !== undefined ) object.visible = data.visible;
  20460. if ( data.userData !== undefined ) object.userData = data.userData;
  20461. if ( data.children !== undefined ) {
  20462. for ( var child in data.children ) {
  20463. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20464. }
  20465. }
  20466. if ( data.type === 'LOD' ) {
  20467. var levels = data.levels;
  20468. for ( var l = 0; l < levels.length; l ++ ) {
  20469. var level = levels[ l ];
  20470. var child = object.getObjectByProperty( 'uuid', level.object );
  20471. if ( child !== undefined ) {
  20472. object.addLevel( child, level.distance );
  20473. }
  20474. }
  20475. }
  20476. return object;
  20477. };
  20478. }()
  20479. } );
  20480. var TEXTURE_MAPPING = {
  20481. UVMapping: UVMapping,
  20482. CubeReflectionMapping: CubeReflectionMapping,
  20483. CubeRefractionMapping: CubeRefractionMapping,
  20484. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20485. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20486. SphericalReflectionMapping: SphericalReflectionMapping,
  20487. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20488. CubeUVRefractionMapping: CubeUVRefractionMapping
  20489. };
  20490. var TEXTURE_WRAPPING = {
  20491. RepeatWrapping: RepeatWrapping,
  20492. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20493. MirroredRepeatWrapping: MirroredRepeatWrapping
  20494. };
  20495. var TEXTURE_FILTER = {
  20496. NearestFilter: NearestFilter,
  20497. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20498. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20499. LinearFilter: LinearFilter,
  20500. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20501. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20502. };
  20503. /**
  20504. * @author zz85 / http://www.lab4games.net/zz85/blog
  20505. *
  20506. * Bezier Curves formulas obtained from
  20507. * http://en.wikipedia.org/wiki/Bézier_curve
  20508. */
  20509. function CatmullRom( t, p0, p1, p2, p3 ) {
  20510. var v0 = ( p2 - p0 ) * 0.5;
  20511. var v1 = ( p3 - p1 ) * 0.5;
  20512. var t2 = t * t;
  20513. var t3 = t * t2;
  20514. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20515. }
  20516. //
  20517. function QuadraticBezierP0( t, p ) {
  20518. var k = 1 - t;
  20519. return k * k * p;
  20520. }
  20521. function QuadraticBezierP1( t, p ) {
  20522. return 2 * ( 1 - t ) * t * p;
  20523. }
  20524. function QuadraticBezierP2( t, p ) {
  20525. return t * t * p;
  20526. }
  20527. function QuadraticBezier( t, p0, p1, p2 ) {
  20528. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20529. QuadraticBezierP2( t, p2 );
  20530. }
  20531. //
  20532. function CubicBezierP0( t, p ) {
  20533. var k = 1 - t;
  20534. return k * k * k * p;
  20535. }
  20536. function CubicBezierP1( t, p ) {
  20537. var k = 1 - t;
  20538. return 3 * k * k * t * p;
  20539. }
  20540. function CubicBezierP2( t, p ) {
  20541. return 3 * ( 1 - t ) * t * t * p;
  20542. }
  20543. function CubicBezierP3( t, p ) {
  20544. return t * t * t * p;
  20545. }
  20546. function CubicBezier( t, p0, p1, p2, p3 ) {
  20547. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20548. CubicBezierP3( t, p3 );
  20549. }
  20550. /**
  20551. * @author zz85 / http://www.lab4games.net/zz85/blog
  20552. * Extensible curve object
  20553. *
  20554. * Some common of curve methods:
  20555. * .getPoint(t), getTangent(t)
  20556. * .getPointAt(u), getTangentAt(u)
  20557. * .getPoints(), .getSpacedPoints()
  20558. * .getLength()
  20559. * .updateArcLengths()
  20560. *
  20561. * This following curves inherit from THREE.Curve:
  20562. *
  20563. * -- 2D curves --
  20564. * THREE.ArcCurve
  20565. * THREE.CubicBezierCurve
  20566. * THREE.EllipseCurve
  20567. * THREE.LineCurve
  20568. * THREE.QuadraticBezierCurve
  20569. * THREE.SplineCurve
  20570. *
  20571. * -- 3D curves --
  20572. * THREE.CatmullRomCurve3
  20573. * THREE.CubicBezierCurve3
  20574. * THREE.LineCurve3
  20575. * THREE.QuadraticBezierCurve3
  20576. *
  20577. * A series of curves can be represented as a THREE.CurvePath.
  20578. *
  20579. **/
  20580. /**************************************************************
  20581. * Abstract Curve base class
  20582. **************************************************************/
  20583. function Curve() {
  20584. this.arcLengthDivisions = 200;
  20585. }
  20586. Object.assign( Curve.prototype, {
  20587. // Virtual base class method to overwrite and implement in subclasses
  20588. // - t [0 .. 1]
  20589. getPoint: function () {
  20590. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20591. return null;
  20592. },
  20593. // Get point at relative position in curve according to arc length
  20594. // - u [0 .. 1]
  20595. getPointAt: function ( u ) {
  20596. var t = this.getUtoTmapping( u );
  20597. return this.getPoint( t );
  20598. },
  20599. // Get sequence of points using getPoint( t )
  20600. getPoints: function ( divisions ) {
  20601. if ( divisions === undefined ) divisions = 5;
  20602. var points = [];
  20603. for ( var d = 0; d <= divisions; d ++ ) {
  20604. points.push( this.getPoint( d / divisions ) );
  20605. }
  20606. return points;
  20607. },
  20608. // Get sequence of points using getPointAt( u )
  20609. getSpacedPoints: function ( divisions ) {
  20610. if ( divisions === undefined ) divisions = 5;
  20611. var points = [];
  20612. for ( var d = 0; d <= divisions; d ++ ) {
  20613. points.push( this.getPointAt( d / divisions ) );
  20614. }
  20615. return points;
  20616. },
  20617. // Get total curve arc length
  20618. getLength: function () {
  20619. var lengths = this.getLengths();
  20620. return lengths[ lengths.length - 1 ];
  20621. },
  20622. // Get list of cumulative segment lengths
  20623. getLengths: function ( divisions ) {
  20624. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20625. if ( this.cacheArcLengths &&
  20626. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20627. ! this.needsUpdate ) {
  20628. return this.cacheArcLengths;
  20629. }
  20630. this.needsUpdate = false;
  20631. var cache = [];
  20632. var current, last = this.getPoint( 0 );
  20633. var p, sum = 0;
  20634. cache.push( 0 );
  20635. for ( p = 1; p <= divisions; p ++ ) {
  20636. current = this.getPoint( p / divisions );
  20637. sum += current.distanceTo( last );
  20638. cache.push( sum );
  20639. last = current;
  20640. }
  20641. this.cacheArcLengths = cache;
  20642. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20643. },
  20644. updateArcLengths: function () {
  20645. this.needsUpdate = true;
  20646. this.getLengths();
  20647. },
  20648. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20649. getUtoTmapping: function ( u, distance ) {
  20650. var arcLengths = this.getLengths();
  20651. var i = 0, il = arcLengths.length;
  20652. var targetArcLength; // The targeted u distance value to get
  20653. if ( distance ) {
  20654. targetArcLength = distance;
  20655. } else {
  20656. targetArcLength = u * arcLengths[ il - 1 ];
  20657. }
  20658. // binary search for the index with largest value smaller than target u distance
  20659. var low = 0, high = il - 1, comparison;
  20660. while ( low <= high ) {
  20661. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  20662. comparison = arcLengths[ i ] - targetArcLength;
  20663. if ( comparison < 0 ) {
  20664. low = i + 1;
  20665. } else if ( comparison > 0 ) {
  20666. high = i - 1;
  20667. } else {
  20668. high = i;
  20669. break;
  20670. // DONE
  20671. }
  20672. }
  20673. i = high;
  20674. if ( arcLengths[ i ] === targetArcLength ) {
  20675. return i / ( il - 1 );
  20676. }
  20677. // we could get finer grain at lengths, or use simple interpolation between two points
  20678. var lengthBefore = arcLengths[ i ];
  20679. var lengthAfter = arcLengths[ i + 1 ];
  20680. var segmentLength = lengthAfter - lengthBefore;
  20681. // determine where we are between the 'before' and 'after' points
  20682. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20683. // add that fractional amount to t
  20684. var t = ( i + segmentFraction ) / ( il - 1 );
  20685. return t;
  20686. },
  20687. // Returns a unit vector tangent at t
  20688. // In case any sub curve does not implement its tangent derivation,
  20689. // 2 points a small delta apart will be used to find its gradient
  20690. // which seems to give a reasonable approximation
  20691. getTangent: function ( t ) {
  20692. var delta = 0.0001;
  20693. var t1 = t - delta;
  20694. var t2 = t + delta;
  20695. // Capping in case of danger
  20696. if ( t1 < 0 ) t1 = 0;
  20697. if ( t2 > 1 ) t2 = 1;
  20698. var pt1 = this.getPoint( t1 );
  20699. var pt2 = this.getPoint( t2 );
  20700. var vec = pt2.clone().sub( pt1 );
  20701. return vec.normalize();
  20702. },
  20703. getTangentAt: function ( u ) {
  20704. var t = this.getUtoTmapping( u );
  20705. return this.getTangent( t );
  20706. },
  20707. computeFrenetFrames: function ( segments, closed ) {
  20708. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20709. var normal = new Vector3();
  20710. var tangents = [];
  20711. var normals = [];
  20712. var binormals = [];
  20713. var vec = new Vector3();
  20714. var mat = new Matrix4();
  20715. var i, u, theta;
  20716. // compute the tangent vectors for each segment on the curve
  20717. for ( i = 0; i <= segments; i ++ ) {
  20718. u = i / segments;
  20719. tangents[ i ] = this.getTangentAt( u );
  20720. tangents[ i ].normalize();
  20721. }
  20722. // select an initial normal vector perpendicular to the first tangent vector,
  20723. // and in the direction of the minimum tangent xyz component
  20724. normals[ 0 ] = new Vector3();
  20725. binormals[ 0 ] = new Vector3();
  20726. var min = Number.MAX_VALUE;
  20727. var tx = Math.abs( tangents[ 0 ].x );
  20728. var ty = Math.abs( tangents[ 0 ].y );
  20729. var tz = Math.abs( tangents[ 0 ].z );
  20730. if ( tx <= min ) {
  20731. min = tx;
  20732. normal.set( 1, 0, 0 );
  20733. }
  20734. if ( ty <= min ) {
  20735. min = ty;
  20736. normal.set( 0, 1, 0 );
  20737. }
  20738. if ( tz <= min ) {
  20739. normal.set( 0, 0, 1 );
  20740. }
  20741. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20742. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20743. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20744. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20745. for ( i = 1; i <= segments; i ++ ) {
  20746. normals[ i ] = normals[ i - 1 ].clone();
  20747. binormals[ i ] = binormals[ i - 1 ].clone();
  20748. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20749. if ( vec.length() > Number.EPSILON ) {
  20750. vec.normalize();
  20751. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20752. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20753. }
  20754. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20755. }
  20756. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20757. if ( closed === true ) {
  20758. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20759. theta /= segments;
  20760. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20761. theta = - theta;
  20762. }
  20763. for ( i = 1; i <= segments; i ++ ) {
  20764. // twist a little...
  20765. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20766. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20767. }
  20768. }
  20769. return {
  20770. tangents: tangents,
  20771. normals: normals,
  20772. binormals: binormals
  20773. };
  20774. }
  20775. } );
  20776. function LineCurve( v1, v2 ) {
  20777. Curve.call( this );
  20778. this.v1 = v1;
  20779. this.v2 = v2;
  20780. }
  20781. LineCurve.prototype = Object.create( Curve.prototype );
  20782. LineCurve.prototype.constructor = LineCurve;
  20783. LineCurve.prototype.isLineCurve = true;
  20784. LineCurve.prototype.getPoint = function ( t ) {
  20785. if ( t === 1 ) {
  20786. return this.v2.clone();
  20787. }
  20788. var point = this.v2.clone().sub( this.v1 );
  20789. point.multiplyScalar( t ).add( this.v1 );
  20790. return point;
  20791. };
  20792. // Line curve is linear, so we can overwrite default getPointAt
  20793. LineCurve.prototype.getPointAt = function ( u ) {
  20794. return this.getPoint( u );
  20795. };
  20796. LineCurve.prototype.getTangent = function ( t ) {
  20797. var tangent = this.v2.clone().sub( this.v1 );
  20798. return tangent.normalize();
  20799. };
  20800. /**
  20801. * @author zz85 / http://www.lab4games.net/zz85/blog
  20802. *
  20803. **/
  20804. /**************************************************************
  20805. * Curved Path - a curve path is simply a array of connected
  20806. * curves, but retains the api of a curve
  20807. **************************************************************/
  20808. function CurvePath() {
  20809. Curve.call( this );
  20810. this.curves = [];
  20811. this.autoClose = false; // Automatically closes the path
  20812. }
  20813. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20814. constructor: CurvePath,
  20815. add: function ( curve ) {
  20816. this.curves.push( curve );
  20817. },
  20818. closePath: function () {
  20819. // Add a line curve if start and end of lines are not connected
  20820. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20821. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20822. if ( ! startPoint.equals( endPoint ) ) {
  20823. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20824. }
  20825. },
  20826. // To get accurate point with reference to
  20827. // entire path distance at time t,
  20828. // following has to be done:
  20829. // 1. Length of each sub path have to be known
  20830. // 2. Locate and identify type of curve
  20831. // 3. Get t for the curve
  20832. // 4. Return curve.getPointAt(t')
  20833. getPoint: function ( t ) {
  20834. var d = t * this.getLength();
  20835. var curveLengths = this.getCurveLengths();
  20836. var i = 0;
  20837. // To think about boundaries points.
  20838. while ( i < curveLengths.length ) {
  20839. if ( curveLengths[ i ] >= d ) {
  20840. var diff = curveLengths[ i ] - d;
  20841. var curve = this.curves[ i ];
  20842. var segmentLength = curve.getLength();
  20843. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20844. return curve.getPointAt( u );
  20845. }
  20846. i ++;
  20847. }
  20848. return null;
  20849. // loop where sum != 0, sum > d , sum+1 <d
  20850. },
  20851. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20852. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20853. // getPoint() depends on getLength
  20854. getLength: function () {
  20855. var lens = this.getCurveLengths();
  20856. return lens[ lens.length - 1 ];
  20857. },
  20858. // cacheLengths must be recalculated.
  20859. updateArcLengths: function () {
  20860. this.needsUpdate = true;
  20861. this.cacheLengths = null;
  20862. this.getCurveLengths();
  20863. },
  20864. // Compute lengths and cache them
  20865. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20866. getCurveLengths: function () {
  20867. // We use cache values if curves and cache array are same length
  20868. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20869. return this.cacheLengths;
  20870. }
  20871. // Get length of sub-curve
  20872. // Push sums into cached array
  20873. var lengths = [], sums = 0;
  20874. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20875. sums += this.curves[ i ].getLength();
  20876. lengths.push( sums );
  20877. }
  20878. this.cacheLengths = lengths;
  20879. return lengths;
  20880. },
  20881. getSpacedPoints: function ( divisions ) {
  20882. if ( divisions === undefined ) divisions = 40;
  20883. var points = [];
  20884. for ( var i = 0; i <= divisions; i ++ ) {
  20885. points.push( this.getPoint( i / divisions ) );
  20886. }
  20887. if ( this.autoClose ) {
  20888. points.push( points[ 0 ] );
  20889. }
  20890. return points;
  20891. },
  20892. getPoints: function ( divisions ) {
  20893. divisions = divisions || 12;
  20894. var points = [], last;
  20895. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20896. var curve = curves[ i ];
  20897. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20898. : (curve && curve.isLineCurve) ? 1
  20899. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20900. : divisions;
  20901. var pts = curve.getPoints( resolution );
  20902. for ( var j = 0; j < pts.length; j++ ) {
  20903. var point = pts[ j ];
  20904. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20905. points.push( point );
  20906. last = point;
  20907. }
  20908. }
  20909. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20910. points.push( points[ 0 ] );
  20911. }
  20912. return points;
  20913. },
  20914. /**************************************************************
  20915. * Create Geometries Helpers
  20916. **************************************************************/
  20917. /// Generate geometry from path points (for Line or Points objects)
  20918. createPointsGeometry: function ( divisions ) {
  20919. var pts = this.getPoints( divisions );
  20920. return this.createGeometry( pts );
  20921. },
  20922. // Generate geometry from equidistant sampling along the path
  20923. createSpacedPointsGeometry: function ( divisions ) {
  20924. var pts = this.getSpacedPoints( divisions );
  20925. return this.createGeometry( pts );
  20926. },
  20927. createGeometry: function ( points ) {
  20928. var geometry = new Geometry();
  20929. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20930. var point = points[ i ];
  20931. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20932. }
  20933. return geometry;
  20934. }
  20935. } );
  20936. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20937. Curve.call( this );
  20938. this.aX = aX;
  20939. this.aY = aY;
  20940. this.xRadius = xRadius;
  20941. this.yRadius = yRadius;
  20942. this.aStartAngle = aStartAngle;
  20943. this.aEndAngle = aEndAngle;
  20944. this.aClockwise = aClockwise;
  20945. this.aRotation = aRotation || 0;
  20946. }
  20947. EllipseCurve.prototype = Object.create( Curve.prototype );
  20948. EllipseCurve.prototype.constructor = EllipseCurve;
  20949. EllipseCurve.prototype.isEllipseCurve = true;
  20950. EllipseCurve.prototype.getPoint = function ( t ) {
  20951. var twoPi = Math.PI * 2;
  20952. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20953. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20954. // ensures that deltaAngle is 0 .. 2 PI
  20955. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20956. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20957. if ( deltaAngle < Number.EPSILON ) {
  20958. if ( samePoints ) {
  20959. deltaAngle = 0;
  20960. } else {
  20961. deltaAngle = twoPi;
  20962. }
  20963. }
  20964. if ( this.aClockwise === true && ! samePoints ) {
  20965. if ( deltaAngle === twoPi ) {
  20966. deltaAngle = - twoPi;
  20967. } else {
  20968. deltaAngle = deltaAngle - twoPi;
  20969. }
  20970. }
  20971. var angle = this.aStartAngle + t * deltaAngle;
  20972. var x = this.aX + this.xRadius * Math.cos( angle );
  20973. var y = this.aY + this.yRadius * Math.sin( angle );
  20974. if ( this.aRotation !== 0 ) {
  20975. var cos = Math.cos( this.aRotation );
  20976. var sin = Math.sin( this.aRotation );
  20977. var tx = x - this.aX;
  20978. var ty = y - this.aY;
  20979. // Rotate the point about the center of the ellipse.
  20980. x = tx * cos - ty * sin + this.aX;
  20981. y = tx * sin + ty * cos + this.aY;
  20982. }
  20983. return new Vector2( x, y );
  20984. };
  20985. function SplineCurve( points /* array of Vector2 */ ) {
  20986. Curve.call( this );
  20987. this.points = ( points === undefined ) ? [] : points;
  20988. }
  20989. SplineCurve.prototype = Object.create( Curve.prototype );
  20990. SplineCurve.prototype.constructor = SplineCurve;
  20991. SplineCurve.prototype.isSplineCurve = true;
  20992. SplineCurve.prototype.getPoint = function ( t ) {
  20993. var points = this.points;
  20994. var point = ( points.length - 1 ) * t;
  20995. var intPoint = Math.floor( point );
  20996. var weight = point - intPoint;
  20997. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20998. var point1 = points[ intPoint ];
  20999. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21000. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21001. return new Vector2(
  21002. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21003. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21004. );
  21005. };
  21006. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21007. Curve.call( this );
  21008. this.v0 = v0;
  21009. this.v1 = v1;
  21010. this.v2 = v2;
  21011. this.v3 = v3;
  21012. }
  21013. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21014. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21015. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21016. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21017. return new Vector2(
  21018. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21019. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21020. );
  21021. };
  21022. function QuadraticBezierCurve( v0, v1, v2 ) {
  21023. Curve.call( this );
  21024. this.v0 = v0;
  21025. this.v1 = v1;
  21026. this.v2 = v2;
  21027. }
  21028. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21029. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21030. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21031. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21032. return new Vector2(
  21033. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21034. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21035. );
  21036. };
  21037. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21038. fromPoints: function ( vectors ) {
  21039. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21040. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21041. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21042. }
  21043. },
  21044. moveTo: function ( x, y ) {
  21045. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21046. },
  21047. lineTo: function ( x, y ) {
  21048. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21049. this.curves.push( curve );
  21050. this.currentPoint.set( x, y );
  21051. },
  21052. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21053. var curve = new QuadraticBezierCurve(
  21054. this.currentPoint.clone(),
  21055. new Vector2( aCPx, aCPy ),
  21056. new Vector2( aX, aY )
  21057. );
  21058. this.curves.push( curve );
  21059. this.currentPoint.set( aX, aY );
  21060. },
  21061. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21062. var curve = new CubicBezierCurve(
  21063. this.currentPoint.clone(),
  21064. new Vector2( aCP1x, aCP1y ),
  21065. new Vector2( aCP2x, aCP2y ),
  21066. new Vector2( aX, aY )
  21067. );
  21068. this.curves.push( curve );
  21069. this.currentPoint.set( aX, aY );
  21070. },
  21071. splineThru: function ( pts /*Array of Vector*/ ) {
  21072. var npts = [ this.currentPoint.clone() ].concat( pts );
  21073. var curve = new SplineCurve( npts );
  21074. this.curves.push( curve );
  21075. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21076. },
  21077. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21078. var x0 = this.currentPoint.x;
  21079. var y0 = this.currentPoint.y;
  21080. this.absarc( aX + x0, aY + y0, aRadius,
  21081. aStartAngle, aEndAngle, aClockwise );
  21082. },
  21083. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21084. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21085. },
  21086. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21087. var x0 = this.currentPoint.x;
  21088. var y0 = this.currentPoint.y;
  21089. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21090. },
  21091. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21092. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21093. if ( this.curves.length > 0 ) {
  21094. // if a previous curve is present, attempt to join
  21095. var firstPoint = curve.getPoint( 0 );
  21096. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21097. this.lineTo( firstPoint.x, firstPoint.y );
  21098. }
  21099. }
  21100. this.curves.push( curve );
  21101. var lastPoint = curve.getPoint( 1 );
  21102. this.currentPoint.copy( lastPoint );
  21103. }
  21104. } );
  21105. /**
  21106. * @author zz85 / http://www.lab4games.net/zz85/blog
  21107. * Creates free form 2d path using series of points, lines or curves.
  21108. **/
  21109. function Path( points ) {
  21110. CurvePath.call( this );
  21111. this.currentPoint = new Vector2();
  21112. if ( points ) {
  21113. this.fromPoints( points );
  21114. }
  21115. }
  21116. Path.prototype = PathPrototype;
  21117. PathPrototype.constructor = Path;
  21118. /**
  21119. * @author zz85 / http://www.lab4games.net/zz85/blog
  21120. * Defines a 2d shape plane using paths.
  21121. **/
  21122. // STEP 1 Create a path.
  21123. // STEP 2 Turn path into shape.
  21124. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21125. // STEP 3a - Extract points from each shape, turn to vertices
  21126. // STEP 3b - Triangulate each shape, add faces.
  21127. function Shape() {
  21128. Path.apply( this, arguments );
  21129. this.holes = [];
  21130. }
  21131. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21132. constructor: Shape,
  21133. getPointsHoles: function ( divisions ) {
  21134. var holesPts = [];
  21135. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21136. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21137. }
  21138. return holesPts;
  21139. },
  21140. // Get points of shape and holes (keypoints based on segments parameter)
  21141. extractAllPoints: function ( divisions ) {
  21142. return {
  21143. shape: this.getPoints( divisions ),
  21144. holes: this.getPointsHoles( divisions )
  21145. };
  21146. },
  21147. extractPoints: function ( divisions ) {
  21148. return this.extractAllPoints( divisions );
  21149. }
  21150. } );
  21151. /**
  21152. * @author zz85 / http://www.lab4games.net/zz85/blog
  21153. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21154. **/
  21155. function ShapePath() {
  21156. this.subPaths = [];
  21157. this.currentPath = null;
  21158. }
  21159. Object.assign( ShapePath.prototype, {
  21160. moveTo: function ( x, y ) {
  21161. this.currentPath = new Path();
  21162. this.subPaths.push( this.currentPath );
  21163. this.currentPath.moveTo( x, y );
  21164. },
  21165. lineTo: function ( x, y ) {
  21166. this.currentPath.lineTo( x, y );
  21167. },
  21168. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21169. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21170. },
  21171. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21172. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21173. },
  21174. splineThru: function ( pts ) {
  21175. this.currentPath.splineThru( pts );
  21176. },
  21177. toShapes: function ( isCCW, noHoles ) {
  21178. function toShapesNoHoles( inSubpaths ) {
  21179. var shapes = [];
  21180. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21181. var tmpPath = inSubpaths[ i ];
  21182. var tmpShape = new Shape();
  21183. tmpShape.curves = tmpPath.curves;
  21184. shapes.push( tmpShape );
  21185. }
  21186. return shapes;
  21187. }
  21188. function isPointInsidePolygon( inPt, inPolygon ) {
  21189. var polyLen = inPolygon.length;
  21190. // inPt on polygon contour => immediate success or
  21191. // toggling of inside/outside at every single! intersection point of an edge
  21192. // with the horizontal line through inPt, left of inPt
  21193. // not counting lowerY endpoints of edges and whole edges on that line
  21194. var inside = false;
  21195. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21196. var edgeLowPt = inPolygon[ p ];
  21197. var edgeHighPt = inPolygon[ q ];
  21198. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21199. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21200. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21201. // not parallel
  21202. if ( edgeDy < 0 ) {
  21203. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21204. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21205. }
  21206. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21207. if ( inPt.y === edgeLowPt.y ) {
  21208. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21209. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21210. } else {
  21211. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21212. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21213. if ( perpEdge < 0 ) continue;
  21214. inside = ! inside; // true intersection left of inPt
  21215. }
  21216. } else {
  21217. // parallel or collinear
  21218. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21219. // edge lies on the same horizontal line as inPt
  21220. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21221. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21222. // continue;
  21223. }
  21224. }
  21225. return inside;
  21226. }
  21227. var isClockWise = ShapeUtils.isClockWise;
  21228. var subPaths = this.subPaths;
  21229. if ( subPaths.length === 0 ) return [];
  21230. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21231. var solid, tmpPath, tmpShape, shapes = [];
  21232. if ( subPaths.length === 1 ) {
  21233. tmpPath = subPaths[ 0 ];
  21234. tmpShape = new Shape();
  21235. tmpShape.curves = tmpPath.curves;
  21236. shapes.push( tmpShape );
  21237. return shapes;
  21238. }
  21239. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21240. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21241. // console.log("Holes first", holesFirst);
  21242. var betterShapeHoles = [];
  21243. var newShapes = [];
  21244. var newShapeHoles = [];
  21245. var mainIdx = 0;
  21246. var tmpPoints;
  21247. newShapes[ mainIdx ] = undefined;
  21248. newShapeHoles[ mainIdx ] = [];
  21249. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21250. tmpPath = subPaths[ i ];
  21251. tmpPoints = tmpPath.getPoints();
  21252. solid = isClockWise( tmpPoints );
  21253. solid = isCCW ? ! solid : solid;
  21254. if ( solid ) {
  21255. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21256. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21257. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21258. if ( holesFirst ) mainIdx ++;
  21259. newShapeHoles[ mainIdx ] = [];
  21260. //console.log('cw', i);
  21261. } else {
  21262. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21263. //console.log('ccw', i);
  21264. }
  21265. }
  21266. // only Holes? -> probably all Shapes with wrong orientation
  21267. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21268. if ( newShapes.length > 1 ) {
  21269. var ambiguous = false;
  21270. var toChange = [];
  21271. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21272. betterShapeHoles[ sIdx ] = [];
  21273. }
  21274. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21275. var sho = newShapeHoles[ sIdx ];
  21276. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21277. var ho = sho[ hIdx ];
  21278. var hole_unassigned = true;
  21279. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21280. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21281. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21282. if ( hole_unassigned ) {
  21283. hole_unassigned = false;
  21284. betterShapeHoles[ s2Idx ].push( ho );
  21285. } else {
  21286. ambiguous = true;
  21287. }
  21288. }
  21289. }
  21290. if ( hole_unassigned ) {
  21291. betterShapeHoles[ sIdx ].push( ho );
  21292. }
  21293. }
  21294. }
  21295. // console.log("ambiguous: ", ambiguous);
  21296. if ( toChange.length > 0 ) {
  21297. // console.log("to change: ", toChange);
  21298. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21299. }
  21300. }
  21301. var tmpHoles;
  21302. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21303. tmpShape = newShapes[ i ].s;
  21304. shapes.push( tmpShape );
  21305. tmpHoles = newShapeHoles[ i ];
  21306. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21307. tmpShape.holes.push( tmpHoles[ j ].h );
  21308. }
  21309. }
  21310. //console.log("shape", shapes);
  21311. return shapes;
  21312. }
  21313. } );
  21314. /**
  21315. * @author zz85 / http://www.lab4games.net/zz85/blog
  21316. * @author mrdoob / http://mrdoob.com/
  21317. */
  21318. function Font( data ) {
  21319. this.data = data;
  21320. }
  21321. Object.assign( Font.prototype, {
  21322. isFont: true,
  21323. generateShapes: function ( text, size, divisions ) {
  21324. function createPaths( text ) {
  21325. var chars = String( text ).split( '' );
  21326. var scale = size / data.resolution;
  21327. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21328. var offsetX = 0, offsetY = 0;
  21329. var paths = [];
  21330. for ( var i = 0; i < chars.length; i ++ ) {
  21331. var char = chars[ i ];
  21332. if ( char === '\n' ) {
  21333. offsetX = 0;
  21334. offsetY -= line_height;
  21335. } else {
  21336. var ret = createPath( char, scale, offsetX, offsetY );
  21337. offsetX += ret.offsetX;
  21338. paths.push( ret.path );
  21339. }
  21340. }
  21341. return paths;
  21342. }
  21343. function createPath( c, scale, offsetX, offsetY ) {
  21344. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21345. if ( ! glyph ) return;
  21346. var path = new ShapePath();
  21347. var pts = [];
  21348. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21349. if ( glyph.o ) {
  21350. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21351. for ( var i = 0, l = outline.length; i < l; ) {
  21352. var action = outline[ i ++ ];
  21353. switch ( action ) {
  21354. case 'm': // moveTo
  21355. x = outline[ i ++ ] * scale + offsetX;
  21356. y = outline[ i ++ ] * scale + offsetY;
  21357. path.moveTo( x, y );
  21358. break;
  21359. case 'l': // lineTo
  21360. x = outline[ i ++ ] * scale + offsetX;
  21361. y = outline[ i ++ ] * scale + offsetY;
  21362. path.lineTo( x, y );
  21363. break;
  21364. case 'q': // quadraticCurveTo
  21365. cpx = outline[ i ++ ] * scale + offsetX;
  21366. cpy = outline[ i ++ ] * scale + offsetY;
  21367. cpx1 = outline[ i ++ ] * scale + offsetX;
  21368. cpy1 = outline[ i ++ ] * scale + offsetY;
  21369. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21370. laste = pts[ pts.length - 1 ];
  21371. if ( laste ) {
  21372. cpx0 = laste.x;
  21373. cpy0 = laste.y;
  21374. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21375. var t = i2 / divisions;
  21376. QuadraticBezier( t, cpx0, cpx1, cpx );
  21377. QuadraticBezier( t, cpy0, cpy1, cpy );
  21378. }
  21379. }
  21380. break;
  21381. case 'b': // bezierCurveTo
  21382. cpx = outline[ i ++ ] * scale + offsetX;
  21383. cpy = outline[ i ++ ] * scale + offsetY;
  21384. cpx1 = outline[ i ++ ] * scale + offsetX;
  21385. cpy1 = outline[ i ++ ] * scale + offsetY;
  21386. cpx2 = outline[ i ++ ] * scale + offsetX;
  21387. cpy2 = outline[ i ++ ] * scale + offsetY;
  21388. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21389. laste = pts[ pts.length - 1 ];
  21390. if ( laste ) {
  21391. cpx0 = laste.x;
  21392. cpy0 = laste.y;
  21393. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21394. var t = i2 / divisions;
  21395. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21396. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21397. }
  21398. }
  21399. break;
  21400. }
  21401. }
  21402. }
  21403. return { offsetX: glyph.ha * scale, path: path };
  21404. }
  21405. //
  21406. if ( size === undefined ) size = 100;
  21407. if ( divisions === undefined ) divisions = 4;
  21408. var data = this.data;
  21409. var paths = createPaths( text );
  21410. var shapes = [];
  21411. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21412. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21413. }
  21414. return shapes;
  21415. }
  21416. } );
  21417. /**
  21418. * @author mrdoob / http://mrdoob.com/
  21419. */
  21420. function FontLoader( manager ) {
  21421. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21422. }
  21423. Object.assign( FontLoader.prototype, {
  21424. load: function ( url, onLoad, onProgress, onError ) {
  21425. var scope = this;
  21426. var loader = new FileLoader( this.manager );
  21427. loader.load( url, function ( text ) {
  21428. var json;
  21429. try {
  21430. json = JSON.parse( text );
  21431. } catch ( e ) {
  21432. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21433. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21434. }
  21435. var font = scope.parse( json );
  21436. if ( onLoad ) onLoad( font );
  21437. }, onProgress, onError );
  21438. },
  21439. parse: function ( json ) {
  21440. return new Font( json );
  21441. }
  21442. } );
  21443. var context;
  21444. var AudioContext = {
  21445. getContext: function () {
  21446. if ( context === undefined ) {
  21447. context = new ( window.AudioContext || window.webkitAudioContext )();
  21448. }
  21449. return context;
  21450. },
  21451. setContext: function ( value ) {
  21452. context = value;
  21453. }
  21454. };
  21455. /**
  21456. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21457. */
  21458. function AudioLoader( manager ) {
  21459. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21460. }
  21461. Object.assign( AudioLoader.prototype, {
  21462. load: function ( url, onLoad, onProgress, onError ) {
  21463. var loader = new FileLoader( this.manager );
  21464. loader.setResponseType( 'arraybuffer' );
  21465. loader.load( url, function ( buffer ) {
  21466. var context = AudioContext.getContext();
  21467. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21468. onLoad( audioBuffer );
  21469. } );
  21470. }, onProgress, onError );
  21471. }
  21472. } );
  21473. /**
  21474. * @author mrdoob / http://mrdoob.com/
  21475. */
  21476. function StereoCamera() {
  21477. this.type = 'StereoCamera';
  21478. this.aspect = 1;
  21479. this.eyeSep = 0.064;
  21480. this.cameraL = new PerspectiveCamera();
  21481. this.cameraL.layers.enable( 1 );
  21482. this.cameraL.matrixAutoUpdate = false;
  21483. this.cameraR = new PerspectiveCamera();
  21484. this.cameraR.layers.enable( 2 );
  21485. this.cameraR.matrixAutoUpdate = false;
  21486. }
  21487. Object.assign( StereoCamera.prototype, {
  21488. update: ( function () {
  21489. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21490. var eyeRight = new Matrix4();
  21491. var eyeLeft = new Matrix4();
  21492. return function update( camera ) {
  21493. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21494. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21495. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21496. if ( needsUpdate ) {
  21497. instance = this;
  21498. focus = camera.focus;
  21499. fov = camera.fov;
  21500. aspect = camera.aspect * this.aspect;
  21501. near = camera.near;
  21502. far = camera.far;
  21503. zoom = camera.zoom;
  21504. // Off-axis stereoscopic effect based on
  21505. // http://paulbourke.net/stereographics/stereorender/
  21506. var projectionMatrix = camera.projectionMatrix.clone();
  21507. eyeSep = this.eyeSep / 2;
  21508. var eyeSepOnProjection = eyeSep * near / focus;
  21509. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21510. var xmin, xmax;
  21511. // translate xOffset
  21512. eyeLeft.elements[ 12 ] = - eyeSep;
  21513. eyeRight.elements[ 12 ] = eyeSep;
  21514. // for left eye
  21515. xmin = - ymax * aspect + eyeSepOnProjection;
  21516. xmax = ymax * aspect + eyeSepOnProjection;
  21517. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21518. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21519. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21520. // for right eye
  21521. xmin = - ymax * aspect - eyeSepOnProjection;
  21522. xmax = ymax * aspect - eyeSepOnProjection;
  21523. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21524. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21525. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21526. }
  21527. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21528. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21529. };
  21530. } )()
  21531. } );
  21532. /**
  21533. * Camera for rendering cube maps
  21534. * - renders scene into axis-aligned cube
  21535. *
  21536. * @author alteredq / http://alteredqualia.com/
  21537. */
  21538. function CubeCamera( near, far, cubeResolution ) {
  21539. Object3D.call( this );
  21540. this.type = 'CubeCamera';
  21541. var fov = 90, aspect = 1;
  21542. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21543. cameraPX.up.set( 0, - 1, 0 );
  21544. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21545. this.add( cameraPX );
  21546. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21547. cameraNX.up.set( 0, - 1, 0 );
  21548. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21549. this.add( cameraNX );
  21550. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21551. cameraPY.up.set( 0, 0, 1 );
  21552. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21553. this.add( cameraPY );
  21554. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21555. cameraNY.up.set( 0, 0, - 1 );
  21556. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21557. this.add( cameraNY );
  21558. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21559. cameraPZ.up.set( 0, - 1, 0 );
  21560. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21561. this.add( cameraPZ );
  21562. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21563. cameraNZ.up.set( 0, - 1, 0 );
  21564. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21565. this.add( cameraNZ );
  21566. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21567. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21568. this.renderTarget.texture.name = "CubeCamera";
  21569. this.updateCubeMap = function ( renderer, scene ) {
  21570. if ( this.parent === null ) this.updateMatrixWorld();
  21571. var renderTarget = this.renderTarget;
  21572. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21573. renderTarget.texture.generateMipmaps = false;
  21574. renderTarget.activeCubeFace = 0;
  21575. renderer.render( scene, cameraPX, renderTarget );
  21576. renderTarget.activeCubeFace = 1;
  21577. renderer.render( scene, cameraNX, renderTarget );
  21578. renderTarget.activeCubeFace = 2;
  21579. renderer.render( scene, cameraPY, renderTarget );
  21580. renderTarget.activeCubeFace = 3;
  21581. renderer.render( scene, cameraNY, renderTarget );
  21582. renderTarget.activeCubeFace = 4;
  21583. renderer.render( scene, cameraPZ, renderTarget );
  21584. renderTarget.texture.generateMipmaps = generateMipmaps;
  21585. renderTarget.activeCubeFace = 5;
  21586. renderer.render( scene, cameraNZ, renderTarget );
  21587. renderer.setRenderTarget( null );
  21588. };
  21589. }
  21590. CubeCamera.prototype = Object.create( Object3D.prototype );
  21591. CubeCamera.prototype.constructor = CubeCamera;
  21592. /**
  21593. * @author mrdoob / http://mrdoob.com/
  21594. */
  21595. function ArrayCamera( array ) {
  21596. PerspectiveCamera.call( this );
  21597. this.enabled = false;
  21598. this.cameras = array || [];
  21599. }
  21600. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  21601. constructor: ArrayCamera,
  21602. isArrayCamera: true
  21603. } );
  21604. /**
  21605. * @author mrdoob / http://mrdoob.com/
  21606. */
  21607. function AudioListener() {
  21608. Object3D.call( this );
  21609. this.type = 'AudioListener';
  21610. this.context = AudioContext.getContext();
  21611. this.gain = this.context.createGain();
  21612. this.gain.connect( this.context.destination );
  21613. this.filter = null;
  21614. }
  21615. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21616. constructor: AudioListener,
  21617. getInput: function () {
  21618. return this.gain;
  21619. },
  21620. removeFilter: function ( ) {
  21621. if ( this.filter !== null ) {
  21622. this.gain.disconnect( this.filter );
  21623. this.filter.disconnect( this.context.destination );
  21624. this.gain.connect( this.context.destination );
  21625. this.filter = null;
  21626. }
  21627. },
  21628. getFilter: function () {
  21629. return this.filter;
  21630. },
  21631. setFilter: function ( value ) {
  21632. if ( this.filter !== null ) {
  21633. this.gain.disconnect( this.filter );
  21634. this.filter.disconnect( this.context.destination );
  21635. } else {
  21636. this.gain.disconnect( this.context.destination );
  21637. }
  21638. this.filter = value;
  21639. this.gain.connect( this.filter );
  21640. this.filter.connect( this.context.destination );
  21641. },
  21642. getMasterVolume: function () {
  21643. return this.gain.gain.value;
  21644. },
  21645. setMasterVolume: function ( value ) {
  21646. this.gain.gain.value = value;
  21647. },
  21648. updateMatrixWorld: ( function () {
  21649. var position = new Vector3();
  21650. var quaternion = new Quaternion();
  21651. var scale = new Vector3();
  21652. var orientation = new Vector3();
  21653. return function updateMatrixWorld( force ) {
  21654. Object3D.prototype.updateMatrixWorld.call( this, force );
  21655. var listener = this.context.listener;
  21656. var up = this.up;
  21657. this.matrixWorld.decompose( position, quaternion, scale );
  21658. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21659. if ( listener.positionX ) {
  21660. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21661. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21662. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21663. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21664. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21665. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21666. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21667. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21668. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21669. } else {
  21670. listener.setPosition( position.x, position.y, position.z );
  21671. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21672. }
  21673. };
  21674. } )()
  21675. } );
  21676. /**
  21677. * @author mrdoob / http://mrdoob.com/
  21678. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21679. */
  21680. function Audio( listener ) {
  21681. Object3D.call( this );
  21682. this.type = 'Audio';
  21683. this.context = listener.context;
  21684. this.gain = this.context.createGain();
  21685. this.gain.connect( listener.getInput() );
  21686. this.autoplay = false;
  21687. this.buffer = null;
  21688. this.loop = false;
  21689. this.startTime = 0;
  21690. this.playbackRate = 1;
  21691. this.isPlaying = false;
  21692. this.hasPlaybackControl = true;
  21693. this.sourceType = 'empty';
  21694. this.filters = [];
  21695. }
  21696. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21697. constructor: Audio,
  21698. getOutput: function () {
  21699. return this.gain;
  21700. },
  21701. setNodeSource: function ( audioNode ) {
  21702. this.hasPlaybackControl = false;
  21703. this.sourceType = 'audioNode';
  21704. this.source = audioNode;
  21705. this.connect();
  21706. return this;
  21707. },
  21708. setBuffer: function ( audioBuffer ) {
  21709. this.buffer = audioBuffer;
  21710. this.sourceType = 'buffer';
  21711. if ( this.autoplay ) this.play();
  21712. return this;
  21713. },
  21714. play: function () {
  21715. if ( this.isPlaying === true ) {
  21716. console.warn( 'THREE.Audio: Audio is already playing.' );
  21717. return;
  21718. }
  21719. if ( this.hasPlaybackControl === false ) {
  21720. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21721. return;
  21722. }
  21723. var source = this.context.createBufferSource();
  21724. source.buffer = this.buffer;
  21725. source.loop = this.loop;
  21726. source.onended = this.onEnded.bind( this );
  21727. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21728. source.start( 0, this.startTime );
  21729. this.isPlaying = true;
  21730. this.source = source;
  21731. return this.connect();
  21732. },
  21733. pause: function () {
  21734. if ( this.hasPlaybackControl === false ) {
  21735. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21736. return;
  21737. }
  21738. this.source.stop();
  21739. this.startTime = this.context.currentTime;
  21740. this.isPlaying = false;
  21741. return this;
  21742. },
  21743. stop: function () {
  21744. if ( this.hasPlaybackControl === false ) {
  21745. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21746. return;
  21747. }
  21748. this.source.stop();
  21749. this.startTime = 0;
  21750. this.isPlaying = false;
  21751. return this;
  21752. },
  21753. connect: function () {
  21754. if ( this.filters.length > 0 ) {
  21755. this.source.connect( this.filters[ 0 ] );
  21756. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21757. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21758. }
  21759. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21760. } else {
  21761. this.source.connect( this.getOutput() );
  21762. }
  21763. return this;
  21764. },
  21765. disconnect: function () {
  21766. if ( this.filters.length > 0 ) {
  21767. this.source.disconnect( this.filters[ 0 ] );
  21768. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21769. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21770. }
  21771. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21772. } else {
  21773. this.source.disconnect( this.getOutput() );
  21774. }
  21775. return this;
  21776. },
  21777. getFilters: function () {
  21778. return this.filters;
  21779. },
  21780. setFilters: function ( value ) {
  21781. if ( ! value ) value = [];
  21782. if ( this.isPlaying === true ) {
  21783. this.disconnect();
  21784. this.filters = value;
  21785. this.connect();
  21786. } else {
  21787. this.filters = value;
  21788. }
  21789. return this;
  21790. },
  21791. getFilter: function () {
  21792. return this.getFilters()[ 0 ];
  21793. },
  21794. setFilter: function ( filter ) {
  21795. return this.setFilters( filter ? [ filter ] : [] );
  21796. },
  21797. setPlaybackRate: function ( value ) {
  21798. if ( this.hasPlaybackControl === false ) {
  21799. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21800. return;
  21801. }
  21802. this.playbackRate = value;
  21803. if ( this.isPlaying === true ) {
  21804. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21805. }
  21806. return this;
  21807. },
  21808. getPlaybackRate: function () {
  21809. return this.playbackRate;
  21810. },
  21811. onEnded: function () {
  21812. this.isPlaying = false;
  21813. },
  21814. getLoop: function () {
  21815. if ( this.hasPlaybackControl === false ) {
  21816. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21817. return false;
  21818. }
  21819. return this.loop;
  21820. },
  21821. setLoop: function ( value ) {
  21822. if ( this.hasPlaybackControl === false ) {
  21823. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21824. return;
  21825. }
  21826. this.loop = value;
  21827. if ( this.isPlaying === true ) {
  21828. this.source.loop = this.loop;
  21829. }
  21830. return this;
  21831. },
  21832. getVolume: function () {
  21833. return this.gain.gain.value;
  21834. },
  21835. setVolume: function ( value ) {
  21836. this.gain.gain.value = value;
  21837. return this;
  21838. }
  21839. } );
  21840. /**
  21841. * @author mrdoob / http://mrdoob.com/
  21842. */
  21843. function PositionalAudio( listener ) {
  21844. Audio.call( this, listener );
  21845. this.panner = this.context.createPanner();
  21846. this.panner.connect( this.gain );
  21847. }
  21848. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21849. constructor: PositionalAudio,
  21850. getOutput: function () {
  21851. return this.panner;
  21852. },
  21853. getRefDistance: function () {
  21854. return this.panner.refDistance;
  21855. },
  21856. setRefDistance: function ( value ) {
  21857. this.panner.refDistance = value;
  21858. },
  21859. getRolloffFactor: function () {
  21860. return this.panner.rolloffFactor;
  21861. },
  21862. setRolloffFactor: function ( value ) {
  21863. this.panner.rolloffFactor = value;
  21864. },
  21865. getDistanceModel: function () {
  21866. return this.panner.distanceModel;
  21867. },
  21868. setDistanceModel: function ( value ) {
  21869. this.panner.distanceModel = value;
  21870. },
  21871. getMaxDistance: function () {
  21872. return this.panner.maxDistance;
  21873. },
  21874. setMaxDistance: function ( value ) {
  21875. this.panner.maxDistance = value;
  21876. },
  21877. updateMatrixWorld: ( function () {
  21878. var position = new Vector3();
  21879. return function updateMatrixWorld( force ) {
  21880. Object3D.prototype.updateMatrixWorld.call( this, force );
  21881. position.setFromMatrixPosition( this.matrixWorld );
  21882. this.panner.setPosition( position.x, position.y, position.z );
  21883. };
  21884. } )()
  21885. } );
  21886. /**
  21887. * @author mrdoob / http://mrdoob.com/
  21888. */
  21889. function AudioAnalyser( audio, fftSize ) {
  21890. this.analyser = audio.context.createAnalyser();
  21891. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21892. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21893. audio.getOutput().connect( this.analyser );
  21894. }
  21895. Object.assign( AudioAnalyser.prototype, {
  21896. getFrequencyData: function () {
  21897. this.analyser.getByteFrequencyData( this.data );
  21898. return this.data;
  21899. },
  21900. getAverageFrequency: function () {
  21901. var value = 0, data = this.getFrequencyData();
  21902. for ( var i = 0; i < data.length; i ++ ) {
  21903. value += data[ i ];
  21904. }
  21905. return value / data.length;
  21906. }
  21907. } );
  21908. /**
  21909. *
  21910. * Buffered scene graph property that allows weighted accumulation.
  21911. *
  21912. *
  21913. * @author Ben Houston / http://clara.io/
  21914. * @author David Sarno / http://lighthaus.us/
  21915. * @author tschw
  21916. */
  21917. function PropertyMixer( binding, typeName, valueSize ) {
  21918. this.binding = binding;
  21919. this.valueSize = valueSize;
  21920. var bufferType = Float64Array,
  21921. mixFunction;
  21922. switch ( typeName ) {
  21923. case 'quaternion':
  21924. mixFunction = this._slerp;
  21925. break;
  21926. case 'string':
  21927. case 'bool':
  21928. bufferType = Array;
  21929. mixFunction = this._select;
  21930. break;
  21931. default:
  21932. mixFunction = this._lerp;
  21933. }
  21934. this.buffer = new bufferType( valueSize * 4 );
  21935. // layout: [ incoming | accu0 | accu1 | orig ]
  21936. //
  21937. // interpolators can use .buffer as their .result
  21938. // the data then goes to 'incoming'
  21939. //
  21940. // 'accu0' and 'accu1' are used frame-interleaved for
  21941. // the cumulative result and are compared to detect
  21942. // changes
  21943. //
  21944. // 'orig' stores the original state of the property
  21945. this._mixBufferRegion = mixFunction;
  21946. this.cumulativeWeight = 0;
  21947. this.useCount = 0;
  21948. this.referenceCount = 0;
  21949. }
  21950. Object.assign( PropertyMixer.prototype, {
  21951. // accumulate data in the 'incoming' region into 'accu<i>'
  21952. accumulate: function ( accuIndex, weight ) {
  21953. // note: happily accumulating nothing when weight = 0, the caller knows
  21954. // the weight and shouldn't have made the call in the first place
  21955. var buffer = this.buffer,
  21956. stride = this.valueSize,
  21957. offset = accuIndex * stride + stride,
  21958. currentWeight = this.cumulativeWeight;
  21959. if ( currentWeight === 0 ) {
  21960. // accuN := incoming * weight
  21961. for ( var i = 0; i !== stride; ++ i ) {
  21962. buffer[ offset + i ] = buffer[ i ];
  21963. }
  21964. currentWeight = weight;
  21965. } else {
  21966. // accuN := accuN + incoming * weight
  21967. currentWeight += weight;
  21968. var mix = weight / currentWeight;
  21969. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21970. }
  21971. this.cumulativeWeight = currentWeight;
  21972. },
  21973. // apply the state of 'accu<i>' to the binding when accus differ
  21974. apply: function ( accuIndex ) {
  21975. var stride = this.valueSize,
  21976. buffer = this.buffer,
  21977. offset = accuIndex * stride + stride,
  21978. weight = this.cumulativeWeight,
  21979. binding = this.binding;
  21980. this.cumulativeWeight = 0;
  21981. if ( weight < 1 ) {
  21982. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21983. var originalValueOffset = stride * 3;
  21984. this._mixBufferRegion(
  21985. buffer, offset, originalValueOffset, 1 - weight, stride );
  21986. }
  21987. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21988. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21989. // value has changed -> update scene graph
  21990. binding.setValue( buffer, offset );
  21991. break;
  21992. }
  21993. }
  21994. },
  21995. // remember the state of the bound property and copy it to both accus
  21996. saveOriginalState: function () {
  21997. var binding = this.binding;
  21998. var buffer = this.buffer,
  21999. stride = this.valueSize,
  22000. originalValueOffset = stride * 3;
  22001. binding.getValue( buffer, originalValueOffset );
  22002. // accu[0..1] := orig -- initially detect changes against the original
  22003. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22004. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22005. }
  22006. this.cumulativeWeight = 0;
  22007. },
  22008. // apply the state previously taken via 'saveOriginalState' to the binding
  22009. restoreOriginalState: function () {
  22010. var originalValueOffset = this.valueSize * 3;
  22011. this.binding.setValue( this.buffer, originalValueOffset );
  22012. },
  22013. // mix functions
  22014. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22015. if ( t >= 0.5 ) {
  22016. for ( var i = 0; i !== stride; ++ i ) {
  22017. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22018. }
  22019. }
  22020. },
  22021. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22022. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22023. },
  22024. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22025. var s = 1 - t;
  22026. for ( var i = 0; i !== stride; ++ i ) {
  22027. var j = dstOffset + i;
  22028. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22029. }
  22030. }
  22031. } );
  22032. /**
  22033. *
  22034. * A reference to a real property in the scene graph.
  22035. *
  22036. *
  22037. * @author Ben Houston / http://clara.io/
  22038. * @author David Sarno / http://lighthaus.us/
  22039. * @author tschw
  22040. */
  22041. function Composite( targetGroup, path, optionalParsedPath ) {
  22042. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22043. this._targetGroup = targetGroup;
  22044. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22045. }
  22046. Object.assign( Composite.prototype, {
  22047. getValue: function ( array, offset ) {
  22048. this.bind(); // bind all binding
  22049. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22050. binding = this._bindings[ firstValidIndex ];
  22051. // and only call .getValue on the first
  22052. if ( binding !== undefined ) binding.getValue( array, offset );
  22053. },
  22054. setValue: function ( array, offset ) {
  22055. var bindings = this._bindings;
  22056. for ( var i = this._targetGroup.nCachedObjects_,
  22057. n = bindings.length; i !== n; ++ i ) {
  22058. bindings[ i ].setValue( array, offset );
  22059. }
  22060. },
  22061. bind: function () {
  22062. var bindings = this._bindings;
  22063. for ( var i = this._targetGroup.nCachedObjects_,
  22064. n = bindings.length; i !== n; ++ i ) {
  22065. bindings[ i ].bind();
  22066. }
  22067. },
  22068. unbind: function () {
  22069. var bindings = this._bindings;
  22070. for ( var i = this._targetGroup.nCachedObjects_,
  22071. n = bindings.length; i !== n; ++ i ) {
  22072. bindings[ i ].unbind();
  22073. }
  22074. }
  22075. } );
  22076. function PropertyBinding( rootNode, path, parsedPath ) {
  22077. this.path = path;
  22078. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22079. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22080. this.rootNode = rootNode;
  22081. }
  22082. Object.assign( PropertyBinding, {
  22083. Composite: Composite,
  22084. create: function ( root, path, parsedPath ) {
  22085. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22086. return new PropertyBinding( root, path, parsedPath );
  22087. } else {
  22088. return new PropertyBinding.Composite( root, path, parsedPath );
  22089. }
  22090. },
  22091. parseTrackName: function () {
  22092. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22093. // be matched to parse the rest of the track name.
  22094. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22095. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22096. var nodeRe = /([\w-\.]+)?/;
  22097. // Object on target node, and accessor. Name may contain only word
  22098. // characters. Accessor may contain any character except closing bracket.
  22099. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22100. // Property and accessor. May contain only word characters. Accessor may
  22101. // contain any non-bracket characters.
  22102. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22103. var trackRe = new RegExp(''
  22104. + '^'
  22105. + directoryRe.source
  22106. + nodeRe.source
  22107. + objectRe.source
  22108. + propertyRe.source
  22109. + '$'
  22110. );
  22111. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22112. return function ( trackName ) {
  22113. var matches = trackRe.exec( trackName );
  22114. if ( ! matches ) {
  22115. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22116. }
  22117. var results = {
  22118. // directoryName: matches[ 1 ], // (tschw) currently unused
  22119. nodeName: matches[ 2 ],
  22120. objectName: matches[ 3 ],
  22121. objectIndex: matches[ 4 ],
  22122. propertyName: matches[ 5 ], // required
  22123. propertyIndex: matches[ 6 ]
  22124. };
  22125. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22126. if ( lastDot !== undefined && lastDot !== -1 ) {
  22127. var objectName = results.nodeName.substring( lastDot + 1 );
  22128. // Object names must be checked against a whitelist. Otherwise, there
  22129. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22130. // 'bar' could be the objectName, or part of a nodeName (which can
  22131. // include '.' characters).
  22132. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22133. results.nodeName = results.nodeName.substring( 0, lastDot );
  22134. results.objectName = objectName;
  22135. }
  22136. }
  22137. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22138. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22139. }
  22140. return results;
  22141. };
  22142. }(),
  22143. findNode: function ( root, nodeName ) {
  22144. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22145. return root;
  22146. }
  22147. // search into skeleton bones.
  22148. if ( root.skeleton ) {
  22149. var searchSkeleton = function ( skeleton ) {
  22150. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22151. var bone = skeleton.bones[ i ];
  22152. if ( bone.name === nodeName ) {
  22153. return bone;
  22154. }
  22155. }
  22156. return null;
  22157. };
  22158. var bone = searchSkeleton( root.skeleton );
  22159. if ( bone ) {
  22160. return bone;
  22161. }
  22162. }
  22163. // search into node subtree.
  22164. if ( root.children ) {
  22165. var searchNodeSubtree = function ( children ) {
  22166. for ( var i = 0; i < children.length; i ++ ) {
  22167. var childNode = children[ i ];
  22168. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22169. return childNode;
  22170. }
  22171. var result = searchNodeSubtree( childNode.children );
  22172. if ( result ) return result;
  22173. }
  22174. return null;
  22175. };
  22176. var subTreeNode = searchNodeSubtree( root.children );
  22177. if ( subTreeNode ) {
  22178. return subTreeNode;
  22179. }
  22180. }
  22181. return null;
  22182. }
  22183. } );
  22184. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22185. // these are used to "bind" a nonexistent property
  22186. _getValue_unavailable: function () {},
  22187. _setValue_unavailable: function () {},
  22188. BindingType: {
  22189. Direct: 0,
  22190. EntireArray: 1,
  22191. ArrayElement: 2,
  22192. HasFromToArray: 3
  22193. },
  22194. Versioning: {
  22195. None: 0,
  22196. NeedsUpdate: 1,
  22197. MatrixWorldNeedsUpdate: 2
  22198. },
  22199. GetterByBindingType: [
  22200. function getValue_direct( buffer, offset ) {
  22201. buffer[ offset ] = this.node[ this.propertyName ];
  22202. },
  22203. function getValue_array( buffer, offset ) {
  22204. var source = this.resolvedProperty;
  22205. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22206. buffer[ offset ++ ] = source[ i ];
  22207. }
  22208. },
  22209. function getValue_arrayElement( buffer, offset ) {
  22210. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22211. },
  22212. function getValue_toArray( buffer, offset ) {
  22213. this.resolvedProperty.toArray( buffer, offset );
  22214. }
  22215. ],
  22216. SetterByBindingTypeAndVersioning: [
  22217. [
  22218. // Direct
  22219. function setValue_direct( buffer, offset ) {
  22220. this.node[ this.propertyName ] = buffer[ offset ];
  22221. },
  22222. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22223. this.node[ this.propertyName ] = buffer[ offset ];
  22224. this.targetObject.needsUpdate = true;
  22225. },
  22226. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22227. this.node[ this.propertyName ] = buffer[ offset ];
  22228. this.targetObject.matrixWorldNeedsUpdate = true;
  22229. }
  22230. ], [
  22231. // EntireArray
  22232. function setValue_array( buffer, offset ) {
  22233. var dest = this.resolvedProperty;
  22234. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22235. dest[ i ] = buffer[ offset ++ ];
  22236. }
  22237. },
  22238. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22239. var dest = this.resolvedProperty;
  22240. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22241. dest[ i ] = buffer[ offset ++ ];
  22242. }
  22243. this.targetObject.needsUpdate = true;
  22244. },
  22245. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22246. var dest = this.resolvedProperty;
  22247. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22248. dest[ i ] = buffer[ offset ++ ];
  22249. }
  22250. this.targetObject.matrixWorldNeedsUpdate = true;
  22251. }
  22252. ], [
  22253. // ArrayElement
  22254. function setValue_arrayElement( buffer, offset ) {
  22255. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22256. },
  22257. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22258. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22259. this.targetObject.needsUpdate = true;
  22260. },
  22261. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22262. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22263. this.targetObject.matrixWorldNeedsUpdate = true;
  22264. }
  22265. ], [
  22266. // HasToFromArray
  22267. function setValue_fromArray( buffer, offset ) {
  22268. this.resolvedProperty.fromArray( buffer, offset );
  22269. },
  22270. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22271. this.resolvedProperty.fromArray( buffer, offset );
  22272. this.targetObject.needsUpdate = true;
  22273. },
  22274. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22275. this.resolvedProperty.fromArray( buffer, offset );
  22276. this.targetObject.matrixWorldNeedsUpdate = true;
  22277. }
  22278. ]
  22279. ],
  22280. getValue: function getValue_unbound( targetArray, offset ) {
  22281. this.bind();
  22282. this.getValue( targetArray, offset );
  22283. // Note: This class uses a State pattern on a per-method basis:
  22284. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22285. // prototype version of these methods with one that represents
  22286. // the bound state. When the property is not found, the methods
  22287. // become no-ops.
  22288. },
  22289. setValue: function getValue_unbound( sourceArray, offset ) {
  22290. this.bind();
  22291. this.setValue( sourceArray, offset );
  22292. },
  22293. // create getter / setter pair for a property in the scene graph
  22294. bind: function () {
  22295. var targetObject = this.node,
  22296. parsedPath = this.parsedPath,
  22297. objectName = parsedPath.objectName,
  22298. propertyName = parsedPath.propertyName,
  22299. propertyIndex = parsedPath.propertyIndex;
  22300. if ( ! targetObject ) {
  22301. targetObject = PropertyBinding.findNode(
  22302. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22303. this.node = targetObject;
  22304. }
  22305. // set fail state so we can just 'return' on error
  22306. this.getValue = this._getValue_unavailable;
  22307. this.setValue = this._setValue_unavailable;
  22308. // ensure there is a value node
  22309. if ( ! targetObject ) {
  22310. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  22311. return;
  22312. }
  22313. if ( objectName ) {
  22314. var objectIndex = parsedPath.objectIndex;
  22315. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22316. switch ( objectName ) {
  22317. case 'materials':
  22318. if ( ! targetObject.material ) {
  22319. console.error( ' can not bind to material as node does not have a material', this );
  22320. return;
  22321. }
  22322. if ( ! targetObject.material.materials ) {
  22323. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  22324. return;
  22325. }
  22326. targetObject = targetObject.material.materials;
  22327. break;
  22328. case 'bones':
  22329. if ( ! targetObject.skeleton ) {
  22330. console.error( ' can not bind to bones as node does not have a skeleton', this );
  22331. return;
  22332. }
  22333. // potential future optimization: skip this if propertyIndex is already an integer
  22334. // and convert the integer string to a true integer.
  22335. targetObject = targetObject.skeleton.bones;
  22336. // support resolving morphTarget names into indices.
  22337. for ( var i = 0; i < targetObject.length; i ++ ) {
  22338. if ( targetObject[ i ].name === objectIndex ) {
  22339. objectIndex = i;
  22340. break;
  22341. }
  22342. }
  22343. break;
  22344. default:
  22345. if ( targetObject[ objectName ] === undefined ) {
  22346. console.error( ' can not bind to objectName of node, undefined', this );
  22347. return;
  22348. }
  22349. targetObject = targetObject[ objectName ];
  22350. }
  22351. if ( objectIndex !== undefined ) {
  22352. if ( targetObject[ objectIndex ] === undefined ) {
  22353. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  22354. return;
  22355. }
  22356. targetObject = targetObject[ objectIndex ];
  22357. }
  22358. }
  22359. // resolve property
  22360. var nodeProperty = targetObject[ propertyName ];
  22361. if ( nodeProperty === undefined ) {
  22362. var nodeName = parsedPath.nodeName;
  22363. console.error( " trying to update property for track: " + nodeName +
  22364. '.' + propertyName + " but it wasn't found.", targetObject );
  22365. return;
  22366. }
  22367. // determine versioning scheme
  22368. var versioning = this.Versioning.None;
  22369. if ( targetObject.needsUpdate !== undefined ) { // material
  22370. versioning = this.Versioning.NeedsUpdate;
  22371. this.targetObject = targetObject;
  22372. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22373. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22374. this.targetObject = targetObject;
  22375. }
  22376. // determine how the property gets bound
  22377. var bindingType = this.BindingType.Direct;
  22378. if ( propertyIndex !== undefined ) {
  22379. // access a sub element of the property array (only primitives are supported right now)
  22380. if ( propertyName === "morphTargetInfluences" ) {
  22381. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22382. // support resolving morphTarget names into indices.
  22383. if ( ! targetObject.geometry ) {
  22384. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  22385. return;
  22386. }
  22387. if ( ! targetObject.geometry.morphTargets ) {
  22388. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  22389. return;
  22390. }
  22391. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22392. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22393. propertyIndex = i;
  22394. break;
  22395. }
  22396. }
  22397. }
  22398. bindingType = this.BindingType.ArrayElement;
  22399. this.resolvedProperty = nodeProperty;
  22400. this.propertyIndex = propertyIndex;
  22401. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22402. // must use copy for Object3D.Euler/Quaternion
  22403. bindingType = this.BindingType.HasFromToArray;
  22404. this.resolvedProperty = nodeProperty;
  22405. } else if ( Array.isArray( nodeProperty ) ) {
  22406. bindingType = this.BindingType.EntireArray;
  22407. this.resolvedProperty = nodeProperty;
  22408. } else {
  22409. this.propertyName = propertyName;
  22410. }
  22411. // select getter / setter
  22412. this.getValue = this.GetterByBindingType[ bindingType ];
  22413. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22414. },
  22415. unbind: function () {
  22416. this.node = null;
  22417. // back to the prototype version of getValue / setValue
  22418. // note: avoiding to mutate the shape of 'this' via 'delete'
  22419. this.getValue = this._getValue_unbound;
  22420. this.setValue = this._setValue_unbound;
  22421. }
  22422. } );
  22423. //!\ DECLARE ALIAS AFTER assign prototype !
  22424. Object.assign( PropertyBinding.prototype, {
  22425. // initial state of these methods that calls 'bind'
  22426. _getValue_unbound: PropertyBinding.prototype.getValue,
  22427. _setValue_unbound: PropertyBinding.prototype.setValue,
  22428. } );
  22429. /**
  22430. *
  22431. * A group of objects that receives a shared animation state.
  22432. *
  22433. * Usage:
  22434. *
  22435. * - Add objects you would otherwise pass as 'root' to the
  22436. * constructor or the .clipAction method of AnimationMixer.
  22437. *
  22438. * - Instead pass this object as 'root'.
  22439. *
  22440. * - You can also add and remove objects later when the mixer
  22441. * is running.
  22442. *
  22443. * Note:
  22444. *
  22445. * Objects of this class appear as one object to the mixer,
  22446. * so cache control of the individual objects must be done
  22447. * on the group.
  22448. *
  22449. * Limitation:
  22450. *
  22451. * - The animated properties must be compatible among the
  22452. * all objects in the group.
  22453. *
  22454. * - A single property can either be controlled through a
  22455. * target group or directly, but not both.
  22456. *
  22457. * @author tschw
  22458. */
  22459. function AnimationObjectGroup( var_args ) {
  22460. this.uuid = _Math.generateUUID();
  22461. // cached objects followed by the active ones
  22462. this._objects = Array.prototype.slice.call( arguments );
  22463. this.nCachedObjects_ = 0; // threshold
  22464. // note: read by PropertyBinding.Composite
  22465. var indices = {};
  22466. this._indicesByUUID = indices; // for bookkeeping
  22467. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22468. indices[ arguments[ i ].uuid ] = i;
  22469. }
  22470. this._paths = []; // inside: string
  22471. this._parsedPaths = []; // inside: { we don't care, here }
  22472. this._bindings = []; // inside: Array< PropertyBinding >
  22473. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22474. var scope = this;
  22475. this.stats = {
  22476. objects: {
  22477. get total() { return scope._objects.length; },
  22478. get inUse() { return this.total - scope.nCachedObjects_; }
  22479. },
  22480. get bindingsPerObject() { return scope._bindings.length; }
  22481. };
  22482. }
  22483. Object.assign( AnimationObjectGroup.prototype, {
  22484. isAnimationObjectGroup: true,
  22485. add: function( var_args ) {
  22486. var objects = this._objects,
  22487. nObjects = objects.length,
  22488. nCachedObjects = this.nCachedObjects_,
  22489. indicesByUUID = this._indicesByUUID,
  22490. paths = this._paths,
  22491. parsedPaths = this._parsedPaths,
  22492. bindings = this._bindings,
  22493. nBindings = bindings.length;
  22494. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22495. var object = arguments[ i ],
  22496. uuid = object.uuid,
  22497. index = indicesByUUID[ uuid ],
  22498. knownObject = undefined;
  22499. if ( index === undefined ) {
  22500. // unknown object -> add it to the ACTIVE region
  22501. index = nObjects ++;
  22502. indicesByUUID[ uuid ] = index;
  22503. objects.push( object );
  22504. // accounting is done, now do the same for all bindings
  22505. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22506. bindings[ j ].push(
  22507. new PropertyBinding(
  22508. object, paths[ j ], parsedPaths[ j ] ) );
  22509. }
  22510. } else if ( index < nCachedObjects ) {
  22511. knownObject = objects[ index ];
  22512. // move existing object to the ACTIVE region
  22513. var firstActiveIndex = -- nCachedObjects,
  22514. lastCachedObject = objects[ firstActiveIndex ];
  22515. indicesByUUID[ lastCachedObject.uuid ] = index;
  22516. objects[ index ] = lastCachedObject;
  22517. indicesByUUID[ uuid ] = firstActiveIndex;
  22518. objects[ firstActiveIndex ] = object;
  22519. // accounting is done, now do the same for all bindings
  22520. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22521. var bindingsForPath = bindings[ j ],
  22522. lastCached = bindingsForPath[ firstActiveIndex ],
  22523. binding = bindingsForPath[ index ];
  22524. bindingsForPath[ index ] = lastCached;
  22525. if ( binding === undefined ) {
  22526. // since we do not bother to create new bindings
  22527. // for objects that are cached, the binding may
  22528. // or may not exist
  22529. binding = new PropertyBinding(
  22530. object, paths[ j ], parsedPaths[ j ] );
  22531. }
  22532. bindingsForPath[ firstActiveIndex ] = binding;
  22533. }
  22534. } else if ( objects[ index ] !== knownObject ) {
  22535. console.error( "Different objects with the same UUID " +
  22536. "detected. Clean the caches or recreate your " +
  22537. "infrastructure when reloading scenes..." );
  22538. } // else the object is already where we want it to be
  22539. } // for arguments
  22540. this.nCachedObjects_ = nCachedObjects;
  22541. },
  22542. remove: function( var_args ) {
  22543. var objects = this._objects,
  22544. nCachedObjects = this.nCachedObjects_,
  22545. indicesByUUID = this._indicesByUUID,
  22546. bindings = this._bindings,
  22547. nBindings = bindings.length;
  22548. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22549. var object = arguments[ i ],
  22550. uuid = object.uuid,
  22551. index = indicesByUUID[ uuid ];
  22552. if ( index !== undefined && index >= nCachedObjects ) {
  22553. // move existing object into the CACHED region
  22554. var lastCachedIndex = nCachedObjects ++,
  22555. firstActiveObject = objects[ lastCachedIndex ];
  22556. indicesByUUID[ firstActiveObject.uuid ] = index;
  22557. objects[ index ] = firstActiveObject;
  22558. indicesByUUID[ uuid ] = lastCachedIndex;
  22559. objects[ lastCachedIndex ] = object;
  22560. // accounting is done, now do the same for all bindings
  22561. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22562. var bindingsForPath = bindings[ j ],
  22563. firstActive = bindingsForPath[ lastCachedIndex ],
  22564. binding = bindingsForPath[ index ];
  22565. bindingsForPath[ index ] = firstActive;
  22566. bindingsForPath[ lastCachedIndex ] = binding;
  22567. }
  22568. }
  22569. } // for arguments
  22570. this.nCachedObjects_ = nCachedObjects;
  22571. },
  22572. // remove & forget
  22573. uncache: function( var_args ) {
  22574. var objects = this._objects,
  22575. nObjects = objects.length,
  22576. nCachedObjects = this.nCachedObjects_,
  22577. indicesByUUID = this._indicesByUUID,
  22578. bindings = this._bindings,
  22579. nBindings = bindings.length;
  22580. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22581. var object = arguments[ i ],
  22582. uuid = object.uuid,
  22583. index = indicesByUUID[ uuid ];
  22584. if ( index !== undefined ) {
  22585. delete indicesByUUID[ uuid ];
  22586. if ( index < nCachedObjects ) {
  22587. // object is cached, shrink the CACHED region
  22588. var firstActiveIndex = -- nCachedObjects,
  22589. lastCachedObject = objects[ firstActiveIndex ],
  22590. lastIndex = -- nObjects,
  22591. lastObject = objects[ lastIndex ];
  22592. // last cached object takes this object's place
  22593. indicesByUUID[ lastCachedObject.uuid ] = index;
  22594. objects[ index ] = lastCachedObject;
  22595. // last object goes to the activated slot and pop
  22596. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22597. objects[ firstActiveIndex ] = lastObject;
  22598. objects.pop();
  22599. // accounting is done, now do the same for all bindings
  22600. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22601. var bindingsForPath = bindings[ j ],
  22602. lastCached = bindingsForPath[ firstActiveIndex ],
  22603. last = bindingsForPath[ lastIndex ];
  22604. bindingsForPath[ index ] = lastCached;
  22605. bindingsForPath[ firstActiveIndex ] = last;
  22606. bindingsForPath.pop();
  22607. }
  22608. } else {
  22609. // object is active, just swap with the last and pop
  22610. var lastIndex = -- nObjects,
  22611. lastObject = objects[ lastIndex ];
  22612. indicesByUUID[ lastObject.uuid ] = index;
  22613. objects[ index ] = lastObject;
  22614. objects.pop();
  22615. // accounting is done, now do the same for all bindings
  22616. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22617. var bindingsForPath = bindings[ j ];
  22618. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22619. bindingsForPath.pop();
  22620. }
  22621. } // cached or active
  22622. } // if object is known
  22623. } // for arguments
  22624. this.nCachedObjects_ = nCachedObjects;
  22625. },
  22626. // Internal interface used by befriended PropertyBinding.Composite:
  22627. subscribe_: function ( path, parsedPath ) {
  22628. // returns an array of bindings for the given path that is changed
  22629. // according to the contained objects in the group
  22630. var indicesByPath = this._bindingsIndicesByPath,
  22631. index = indicesByPath[ path ],
  22632. bindings = this._bindings;
  22633. if ( index !== undefined ) return bindings[ index ];
  22634. var paths = this._paths,
  22635. parsedPaths = this._parsedPaths,
  22636. objects = this._objects,
  22637. nObjects = objects.length,
  22638. nCachedObjects = this.nCachedObjects_,
  22639. bindingsForPath = new Array( nObjects );
  22640. index = bindings.length;
  22641. indicesByPath[ path ] = index;
  22642. paths.push( path );
  22643. parsedPaths.push( parsedPath );
  22644. bindings.push( bindingsForPath );
  22645. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22646. var object = objects[ i ];
  22647. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22648. }
  22649. return bindingsForPath;
  22650. },
  22651. unsubscribe_: function ( path ) {
  22652. // tells the group to forget about a property path and no longer
  22653. // update the array previously obtained with 'subscribe_'
  22654. var indicesByPath = this._bindingsIndicesByPath,
  22655. index = indicesByPath[ path ];
  22656. if ( index !== undefined ) {
  22657. var paths = this._paths,
  22658. parsedPaths = this._parsedPaths,
  22659. bindings = this._bindings,
  22660. lastBindingsIndex = bindings.length - 1,
  22661. lastBindings = bindings[ lastBindingsIndex ],
  22662. lastBindingsPath = path[ lastBindingsIndex ];
  22663. indicesByPath[ lastBindingsPath ] = index;
  22664. bindings[ index ] = lastBindings;
  22665. bindings.pop();
  22666. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22667. parsedPaths.pop();
  22668. paths[ index ] = paths[ lastBindingsIndex ];
  22669. paths.pop();
  22670. }
  22671. }
  22672. } );
  22673. /**
  22674. *
  22675. * Action provided by AnimationMixer for scheduling clip playback on specific
  22676. * objects.
  22677. *
  22678. * @author Ben Houston / http://clara.io/
  22679. * @author David Sarno / http://lighthaus.us/
  22680. * @author tschw
  22681. *
  22682. */
  22683. function AnimationAction( mixer, clip, localRoot ) {
  22684. this._mixer = mixer;
  22685. this._clip = clip;
  22686. this._localRoot = localRoot || null;
  22687. var tracks = clip.tracks,
  22688. nTracks = tracks.length,
  22689. interpolants = new Array( nTracks );
  22690. var interpolantSettings = {
  22691. endingStart: ZeroCurvatureEnding,
  22692. endingEnd: ZeroCurvatureEnding
  22693. };
  22694. for ( var i = 0; i !== nTracks; ++ i ) {
  22695. var interpolant = tracks[ i ].createInterpolant( null );
  22696. interpolants[ i ] = interpolant;
  22697. interpolant.settings = interpolantSettings;
  22698. }
  22699. this._interpolantSettings = interpolantSettings;
  22700. this._interpolants = interpolants; // bound by the mixer
  22701. // inside: PropertyMixer (managed by the mixer)
  22702. this._propertyBindings = new Array( nTracks );
  22703. this._cacheIndex = null; // for the memory manager
  22704. this._byClipCacheIndex = null; // for the memory manager
  22705. this._timeScaleInterpolant = null;
  22706. this._weightInterpolant = null;
  22707. this.loop = LoopRepeat;
  22708. this._loopCount = -1;
  22709. // global mixer time when the action is to be started
  22710. // it's set back to 'null' upon start of the action
  22711. this._startTime = null;
  22712. // scaled local time of the action
  22713. // gets clamped or wrapped to 0..clip.duration according to loop
  22714. this.time = 0;
  22715. this.timeScale = 1;
  22716. this._effectiveTimeScale = 1;
  22717. this.weight = 1;
  22718. this._effectiveWeight = 1;
  22719. this.repetitions = Infinity; // no. of repetitions when looping
  22720. this.paused = false; // true -> zero effective time scale
  22721. this.enabled = true; // false -> zero effective weight
  22722. this.clampWhenFinished = false; // keep feeding the last frame?
  22723. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22724. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22725. }
  22726. Object.assign( AnimationAction.prototype, {
  22727. // State & Scheduling
  22728. play: function() {
  22729. this._mixer._activateAction( this );
  22730. return this;
  22731. },
  22732. stop: function() {
  22733. this._mixer._deactivateAction( this );
  22734. return this.reset();
  22735. },
  22736. reset: function() {
  22737. this.paused = false;
  22738. this.enabled = true;
  22739. this.time = 0; // restart clip
  22740. this._loopCount = -1; // forget previous loops
  22741. this._startTime = null; // forget scheduling
  22742. return this.stopFading().stopWarping();
  22743. },
  22744. isRunning: function() {
  22745. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22746. this._startTime === null && this._mixer._isActiveAction( this );
  22747. },
  22748. // return true when play has been called
  22749. isScheduled: function() {
  22750. return this._mixer._isActiveAction( this );
  22751. },
  22752. startAt: function( time ) {
  22753. this._startTime = time;
  22754. return this;
  22755. },
  22756. setLoop: function( mode, repetitions ) {
  22757. this.loop = mode;
  22758. this.repetitions = repetitions;
  22759. return this;
  22760. },
  22761. // Weight
  22762. // set the weight stopping any scheduled fading
  22763. // although .enabled = false yields an effective weight of zero, this
  22764. // method does *not* change .enabled, because it would be confusing
  22765. setEffectiveWeight: function( weight ) {
  22766. this.weight = weight;
  22767. // note: same logic as when updated at runtime
  22768. this._effectiveWeight = this.enabled ? weight : 0;
  22769. return this.stopFading();
  22770. },
  22771. // return the weight considering fading and .enabled
  22772. getEffectiveWeight: function() {
  22773. return this._effectiveWeight;
  22774. },
  22775. fadeIn: function( duration ) {
  22776. return this._scheduleFading( duration, 0, 1 );
  22777. },
  22778. fadeOut: function( duration ) {
  22779. return this._scheduleFading( duration, 1, 0 );
  22780. },
  22781. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22782. fadeOutAction.fadeOut( duration );
  22783. this.fadeIn( duration );
  22784. if( warp ) {
  22785. var fadeInDuration = this._clip.duration,
  22786. fadeOutDuration = fadeOutAction._clip.duration,
  22787. startEndRatio = fadeOutDuration / fadeInDuration,
  22788. endStartRatio = fadeInDuration / fadeOutDuration;
  22789. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22790. this.warp( endStartRatio, 1.0, duration );
  22791. }
  22792. return this;
  22793. },
  22794. crossFadeTo: function( fadeInAction, duration, warp ) {
  22795. return fadeInAction.crossFadeFrom( this, duration, warp );
  22796. },
  22797. stopFading: function() {
  22798. var weightInterpolant = this._weightInterpolant;
  22799. if ( weightInterpolant !== null ) {
  22800. this._weightInterpolant = null;
  22801. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22802. }
  22803. return this;
  22804. },
  22805. // Time Scale Control
  22806. // set the time scale stopping any scheduled warping
  22807. // although .paused = true yields an effective time scale of zero, this
  22808. // method does *not* change .paused, because it would be confusing
  22809. setEffectiveTimeScale: function( timeScale ) {
  22810. this.timeScale = timeScale;
  22811. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22812. return this.stopWarping();
  22813. },
  22814. // return the time scale considering warping and .paused
  22815. getEffectiveTimeScale: function() {
  22816. return this._effectiveTimeScale;
  22817. },
  22818. setDuration: function( duration ) {
  22819. this.timeScale = this._clip.duration / duration;
  22820. return this.stopWarping();
  22821. },
  22822. syncWith: function( action ) {
  22823. this.time = action.time;
  22824. this.timeScale = action.timeScale;
  22825. return this.stopWarping();
  22826. },
  22827. halt: function( duration ) {
  22828. return this.warp( this._effectiveTimeScale, 0, duration );
  22829. },
  22830. warp: function( startTimeScale, endTimeScale, duration ) {
  22831. var mixer = this._mixer, now = mixer.time,
  22832. interpolant = this._timeScaleInterpolant,
  22833. timeScale = this.timeScale;
  22834. if ( interpolant === null ) {
  22835. interpolant = mixer._lendControlInterpolant();
  22836. this._timeScaleInterpolant = interpolant;
  22837. }
  22838. var times = interpolant.parameterPositions,
  22839. values = interpolant.sampleValues;
  22840. times[ 0 ] = now;
  22841. times[ 1 ] = now + duration;
  22842. values[ 0 ] = startTimeScale / timeScale;
  22843. values[ 1 ] = endTimeScale / timeScale;
  22844. return this;
  22845. },
  22846. stopWarping: function() {
  22847. var timeScaleInterpolant = this._timeScaleInterpolant;
  22848. if ( timeScaleInterpolant !== null ) {
  22849. this._timeScaleInterpolant = null;
  22850. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22851. }
  22852. return this;
  22853. },
  22854. // Object Accessors
  22855. getMixer: function() {
  22856. return this._mixer;
  22857. },
  22858. getClip: function() {
  22859. return this._clip;
  22860. },
  22861. getRoot: function() {
  22862. return this._localRoot || this._mixer._root;
  22863. },
  22864. // Interna
  22865. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22866. // called by the mixer
  22867. if ( ! this.enabled ) {
  22868. // call ._updateWeight() to update ._effectiveWeight
  22869. this._updateWeight( time );
  22870. return;
  22871. }
  22872. var startTime = this._startTime;
  22873. if ( startTime !== null ) {
  22874. // check for scheduled start of action
  22875. var timeRunning = ( time - startTime ) * timeDirection;
  22876. if ( timeRunning < 0 || timeDirection === 0 ) {
  22877. return; // yet to come / don't decide when delta = 0
  22878. }
  22879. // start
  22880. this._startTime = null; // unschedule
  22881. deltaTime = timeDirection * timeRunning;
  22882. }
  22883. // apply time scale and advance time
  22884. deltaTime *= this._updateTimeScale( time );
  22885. var clipTime = this._updateTime( deltaTime );
  22886. // note: _updateTime may disable the action resulting in
  22887. // an effective weight of 0
  22888. var weight = this._updateWeight( time );
  22889. if ( weight > 0 ) {
  22890. var interpolants = this._interpolants;
  22891. var propertyMixers = this._propertyBindings;
  22892. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22893. interpolants[ j ].evaluate( clipTime );
  22894. propertyMixers[ j ].accumulate( accuIndex, weight );
  22895. }
  22896. }
  22897. },
  22898. _updateWeight: function( time ) {
  22899. var weight = 0;
  22900. if ( this.enabled ) {
  22901. weight = this.weight;
  22902. var interpolant = this._weightInterpolant;
  22903. if ( interpolant !== null ) {
  22904. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22905. weight *= interpolantValue;
  22906. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22907. this.stopFading();
  22908. if ( interpolantValue === 0 ) {
  22909. // faded out, disable
  22910. this.enabled = false;
  22911. }
  22912. }
  22913. }
  22914. }
  22915. this._effectiveWeight = weight;
  22916. return weight;
  22917. },
  22918. _updateTimeScale: function( time ) {
  22919. var timeScale = 0;
  22920. if ( ! this.paused ) {
  22921. timeScale = this.timeScale;
  22922. var interpolant = this._timeScaleInterpolant;
  22923. if ( interpolant !== null ) {
  22924. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22925. timeScale *= interpolantValue;
  22926. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22927. this.stopWarping();
  22928. if ( timeScale === 0 ) {
  22929. // motion has halted, pause
  22930. this.paused = true;
  22931. } else {
  22932. // warp done - apply final time scale
  22933. this.timeScale = timeScale;
  22934. }
  22935. }
  22936. }
  22937. }
  22938. this._effectiveTimeScale = timeScale;
  22939. return timeScale;
  22940. },
  22941. _updateTime: function( deltaTime ) {
  22942. var time = this.time + deltaTime;
  22943. if ( deltaTime === 0 ) return time;
  22944. var duration = this._clip.duration,
  22945. loop = this.loop,
  22946. loopCount = this._loopCount;
  22947. if ( loop === LoopOnce ) {
  22948. if ( loopCount === -1 ) {
  22949. // just started
  22950. this._loopCount = 0;
  22951. this._setEndings( true, true, false );
  22952. }
  22953. handle_stop: {
  22954. if ( time >= duration ) {
  22955. time = duration;
  22956. } else if ( time < 0 ) {
  22957. time = 0;
  22958. } else break handle_stop;
  22959. if ( this.clampWhenFinished ) this.paused = true;
  22960. else this.enabled = false;
  22961. this._mixer.dispatchEvent( {
  22962. type: 'finished', action: this,
  22963. direction: deltaTime < 0 ? -1 : 1
  22964. } );
  22965. }
  22966. } else { // repetitive Repeat or PingPong
  22967. var pingPong = ( loop === LoopPingPong );
  22968. if ( loopCount === -1 ) {
  22969. // just started
  22970. if ( deltaTime >= 0 ) {
  22971. loopCount = 0;
  22972. this._setEndings(
  22973. true, this.repetitions === 0, pingPong );
  22974. } else {
  22975. // when looping in reverse direction, the initial
  22976. // transition through zero counts as a repetition,
  22977. // so leave loopCount at -1
  22978. this._setEndings(
  22979. this.repetitions === 0, true, pingPong );
  22980. }
  22981. }
  22982. if ( time >= duration || time < 0 ) {
  22983. // wrap around
  22984. var loopDelta = Math.floor( time / duration ); // signed
  22985. time -= duration * loopDelta;
  22986. loopCount += Math.abs( loopDelta );
  22987. var pending = this.repetitions - loopCount;
  22988. if ( pending < 0 ) {
  22989. // have to stop (switch state, clamp time, fire event)
  22990. if ( this.clampWhenFinished ) this.paused = true;
  22991. else this.enabled = false;
  22992. time = deltaTime > 0 ? duration : 0;
  22993. this._mixer.dispatchEvent( {
  22994. type: 'finished', action: this,
  22995. direction: deltaTime > 0 ? 1 : -1
  22996. } );
  22997. } else {
  22998. // keep running
  22999. if ( pending === 0 ) {
  23000. // entering the last round
  23001. var atStart = deltaTime < 0;
  23002. this._setEndings( atStart, ! atStart, pingPong );
  23003. } else {
  23004. this._setEndings( false, false, pingPong );
  23005. }
  23006. this._loopCount = loopCount;
  23007. this._mixer.dispatchEvent( {
  23008. type: 'loop', action: this, loopDelta: loopDelta
  23009. } );
  23010. }
  23011. }
  23012. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23013. // invert time for the "pong round"
  23014. this.time = time;
  23015. return duration - time;
  23016. }
  23017. }
  23018. this.time = time;
  23019. return time;
  23020. },
  23021. _setEndings: function( atStart, atEnd, pingPong ) {
  23022. var settings = this._interpolantSettings;
  23023. if ( pingPong ) {
  23024. settings.endingStart = ZeroSlopeEnding;
  23025. settings.endingEnd = ZeroSlopeEnding;
  23026. } else {
  23027. // assuming for LoopOnce atStart == atEnd == true
  23028. if ( atStart ) {
  23029. settings.endingStart = this.zeroSlopeAtStart ?
  23030. ZeroSlopeEnding : ZeroCurvatureEnding;
  23031. } else {
  23032. settings.endingStart = WrapAroundEnding;
  23033. }
  23034. if ( atEnd ) {
  23035. settings.endingEnd = this.zeroSlopeAtEnd ?
  23036. ZeroSlopeEnding : ZeroCurvatureEnding;
  23037. } else {
  23038. settings.endingEnd = WrapAroundEnding;
  23039. }
  23040. }
  23041. },
  23042. _scheduleFading: function( duration, weightNow, weightThen ) {
  23043. var mixer = this._mixer, now = mixer.time,
  23044. interpolant = this._weightInterpolant;
  23045. if ( interpolant === null ) {
  23046. interpolant = mixer._lendControlInterpolant();
  23047. this._weightInterpolant = interpolant;
  23048. }
  23049. var times = interpolant.parameterPositions,
  23050. values = interpolant.sampleValues;
  23051. times[ 0 ] = now; values[ 0 ] = weightNow;
  23052. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23053. return this;
  23054. }
  23055. } );
  23056. /**
  23057. *
  23058. * Player for AnimationClips.
  23059. *
  23060. *
  23061. * @author Ben Houston / http://clara.io/
  23062. * @author David Sarno / http://lighthaus.us/
  23063. * @author tschw
  23064. */
  23065. function AnimationMixer( root ) {
  23066. this._root = root;
  23067. this._initMemoryManager();
  23068. this._accuIndex = 0;
  23069. this.time = 0;
  23070. this.timeScale = 1.0;
  23071. }
  23072. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23073. _bindAction: function ( action, prototypeAction ) {
  23074. var root = action._localRoot || this._root,
  23075. tracks = action._clip.tracks,
  23076. nTracks = tracks.length,
  23077. bindings = action._propertyBindings,
  23078. interpolants = action._interpolants,
  23079. rootUuid = root.uuid,
  23080. bindingsByRoot = this._bindingsByRootAndName,
  23081. bindingsByName = bindingsByRoot[ rootUuid ];
  23082. if ( bindingsByName === undefined ) {
  23083. bindingsByName = {};
  23084. bindingsByRoot[ rootUuid ] = bindingsByName;
  23085. }
  23086. for ( var i = 0; i !== nTracks; ++ i ) {
  23087. var track = tracks[ i ],
  23088. trackName = track.name,
  23089. binding = bindingsByName[ trackName ];
  23090. if ( binding !== undefined ) {
  23091. bindings[ i ] = binding;
  23092. } else {
  23093. binding = bindings[ i ];
  23094. if ( binding !== undefined ) {
  23095. // existing binding, make sure the cache knows
  23096. if ( binding._cacheIndex === null ) {
  23097. ++ binding.referenceCount;
  23098. this._addInactiveBinding( binding, rootUuid, trackName );
  23099. }
  23100. continue;
  23101. }
  23102. var path = prototypeAction && prototypeAction.
  23103. _propertyBindings[ i ].binding.parsedPath;
  23104. binding = new PropertyMixer(
  23105. PropertyBinding.create( root, trackName, path ),
  23106. track.ValueTypeName, track.getValueSize() );
  23107. ++ binding.referenceCount;
  23108. this._addInactiveBinding( binding, rootUuid, trackName );
  23109. bindings[ i ] = binding;
  23110. }
  23111. interpolants[ i ].resultBuffer = binding.buffer;
  23112. }
  23113. },
  23114. _activateAction: function ( action ) {
  23115. if ( ! this._isActiveAction( action ) ) {
  23116. if ( action._cacheIndex === null ) {
  23117. // this action has been forgotten by the cache, but the user
  23118. // appears to be still using it -> rebind
  23119. var rootUuid = ( action._localRoot || this._root ).uuid,
  23120. clipUuid = action._clip.uuid,
  23121. actionsForClip = this._actionsByClip[ clipUuid ];
  23122. this._bindAction( action,
  23123. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23124. this._addInactiveAction( action, clipUuid, rootUuid );
  23125. }
  23126. var bindings = action._propertyBindings;
  23127. // increment reference counts / sort out state
  23128. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23129. var binding = bindings[ i ];
  23130. if ( binding.useCount ++ === 0 ) {
  23131. this._lendBinding( binding );
  23132. binding.saveOriginalState();
  23133. }
  23134. }
  23135. this._lendAction( action );
  23136. }
  23137. },
  23138. _deactivateAction: function ( action ) {
  23139. if ( this._isActiveAction( action ) ) {
  23140. var bindings = action._propertyBindings;
  23141. // decrement reference counts / sort out state
  23142. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23143. var binding = bindings[ i ];
  23144. if ( -- binding.useCount === 0 ) {
  23145. binding.restoreOriginalState();
  23146. this._takeBackBinding( binding );
  23147. }
  23148. }
  23149. this._takeBackAction( action );
  23150. }
  23151. },
  23152. // Memory manager
  23153. _initMemoryManager: function () {
  23154. this._actions = []; // 'nActiveActions' followed by inactive ones
  23155. this._nActiveActions = 0;
  23156. this._actionsByClip = {};
  23157. // inside:
  23158. // {
  23159. // knownActions: Array< AnimationAction > - used as prototypes
  23160. // actionByRoot: AnimationAction - lookup
  23161. // }
  23162. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23163. this._nActiveBindings = 0;
  23164. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23165. this._controlInterpolants = []; // same game as above
  23166. this._nActiveControlInterpolants = 0;
  23167. var scope = this;
  23168. this.stats = {
  23169. actions: {
  23170. get total() { return scope._actions.length; },
  23171. get inUse() { return scope._nActiveActions; }
  23172. },
  23173. bindings: {
  23174. get total() { return scope._bindings.length; },
  23175. get inUse() { return scope._nActiveBindings; }
  23176. },
  23177. controlInterpolants: {
  23178. get total() { return scope._controlInterpolants.length; },
  23179. get inUse() { return scope._nActiveControlInterpolants; }
  23180. }
  23181. };
  23182. },
  23183. // Memory management for AnimationAction objects
  23184. _isActiveAction: function ( action ) {
  23185. var index = action._cacheIndex;
  23186. return index !== null && index < this._nActiveActions;
  23187. },
  23188. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23189. var actions = this._actions,
  23190. actionsByClip = this._actionsByClip,
  23191. actionsForClip = actionsByClip[ clipUuid ];
  23192. if ( actionsForClip === undefined ) {
  23193. actionsForClip = {
  23194. knownActions: [ action ],
  23195. actionByRoot: {}
  23196. };
  23197. action._byClipCacheIndex = 0;
  23198. actionsByClip[ clipUuid ] = actionsForClip;
  23199. } else {
  23200. var knownActions = actionsForClip.knownActions;
  23201. action._byClipCacheIndex = knownActions.length;
  23202. knownActions.push( action );
  23203. }
  23204. action._cacheIndex = actions.length;
  23205. actions.push( action );
  23206. actionsForClip.actionByRoot[ rootUuid ] = action;
  23207. },
  23208. _removeInactiveAction: function ( action ) {
  23209. var actions = this._actions,
  23210. lastInactiveAction = actions[ actions.length - 1 ],
  23211. cacheIndex = action._cacheIndex;
  23212. lastInactiveAction._cacheIndex = cacheIndex;
  23213. actions[ cacheIndex ] = lastInactiveAction;
  23214. actions.pop();
  23215. action._cacheIndex = null;
  23216. var clipUuid = action._clip.uuid,
  23217. actionsByClip = this._actionsByClip,
  23218. actionsForClip = actionsByClip[ clipUuid ],
  23219. knownActionsForClip = actionsForClip.knownActions,
  23220. lastKnownAction =
  23221. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23222. byClipCacheIndex = action._byClipCacheIndex;
  23223. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23224. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23225. knownActionsForClip.pop();
  23226. action._byClipCacheIndex = null;
  23227. var actionByRoot = actionsForClip.actionByRoot,
  23228. rootUuid = ( action._localRoot || this._root ).uuid;
  23229. delete actionByRoot[ rootUuid ];
  23230. if ( knownActionsForClip.length === 0 ) {
  23231. delete actionsByClip[ clipUuid ];
  23232. }
  23233. this._removeInactiveBindingsForAction( action );
  23234. },
  23235. _removeInactiveBindingsForAction: function ( action ) {
  23236. var bindings = action._propertyBindings;
  23237. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23238. var binding = bindings[ i ];
  23239. if ( -- binding.referenceCount === 0 ) {
  23240. this._removeInactiveBinding( binding );
  23241. }
  23242. }
  23243. },
  23244. _lendAction: function ( action ) {
  23245. // [ active actions | inactive actions ]
  23246. // [ active actions >| inactive actions ]
  23247. // s a
  23248. // <-swap->
  23249. // a s
  23250. var actions = this._actions,
  23251. prevIndex = action._cacheIndex,
  23252. lastActiveIndex = this._nActiveActions ++,
  23253. firstInactiveAction = actions[ lastActiveIndex ];
  23254. action._cacheIndex = lastActiveIndex;
  23255. actions[ lastActiveIndex ] = action;
  23256. firstInactiveAction._cacheIndex = prevIndex;
  23257. actions[ prevIndex ] = firstInactiveAction;
  23258. },
  23259. _takeBackAction: function ( action ) {
  23260. // [ active actions | inactive actions ]
  23261. // [ active actions |< inactive actions ]
  23262. // a s
  23263. // <-swap->
  23264. // s a
  23265. var actions = this._actions,
  23266. prevIndex = action._cacheIndex,
  23267. firstInactiveIndex = -- this._nActiveActions,
  23268. lastActiveAction = actions[ firstInactiveIndex ];
  23269. action._cacheIndex = firstInactiveIndex;
  23270. actions[ firstInactiveIndex ] = action;
  23271. lastActiveAction._cacheIndex = prevIndex;
  23272. actions[ prevIndex ] = lastActiveAction;
  23273. },
  23274. // Memory management for PropertyMixer objects
  23275. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23276. var bindingsByRoot = this._bindingsByRootAndName,
  23277. bindingByName = bindingsByRoot[ rootUuid ],
  23278. bindings = this._bindings;
  23279. if ( bindingByName === undefined ) {
  23280. bindingByName = {};
  23281. bindingsByRoot[ rootUuid ] = bindingByName;
  23282. }
  23283. bindingByName[ trackName ] = binding;
  23284. binding._cacheIndex = bindings.length;
  23285. bindings.push( binding );
  23286. },
  23287. _removeInactiveBinding: function ( binding ) {
  23288. var bindings = this._bindings,
  23289. propBinding = binding.binding,
  23290. rootUuid = propBinding.rootNode.uuid,
  23291. trackName = propBinding.path,
  23292. bindingsByRoot = this._bindingsByRootAndName,
  23293. bindingByName = bindingsByRoot[ rootUuid ],
  23294. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23295. cacheIndex = binding._cacheIndex;
  23296. lastInactiveBinding._cacheIndex = cacheIndex;
  23297. bindings[ cacheIndex ] = lastInactiveBinding;
  23298. bindings.pop();
  23299. delete bindingByName[ trackName ];
  23300. remove_empty_map: {
  23301. for ( var _ in bindingByName ) break remove_empty_map;
  23302. delete bindingsByRoot[ rootUuid ];
  23303. }
  23304. },
  23305. _lendBinding: function ( binding ) {
  23306. var bindings = this._bindings,
  23307. prevIndex = binding._cacheIndex,
  23308. lastActiveIndex = this._nActiveBindings ++,
  23309. firstInactiveBinding = bindings[ lastActiveIndex ];
  23310. binding._cacheIndex = lastActiveIndex;
  23311. bindings[ lastActiveIndex ] = binding;
  23312. firstInactiveBinding._cacheIndex = prevIndex;
  23313. bindings[ prevIndex ] = firstInactiveBinding;
  23314. },
  23315. _takeBackBinding: function ( binding ) {
  23316. var bindings = this._bindings,
  23317. prevIndex = binding._cacheIndex,
  23318. firstInactiveIndex = -- this._nActiveBindings,
  23319. lastActiveBinding = bindings[ firstInactiveIndex ];
  23320. binding._cacheIndex = firstInactiveIndex;
  23321. bindings[ firstInactiveIndex ] = binding;
  23322. lastActiveBinding._cacheIndex = prevIndex;
  23323. bindings[ prevIndex ] = lastActiveBinding;
  23324. },
  23325. // Memory management of Interpolants for weight and time scale
  23326. _lendControlInterpolant: function () {
  23327. var interpolants = this._controlInterpolants,
  23328. lastActiveIndex = this._nActiveControlInterpolants ++,
  23329. interpolant = interpolants[ lastActiveIndex ];
  23330. if ( interpolant === undefined ) {
  23331. interpolant = new LinearInterpolant(
  23332. new Float32Array( 2 ), new Float32Array( 2 ),
  23333. 1, this._controlInterpolantsResultBuffer );
  23334. interpolant.__cacheIndex = lastActiveIndex;
  23335. interpolants[ lastActiveIndex ] = interpolant;
  23336. }
  23337. return interpolant;
  23338. },
  23339. _takeBackControlInterpolant: function ( interpolant ) {
  23340. var interpolants = this._controlInterpolants,
  23341. prevIndex = interpolant.__cacheIndex,
  23342. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23343. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23344. interpolant.__cacheIndex = firstInactiveIndex;
  23345. interpolants[ firstInactiveIndex ] = interpolant;
  23346. lastActiveInterpolant.__cacheIndex = prevIndex;
  23347. interpolants[ prevIndex ] = lastActiveInterpolant;
  23348. },
  23349. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23350. // return an action for a clip optionally using a custom root target
  23351. // object (this method allocates a lot of dynamic memory in case a
  23352. // previously unknown clip/root combination is specified)
  23353. clipAction: function ( clip, optionalRoot ) {
  23354. var root = optionalRoot || this._root,
  23355. rootUuid = root.uuid,
  23356. clipObject = typeof clip === 'string' ?
  23357. AnimationClip.findByName( root, clip ) : clip,
  23358. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23359. actionsForClip = this._actionsByClip[ clipUuid ],
  23360. prototypeAction = null;
  23361. if ( actionsForClip !== undefined ) {
  23362. var existingAction =
  23363. actionsForClip.actionByRoot[ rootUuid ];
  23364. if ( existingAction !== undefined ) {
  23365. return existingAction;
  23366. }
  23367. // we know the clip, so we don't have to parse all
  23368. // the bindings again but can just copy
  23369. prototypeAction = actionsForClip.knownActions[ 0 ];
  23370. // also, take the clip from the prototype action
  23371. if ( clipObject === null )
  23372. clipObject = prototypeAction._clip;
  23373. }
  23374. // clip must be known when specified via string
  23375. if ( clipObject === null ) return null;
  23376. // allocate all resources required to run it
  23377. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23378. this._bindAction( newAction, prototypeAction );
  23379. // and make the action known to the memory manager
  23380. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23381. return newAction;
  23382. },
  23383. // get an existing action
  23384. existingAction: function ( clip, optionalRoot ) {
  23385. var root = optionalRoot || this._root,
  23386. rootUuid = root.uuid,
  23387. clipObject = typeof clip === 'string' ?
  23388. AnimationClip.findByName( root, clip ) : clip,
  23389. clipUuid = clipObject ? clipObject.uuid : clip,
  23390. actionsForClip = this._actionsByClip[ clipUuid ];
  23391. if ( actionsForClip !== undefined ) {
  23392. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23393. }
  23394. return null;
  23395. },
  23396. // deactivates all previously scheduled actions
  23397. stopAllAction: function () {
  23398. var actions = this._actions,
  23399. nActions = this._nActiveActions,
  23400. bindings = this._bindings,
  23401. nBindings = this._nActiveBindings;
  23402. this._nActiveActions = 0;
  23403. this._nActiveBindings = 0;
  23404. for ( var i = 0; i !== nActions; ++ i ) {
  23405. actions[ i ].reset();
  23406. }
  23407. for ( var i = 0; i !== nBindings; ++ i ) {
  23408. bindings[ i ].useCount = 0;
  23409. }
  23410. return this;
  23411. },
  23412. // advance the time and update apply the animation
  23413. update: function ( deltaTime ) {
  23414. deltaTime *= this.timeScale;
  23415. var actions = this._actions,
  23416. nActions = this._nActiveActions,
  23417. time = this.time += deltaTime,
  23418. timeDirection = Math.sign( deltaTime ),
  23419. accuIndex = this._accuIndex ^= 1;
  23420. // run active actions
  23421. for ( var i = 0; i !== nActions; ++ i ) {
  23422. var action = actions[ i ];
  23423. action._update( time, deltaTime, timeDirection, accuIndex );
  23424. }
  23425. // update scene graph
  23426. var bindings = this._bindings,
  23427. nBindings = this._nActiveBindings;
  23428. for ( var i = 0; i !== nBindings; ++ i ) {
  23429. bindings[ i ].apply( accuIndex );
  23430. }
  23431. return this;
  23432. },
  23433. // return this mixer's root target object
  23434. getRoot: function () {
  23435. return this._root;
  23436. },
  23437. // free all resources specific to a particular clip
  23438. uncacheClip: function ( clip ) {
  23439. var actions = this._actions,
  23440. clipUuid = clip.uuid,
  23441. actionsByClip = this._actionsByClip,
  23442. actionsForClip = actionsByClip[ clipUuid ];
  23443. if ( actionsForClip !== undefined ) {
  23444. // note: just calling _removeInactiveAction would mess up the
  23445. // iteration state and also require updating the state we can
  23446. // just throw away
  23447. var actionsToRemove = actionsForClip.knownActions;
  23448. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23449. var action = actionsToRemove[ i ];
  23450. this._deactivateAction( action );
  23451. var cacheIndex = action._cacheIndex,
  23452. lastInactiveAction = actions[ actions.length - 1 ];
  23453. action._cacheIndex = null;
  23454. action._byClipCacheIndex = null;
  23455. lastInactiveAction._cacheIndex = cacheIndex;
  23456. actions[ cacheIndex ] = lastInactiveAction;
  23457. actions.pop();
  23458. this._removeInactiveBindingsForAction( action );
  23459. }
  23460. delete actionsByClip[ clipUuid ];
  23461. }
  23462. },
  23463. // free all resources specific to a particular root target object
  23464. uncacheRoot: function ( root ) {
  23465. var rootUuid = root.uuid,
  23466. actionsByClip = this._actionsByClip;
  23467. for ( var clipUuid in actionsByClip ) {
  23468. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23469. action = actionByRoot[ rootUuid ];
  23470. if ( action !== undefined ) {
  23471. this._deactivateAction( action );
  23472. this._removeInactiveAction( action );
  23473. }
  23474. }
  23475. var bindingsByRoot = this._bindingsByRootAndName,
  23476. bindingByName = bindingsByRoot[ rootUuid ];
  23477. if ( bindingByName !== undefined ) {
  23478. for ( var trackName in bindingByName ) {
  23479. var binding = bindingByName[ trackName ];
  23480. binding.restoreOriginalState();
  23481. this._removeInactiveBinding( binding );
  23482. }
  23483. }
  23484. },
  23485. // remove a targeted clip from the cache
  23486. uncacheAction: function ( clip, optionalRoot ) {
  23487. var action = this.existingAction( clip, optionalRoot );
  23488. if ( action !== null ) {
  23489. this._deactivateAction( action );
  23490. this._removeInactiveAction( action );
  23491. }
  23492. }
  23493. } );
  23494. /**
  23495. * @author mrdoob / http://mrdoob.com/
  23496. */
  23497. function Uniform( value ) {
  23498. if ( typeof value === 'string' ) {
  23499. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23500. value = arguments[ 1 ];
  23501. }
  23502. this.value = value;
  23503. }
  23504. Uniform.prototype.clone = function () {
  23505. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23506. };
  23507. /**
  23508. * @author benaadams / https://twitter.com/ben_a_adams
  23509. */
  23510. function InstancedBufferGeometry() {
  23511. BufferGeometry.call( this );
  23512. this.type = 'InstancedBufferGeometry';
  23513. this.maxInstancedCount = undefined;
  23514. }
  23515. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23516. constructor: InstancedBufferGeometry,
  23517. isInstancedBufferGeometry: true,
  23518. addGroup: function ( start, count, materialIndex ) {
  23519. this.groups.push( {
  23520. start: start,
  23521. count: count,
  23522. materialIndex: materialIndex
  23523. } );
  23524. },
  23525. copy: function ( source ) {
  23526. var index = source.index;
  23527. if ( index !== null ) {
  23528. this.setIndex( index.clone() );
  23529. }
  23530. var attributes = source.attributes;
  23531. for ( var name in attributes ) {
  23532. var attribute = attributes[ name ];
  23533. this.addAttribute( name, attribute.clone() );
  23534. }
  23535. var groups = source.groups;
  23536. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23537. var group = groups[ i ];
  23538. this.addGroup( group.start, group.count, group.materialIndex );
  23539. }
  23540. return this;
  23541. }
  23542. } );
  23543. /**
  23544. * @author benaadams / https://twitter.com/ben_a_adams
  23545. */
  23546. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23547. this.uuid = _Math.generateUUID();
  23548. this.data = interleavedBuffer;
  23549. this.itemSize = itemSize;
  23550. this.offset = offset;
  23551. this.normalized = normalized === true;
  23552. }
  23553. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23554. count: {
  23555. get: function () {
  23556. return this.data.count;
  23557. }
  23558. },
  23559. array: {
  23560. get: function () {
  23561. return this.data.array;
  23562. }
  23563. }
  23564. } );
  23565. Object.assign( InterleavedBufferAttribute.prototype, {
  23566. isInterleavedBufferAttribute: true,
  23567. setX: function ( index, x ) {
  23568. this.data.array[ index * this.data.stride + this.offset ] = x;
  23569. return this;
  23570. },
  23571. setY: function ( index, y ) {
  23572. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23573. return this;
  23574. },
  23575. setZ: function ( index, z ) {
  23576. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23577. return this;
  23578. },
  23579. setW: function ( index, w ) {
  23580. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23581. return this;
  23582. },
  23583. getX: function ( index ) {
  23584. return this.data.array[ index * this.data.stride + this.offset ];
  23585. },
  23586. getY: function ( index ) {
  23587. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23588. },
  23589. getZ: function ( index ) {
  23590. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23591. },
  23592. getW: function ( index ) {
  23593. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23594. },
  23595. setXY: function ( index, x, y ) {
  23596. index = index * this.data.stride + this.offset;
  23597. this.data.array[ index + 0 ] = x;
  23598. this.data.array[ index + 1 ] = y;
  23599. return this;
  23600. },
  23601. setXYZ: function ( index, x, y, z ) {
  23602. index = index * this.data.stride + this.offset;
  23603. this.data.array[ index + 0 ] = x;
  23604. this.data.array[ index + 1 ] = y;
  23605. this.data.array[ index + 2 ] = z;
  23606. return this;
  23607. },
  23608. setXYZW: function ( index, x, y, z, w ) {
  23609. index = index * this.data.stride + this.offset;
  23610. this.data.array[ index + 0 ] = x;
  23611. this.data.array[ index + 1 ] = y;
  23612. this.data.array[ index + 2 ] = z;
  23613. this.data.array[ index + 3 ] = w;
  23614. return this;
  23615. }
  23616. } );
  23617. /**
  23618. * @author benaadams / https://twitter.com/ben_a_adams
  23619. */
  23620. function InterleavedBuffer( array, stride ) {
  23621. this.uuid = _Math.generateUUID();
  23622. this.array = array;
  23623. this.stride = stride;
  23624. this.count = array !== undefined ? array.length / stride : 0;
  23625. this.dynamic = false;
  23626. this.updateRange = { offset: 0, count: - 1 };
  23627. this.onUploadCallback = function () {};
  23628. this.version = 0;
  23629. }
  23630. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23631. set: function ( value ) {
  23632. if ( value === true ) this.version ++;
  23633. }
  23634. } );
  23635. Object.assign( InterleavedBuffer.prototype, {
  23636. isInterleavedBuffer: true,
  23637. setArray: function ( array ) {
  23638. if ( Array.isArray( array ) ) {
  23639. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23640. }
  23641. this.count = array !== undefined ? array.length / this.stride : 0;
  23642. this.array = array;
  23643. },
  23644. setDynamic: function ( value ) {
  23645. this.dynamic = value;
  23646. return this;
  23647. },
  23648. copy: function ( source ) {
  23649. this.array = new source.array.constructor( source.array );
  23650. this.count = source.count;
  23651. this.stride = source.stride;
  23652. this.dynamic = source.dynamic;
  23653. return this;
  23654. },
  23655. copyAt: function ( index1, attribute, index2 ) {
  23656. index1 *= this.stride;
  23657. index2 *= attribute.stride;
  23658. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23659. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23660. }
  23661. return this;
  23662. },
  23663. set: function ( value, offset ) {
  23664. if ( offset === undefined ) offset = 0;
  23665. this.array.set( value, offset );
  23666. return this;
  23667. },
  23668. clone: function () {
  23669. return new this.constructor().copy( this );
  23670. },
  23671. onUpload: function ( callback ) {
  23672. this.onUploadCallback = callback;
  23673. return this;
  23674. }
  23675. } );
  23676. /**
  23677. * @author benaadams / https://twitter.com/ben_a_adams
  23678. */
  23679. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23680. InterleavedBuffer.call( this, array, stride );
  23681. this.meshPerAttribute = meshPerAttribute || 1;
  23682. }
  23683. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23684. constructor: InstancedInterleavedBuffer,
  23685. isInstancedInterleavedBuffer: true,
  23686. copy: function ( source ) {
  23687. InterleavedBuffer.prototype.copy.call( this, source );
  23688. this.meshPerAttribute = source.meshPerAttribute;
  23689. return this;
  23690. }
  23691. } );
  23692. /**
  23693. * @author benaadams / https://twitter.com/ben_a_adams
  23694. */
  23695. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23696. BufferAttribute.call( this, array, itemSize );
  23697. this.meshPerAttribute = meshPerAttribute || 1;
  23698. }
  23699. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  23700. constructor: InstancedBufferAttribute,
  23701. isInstancedBufferAttribute: true,
  23702. copy: function ( source ) {
  23703. BufferAttribute.prototype.copy.call( this, source );
  23704. this.meshPerAttribute = source.meshPerAttribute;
  23705. return this;
  23706. }
  23707. } );
  23708. /**
  23709. * @author mrdoob / http://mrdoob.com/
  23710. * @author bhouston / http://clara.io/
  23711. * @author stephomi / http://stephaneginier.com/
  23712. */
  23713. function Raycaster( origin, direction, near, far ) {
  23714. this.ray = new Ray( origin, direction );
  23715. // direction is assumed to be normalized (for accurate distance calculations)
  23716. this.near = near || 0;
  23717. this.far = far || Infinity;
  23718. this.params = {
  23719. Mesh: {},
  23720. Line: {},
  23721. LOD: {},
  23722. Points: { threshold: 1 },
  23723. Sprite: {}
  23724. };
  23725. Object.defineProperties( this.params, {
  23726. PointCloud: {
  23727. get: function () {
  23728. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23729. return this.Points;
  23730. }
  23731. }
  23732. } );
  23733. }
  23734. function ascSort( a, b ) {
  23735. return a.distance - b.distance;
  23736. }
  23737. function intersectObject( object, raycaster, intersects, recursive ) {
  23738. if ( object.visible === false ) return;
  23739. object.raycast( raycaster, intersects );
  23740. if ( recursive === true ) {
  23741. var children = object.children;
  23742. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23743. intersectObject( children[ i ], raycaster, intersects, true );
  23744. }
  23745. }
  23746. }
  23747. Object.assign( Raycaster.prototype, {
  23748. linePrecision: 1,
  23749. set: function ( origin, direction ) {
  23750. // direction is assumed to be normalized (for accurate distance calculations)
  23751. this.ray.set( origin, direction );
  23752. },
  23753. setFromCamera: function ( coords, camera ) {
  23754. if ( ( camera && camera.isPerspectiveCamera ) ) {
  23755. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23756. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23757. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  23758. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23759. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23760. } else {
  23761. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23762. }
  23763. },
  23764. intersectObject: function ( object, recursive ) {
  23765. var intersects = [];
  23766. intersectObject( object, this, intersects, recursive );
  23767. intersects.sort( ascSort );
  23768. return intersects;
  23769. },
  23770. intersectObjects: function ( objects, recursive ) {
  23771. var intersects = [];
  23772. if ( Array.isArray( objects ) === false ) {
  23773. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23774. return intersects;
  23775. }
  23776. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23777. intersectObject( objects[ i ], this, intersects, recursive );
  23778. }
  23779. intersects.sort( ascSort );
  23780. return intersects;
  23781. }
  23782. } );
  23783. /**
  23784. * @author alteredq / http://alteredqualia.com/
  23785. */
  23786. function Clock( autoStart ) {
  23787. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23788. this.startTime = 0;
  23789. this.oldTime = 0;
  23790. this.elapsedTime = 0;
  23791. this.running = false;
  23792. }
  23793. Object.assign( Clock.prototype, {
  23794. start: function () {
  23795. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  23796. this.oldTime = this.startTime;
  23797. this.elapsedTime = 0;
  23798. this.running = true;
  23799. },
  23800. stop: function () {
  23801. this.getElapsedTime();
  23802. this.running = false;
  23803. },
  23804. getElapsedTime: function () {
  23805. this.getDelta();
  23806. return this.elapsedTime;
  23807. },
  23808. getDelta: function () {
  23809. var diff = 0;
  23810. if ( this.autoStart && ! this.running ) {
  23811. this.start();
  23812. return 0;
  23813. }
  23814. if ( this.running ) {
  23815. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  23816. diff = ( newTime - this.oldTime ) / 1000;
  23817. this.oldTime = newTime;
  23818. this.elapsedTime += diff;
  23819. }
  23820. return diff;
  23821. }
  23822. } );
  23823. /**
  23824. * @author bhouston / http://clara.io
  23825. * @author WestLangley / http://github.com/WestLangley
  23826. *
  23827. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23828. *
  23829. * The poles (phi) are at the positive and negative y axis.
  23830. * The equator starts at positive z.
  23831. */
  23832. function Spherical( radius, phi, theta ) {
  23833. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23834. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23835. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23836. return this;
  23837. }
  23838. Object.assign( Spherical.prototype, {
  23839. set: function ( radius, phi, theta ) {
  23840. this.radius = radius;
  23841. this.phi = phi;
  23842. this.theta = theta;
  23843. return this;
  23844. },
  23845. clone: function () {
  23846. return new this.constructor().copy( this );
  23847. },
  23848. copy: function ( other ) {
  23849. this.radius = other.radius;
  23850. this.phi = other.phi;
  23851. this.theta = other.theta;
  23852. return this;
  23853. },
  23854. // restrict phi to be betwee EPS and PI-EPS
  23855. makeSafe: function() {
  23856. var EPS = 0.000001;
  23857. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23858. return this;
  23859. },
  23860. setFromVector3: function( vec3 ) {
  23861. this.radius = vec3.length();
  23862. if ( this.radius === 0 ) {
  23863. this.theta = 0;
  23864. this.phi = 0;
  23865. } else {
  23866. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23867. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23868. }
  23869. return this;
  23870. }
  23871. } );
  23872. /**
  23873. * @author Mugen87 / https://github.com/Mugen87
  23874. *
  23875. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23876. *
  23877. */
  23878. function Cylindrical( radius, theta, y ) {
  23879. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23880. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23881. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23882. return this;
  23883. }
  23884. Object.assign( Cylindrical.prototype, {
  23885. set: function ( radius, theta, y ) {
  23886. this.radius = radius;
  23887. this.theta = theta;
  23888. this.y = y;
  23889. return this;
  23890. },
  23891. clone: function () {
  23892. return new this.constructor().copy( this );
  23893. },
  23894. copy: function ( other ) {
  23895. this.radius = other.radius;
  23896. this.theta = other.theta;
  23897. this.y = other.y;
  23898. return this;
  23899. },
  23900. setFromVector3: function( vec3 ) {
  23901. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23902. this.theta = Math.atan2( vec3.x, vec3.z );
  23903. this.y = vec3.y;
  23904. return this;
  23905. }
  23906. } );
  23907. /**
  23908. * @author alteredq / http://alteredqualia.com/
  23909. */
  23910. function MorphBlendMesh( geometry, material ) {
  23911. Mesh.call( this, geometry, material );
  23912. this.animationsMap = {};
  23913. this.animationsList = [];
  23914. // prepare default animation
  23915. // (all frames played together in 1 second)
  23916. var numFrames = this.geometry.morphTargets.length;
  23917. var name = "__default";
  23918. var startFrame = 0;
  23919. var endFrame = numFrames - 1;
  23920. var fps = numFrames / 1;
  23921. this.createAnimation( name, startFrame, endFrame, fps );
  23922. this.setAnimationWeight( name, 1 );
  23923. }
  23924. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23925. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23926. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23927. var animation = {
  23928. start: start,
  23929. end: end,
  23930. length: end - start + 1,
  23931. fps: fps,
  23932. duration: ( end - start ) / fps,
  23933. lastFrame: 0,
  23934. currentFrame: 0,
  23935. active: false,
  23936. time: 0,
  23937. direction: 1,
  23938. weight: 1,
  23939. directionBackwards: false,
  23940. mirroredLoop: false
  23941. };
  23942. this.animationsMap[ name ] = animation;
  23943. this.animationsList.push( animation );
  23944. };
  23945. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23946. var pattern = /([a-z]+)_?(\d+)/i;
  23947. var firstAnimation, frameRanges = {};
  23948. var geometry = this.geometry;
  23949. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23950. var morph = geometry.morphTargets[ i ];
  23951. var chunks = morph.name.match( pattern );
  23952. if ( chunks && chunks.length > 1 ) {
  23953. var name = chunks[ 1 ];
  23954. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23955. var range = frameRanges[ name ];
  23956. if ( i < range.start ) range.start = i;
  23957. if ( i > range.end ) range.end = i;
  23958. if ( ! firstAnimation ) firstAnimation = name;
  23959. }
  23960. }
  23961. for ( var name in frameRanges ) {
  23962. var range = frameRanges[ name ];
  23963. this.createAnimation( name, range.start, range.end, fps );
  23964. }
  23965. this.firstAnimation = firstAnimation;
  23966. };
  23967. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23968. var animation = this.animationsMap[ name ];
  23969. if ( animation ) {
  23970. animation.direction = 1;
  23971. animation.directionBackwards = false;
  23972. }
  23973. };
  23974. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23975. var animation = this.animationsMap[ name ];
  23976. if ( animation ) {
  23977. animation.direction = - 1;
  23978. animation.directionBackwards = true;
  23979. }
  23980. };
  23981. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23982. var animation = this.animationsMap[ name ];
  23983. if ( animation ) {
  23984. animation.fps = fps;
  23985. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23986. }
  23987. };
  23988. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23989. var animation = this.animationsMap[ name ];
  23990. if ( animation ) {
  23991. animation.duration = duration;
  23992. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23993. }
  23994. };
  23995. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23996. var animation = this.animationsMap[ name ];
  23997. if ( animation ) {
  23998. animation.weight = weight;
  23999. }
  24000. };
  24001. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24002. var animation = this.animationsMap[ name ];
  24003. if ( animation ) {
  24004. animation.time = time;
  24005. }
  24006. };
  24007. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24008. var time = 0;
  24009. var animation = this.animationsMap[ name ];
  24010. if ( animation ) {
  24011. time = animation.time;
  24012. }
  24013. return time;
  24014. };
  24015. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24016. var duration = - 1;
  24017. var animation = this.animationsMap[ name ];
  24018. if ( animation ) {
  24019. duration = animation.duration;
  24020. }
  24021. return duration;
  24022. };
  24023. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24024. var animation = this.animationsMap[ name ];
  24025. if ( animation ) {
  24026. animation.time = 0;
  24027. animation.active = true;
  24028. } else {
  24029. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24030. }
  24031. };
  24032. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24033. var animation = this.animationsMap[ name ];
  24034. if ( animation ) {
  24035. animation.active = false;
  24036. }
  24037. };
  24038. MorphBlendMesh.prototype.update = function ( delta ) {
  24039. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24040. var animation = this.animationsList[ i ];
  24041. if ( ! animation.active ) continue;
  24042. var frameTime = animation.duration / animation.length;
  24043. animation.time += animation.direction * delta;
  24044. if ( animation.mirroredLoop ) {
  24045. if ( animation.time > animation.duration || animation.time < 0 ) {
  24046. animation.direction *= - 1;
  24047. if ( animation.time > animation.duration ) {
  24048. animation.time = animation.duration;
  24049. animation.directionBackwards = true;
  24050. }
  24051. if ( animation.time < 0 ) {
  24052. animation.time = 0;
  24053. animation.directionBackwards = false;
  24054. }
  24055. }
  24056. } else {
  24057. animation.time = animation.time % animation.duration;
  24058. if ( animation.time < 0 ) animation.time += animation.duration;
  24059. }
  24060. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24061. var weight = animation.weight;
  24062. if ( keyframe !== animation.currentFrame ) {
  24063. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24064. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24065. this.morphTargetInfluences[ keyframe ] = 0;
  24066. animation.lastFrame = animation.currentFrame;
  24067. animation.currentFrame = keyframe;
  24068. }
  24069. var mix = ( animation.time % frameTime ) / frameTime;
  24070. if ( animation.directionBackwards ) mix = 1 - mix;
  24071. if ( animation.currentFrame !== animation.lastFrame ) {
  24072. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24073. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24074. } else {
  24075. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24076. }
  24077. }
  24078. };
  24079. /**
  24080. * @author alteredq / http://alteredqualia.com/
  24081. */
  24082. function ImmediateRenderObject( material ) {
  24083. Object3D.call( this );
  24084. this.material = material;
  24085. this.render = function ( renderCallback ) {};
  24086. }
  24087. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24088. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24089. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24090. /**
  24091. * @author mrdoob / http://mrdoob.com/
  24092. * @author WestLangley / http://github.com/WestLangley
  24093. */
  24094. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24095. this.object = object;
  24096. this.size = ( size !== undefined ) ? size : 1;
  24097. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24098. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24099. //
  24100. var nNormals = 0;
  24101. var objGeometry = this.object.geometry;
  24102. if ( objGeometry && objGeometry.isGeometry ) {
  24103. nNormals = objGeometry.faces.length * 3;
  24104. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24105. nNormals = objGeometry.attributes.normal.count;
  24106. }
  24107. //
  24108. var geometry = new BufferGeometry();
  24109. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24110. geometry.addAttribute( 'position', positions );
  24111. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24112. //
  24113. this.matrixAutoUpdate = false;
  24114. this.update();
  24115. }
  24116. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24117. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24118. VertexNormalsHelper.prototype.update = ( function () {
  24119. var v1 = new Vector3();
  24120. var v2 = new Vector3();
  24121. var normalMatrix = new Matrix3();
  24122. return function update() {
  24123. var keys = [ 'a', 'b', 'c' ];
  24124. this.object.updateMatrixWorld( true );
  24125. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24126. var matrixWorld = this.object.matrixWorld;
  24127. var position = this.geometry.attributes.position;
  24128. //
  24129. var objGeometry = this.object.geometry;
  24130. if ( objGeometry && objGeometry.isGeometry ) {
  24131. var vertices = objGeometry.vertices;
  24132. var faces = objGeometry.faces;
  24133. var idx = 0;
  24134. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24135. var face = faces[ i ];
  24136. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24137. var vertex = vertices[ face[ keys[ j ] ] ];
  24138. var normal = face.vertexNormals[ j ];
  24139. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24140. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24141. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24142. idx = idx + 1;
  24143. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24144. idx = idx + 1;
  24145. }
  24146. }
  24147. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24148. var objPos = objGeometry.attributes.position;
  24149. var objNorm = objGeometry.attributes.normal;
  24150. var idx = 0;
  24151. // for simplicity, ignore index and drawcalls, and render every normal
  24152. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24153. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24154. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24155. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24156. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24157. idx = idx + 1;
  24158. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24159. idx = idx + 1;
  24160. }
  24161. }
  24162. position.needsUpdate = true;
  24163. };
  24164. }() );
  24165. /**
  24166. * @author alteredq / http://alteredqualia.com/
  24167. * @author mrdoob / http://mrdoob.com/
  24168. * @author WestLangley / http://github.com/WestLangley
  24169. */
  24170. function SpotLightHelper( light ) {
  24171. Object3D.call( this );
  24172. this.light = light;
  24173. this.light.updateMatrixWorld();
  24174. this.matrix = light.matrixWorld;
  24175. this.matrixAutoUpdate = false;
  24176. var geometry = new BufferGeometry();
  24177. var positions = [
  24178. 0, 0, 0, 0, 0, 1,
  24179. 0, 0, 0, 1, 0, 1,
  24180. 0, 0, 0, - 1, 0, 1,
  24181. 0, 0, 0, 0, 1, 1,
  24182. 0, 0, 0, 0, - 1, 1
  24183. ];
  24184. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24185. var p1 = ( i / l ) * Math.PI * 2;
  24186. var p2 = ( j / l ) * Math.PI * 2;
  24187. positions.push(
  24188. Math.cos( p1 ), Math.sin( p1 ), 1,
  24189. Math.cos( p2 ), Math.sin( p2 ), 1
  24190. );
  24191. }
  24192. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24193. var material = new LineBasicMaterial( { fog: false } );
  24194. this.cone = new LineSegments( geometry, material );
  24195. this.add( this.cone );
  24196. this.update();
  24197. }
  24198. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24199. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24200. SpotLightHelper.prototype.dispose = function () {
  24201. this.cone.geometry.dispose();
  24202. this.cone.material.dispose();
  24203. };
  24204. SpotLightHelper.prototype.update = function () {
  24205. var vector = new Vector3();
  24206. var vector2 = new Vector3();
  24207. return function update() {
  24208. var coneLength = this.light.distance ? this.light.distance : 1000;
  24209. var coneWidth = coneLength * Math.tan( this.light.angle );
  24210. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24211. vector.setFromMatrixPosition( this.light.matrixWorld );
  24212. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24213. this.cone.lookAt( vector2.sub( vector ) );
  24214. this.cone.material.color.copy( this.light.color );
  24215. };
  24216. }();
  24217. /**
  24218. * @author Sean Griffin / http://twitter.com/sgrif
  24219. * @author Michael Guerrero / http://realitymeltdown.com
  24220. * @author mrdoob / http://mrdoob.com/
  24221. * @author ikerr / http://verold.com
  24222. * @author Mugen87 / https://github.com/Mugen87
  24223. */
  24224. function SkeletonHelper( object ) {
  24225. this.bones = this.getBoneList( object );
  24226. var geometry = new BufferGeometry();
  24227. var vertices = [];
  24228. var colors = [];
  24229. var color1 = new Color( 0, 0, 1 );
  24230. var color2 = new Color( 0, 1, 0 );
  24231. for ( var i = 0; i < this.bones.length; i ++ ) {
  24232. var bone = this.bones[ i ];
  24233. if ( bone.parent && bone.parent.isBone ) {
  24234. vertices.push( 0, 0, 0 );
  24235. vertices.push( 0, 0, 0 );
  24236. colors.push( color1.r, color1.g, color1.b );
  24237. colors.push( color2.r, color2.g, color2.b );
  24238. }
  24239. }
  24240. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24241. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24242. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24243. LineSegments.call( this, geometry, material );
  24244. this.root = object;
  24245. this.matrix = object.matrixWorld;
  24246. this.matrixAutoUpdate = false;
  24247. this.update();
  24248. }
  24249. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24250. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24251. SkeletonHelper.prototype.getBoneList = function( object ) {
  24252. var boneList = [];
  24253. if ( object && object.isBone ) {
  24254. boneList.push( object );
  24255. }
  24256. for ( var i = 0; i < object.children.length; i ++ ) {
  24257. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24258. }
  24259. return boneList;
  24260. };
  24261. SkeletonHelper.prototype.update = function () {
  24262. var vector = new Vector3();
  24263. var boneMatrix = new Matrix4();
  24264. var matrixWorldInv = new Matrix4();
  24265. return function update() {
  24266. var geometry = this.geometry;
  24267. var position = geometry.getAttribute( 'position' );
  24268. matrixWorldInv.getInverse( this.root.matrixWorld );
  24269. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24270. var bone = this.bones[ i ];
  24271. if ( bone.parent && bone.parent.isBone ) {
  24272. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24273. vector.setFromMatrixPosition( boneMatrix );
  24274. position.setXYZ( j, vector.x, vector.y, vector.z );
  24275. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24276. vector.setFromMatrixPosition( boneMatrix );
  24277. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24278. j += 2;
  24279. }
  24280. }
  24281. geometry.getAttribute( 'position' ).needsUpdate = true;
  24282. };
  24283. }();
  24284. /**
  24285. * @author alteredq / http://alteredqualia.com/
  24286. * @author mrdoob / http://mrdoob.com/
  24287. */
  24288. function PointLightHelper( light, sphereSize ) {
  24289. this.light = light;
  24290. this.light.updateMatrixWorld();
  24291. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24292. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24293. material.color.copy( this.light.color );
  24294. Mesh.call( this, geometry, material );
  24295. this.matrix = this.light.matrixWorld;
  24296. this.matrixAutoUpdate = false;
  24297. /*
  24298. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24299. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24300. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24301. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24302. var d = light.distance;
  24303. if ( d === 0.0 ) {
  24304. this.lightDistance.visible = false;
  24305. } else {
  24306. this.lightDistance.scale.set( d, d, d );
  24307. }
  24308. this.add( this.lightDistance );
  24309. */
  24310. }
  24311. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24312. PointLightHelper.prototype.constructor = PointLightHelper;
  24313. PointLightHelper.prototype.dispose = function () {
  24314. this.geometry.dispose();
  24315. this.material.dispose();
  24316. };
  24317. PointLightHelper.prototype.update = function () {
  24318. this.material.color.copy( this.light.color );
  24319. /*
  24320. var d = this.light.distance;
  24321. if ( d === 0.0 ) {
  24322. this.lightDistance.visible = false;
  24323. } else {
  24324. this.lightDistance.visible = true;
  24325. this.lightDistance.scale.set( d, d, d );
  24326. }
  24327. */
  24328. };
  24329. /**
  24330. * @author abelnation / http://github.com/abelnation
  24331. * @author Mugen87 / http://github.com/Mugen87
  24332. * @author WestLangley / http://github.com/WestLangley
  24333. */
  24334. function RectAreaLightHelper( light ) {
  24335. Object3D.call( this );
  24336. this.light = light;
  24337. this.light.updateMatrixWorld();
  24338. this.matrix = light.matrixWorld;
  24339. this.matrixAutoUpdate = false;
  24340. var material = new LineBasicMaterial( { color: light.color } );
  24341. var geometry = new BufferGeometry();
  24342. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24343. this.add( new Line( geometry, material ) );
  24344. this.update();
  24345. }
  24346. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24347. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24348. RectAreaLightHelper.prototype.dispose = function () {
  24349. this.children[ 0 ].geometry.dispose();
  24350. this.children[ 0 ].material.dispose();
  24351. };
  24352. RectAreaLightHelper.prototype.update = function () {
  24353. var line = this.children[ 0 ];
  24354. // update material
  24355. line.material.color.copy( this.light.color );
  24356. // calculate new dimensions of the helper
  24357. var hx = this.light.width * 0.5;
  24358. var hy = this.light.height * 0.5;
  24359. var position = line.geometry.attributes.position;
  24360. var array = position.array;
  24361. // update vertices
  24362. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24363. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24364. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24365. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24366. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24367. position.needsUpdate = true;
  24368. };
  24369. /**
  24370. * @author alteredq / http://alteredqualia.com/
  24371. * @author mrdoob / http://mrdoob.com/
  24372. * @author Mugen87 / https://github.com/Mugen87
  24373. */
  24374. function HemisphereLightHelper( light, size ) {
  24375. Object3D.call( this );
  24376. this.light = light;
  24377. this.light.updateMatrixWorld();
  24378. this.matrix = light.matrixWorld;
  24379. this.matrixAutoUpdate = false;
  24380. var geometry = new OctahedronBufferGeometry( size );
  24381. geometry.rotateY( Math.PI * 0.5 );
  24382. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24383. var position = geometry.getAttribute( 'position' );
  24384. var colors = new Float32Array( position.count * 3 );
  24385. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24386. this.add( new Mesh( geometry, material ) );
  24387. this.update();
  24388. }
  24389. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24390. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24391. HemisphereLightHelper.prototype.dispose = function () {
  24392. this.children[ 0 ].geometry.dispose();
  24393. this.children[ 0 ].material.dispose();
  24394. };
  24395. HemisphereLightHelper.prototype.update = function () {
  24396. var vector = new Vector3();
  24397. var color1 = new Color();
  24398. var color2 = new Color();
  24399. return function update() {
  24400. var mesh = this.children[ 0 ];
  24401. var colors = mesh.geometry.getAttribute( 'color' );
  24402. color1.copy( this.light.color );
  24403. color2.copy( this.light.groundColor );
  24404. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24405. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24406. colors.setXYZ( i, color.r, color.g, color.b );
  24407. }
  24408. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24409. colors.needsUpdate = true;
  24410. };
  24411. }();
  24412. /**
  24413. * @author mrdoob / http://mrdoob.com/
  24414. */
  24415. function GridHelper( size, divisions, color1, color2 ) {
  24416. size = size || 10;
  24417. divisions = divisions || 10;
  24418. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24419. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24420. var center = divisions / 2;
  24421. var step = size / divisions;
  24422. var halfSize = size / 2;
  24423. var vertices = [], colors = [];
  24424. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24425. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24426. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24427. var color = i === center ? color1 : color2;
  24428. color.toArray( colors, j ); j += 3;
  24429. color.toArray( colors, j ); j += 3;
  24430. color.toArray( colors, j ); j += 3;
  24431. color.toArray( colors, j ); j += 3;
  24432. }
  24433. var geometry = new BufferGeometry();
  24434. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24435. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24436. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24437. LineSegments.call( this, geometry, material );
  24438. }
  24439. GridHelper.prototype = Object.create( LineSegments.prototype );
  24440. GridHelper.prototype.constructor = GridHelper;
  24441. /**
  24442. * @author mrdoob / http://mrdoob.com/
  24443. * @author Mugen87 / http://github.com/Mugen87
  24444. * @author Hectate / http://www.github.com/Hectate
  24445. */
  24446. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24447. radius = radius || 10;
  24448. radials = radials || 16;
  24449. circles = circles || 8;
  24450. divisions = divisions || 64;
  24451. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24452. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24453. var vertices = [];
  24454. var colors = [];
  24455. var x, z;
  24456. var v, i, j, r, color;
  24457. // create the radials
  24458. for ( i = 0; i <= radials; i ++ ) {
  24459. v = ( i / radials ) * ( Math.PI * 2 );
  24460. x = Math.sin( v ) * radius;
  24461. z = Math.cos( v ) * radius;
  24462. vertices.push( 0, 0, 0 );
  24463. vertices.push( x, 0, z );
  24464. color = ( i & 1 ) ? color1 : color2;
  24465. colors.push( color.r, color.g, color.b );
  24466. colors.push( color.r, color.g, color.b );
  24467. }
  24468. // create the circles
  24469. for ( i = 0; i <= circles; i ++ ) {
  24470. color = ( i & 1 ) ? color1 : color2;
  24471. r = radius - ( radius / circles * i );
  24472. for ( j = 0; j < divisions; j ++ ) {
  24473. // first vertex
  24474. v = ( j / divisions ) * ( Math.PI * 2 );
  24475. x = Math.sin( v ) * r;
  24476. z = Math.cos( v ) * r;
  24477. vertices.push( x, 0, z );
  24478. colors.push( color.r, color.g, color.b );
  24479. // second vertex
  24480. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24481. x = Math.sin( v ) * r;
  24482. z = Math.cos( v ) * r;
  24483. vertices.push( x, 0, z );
  24484. colors.push( color.r, color.g, color.b );
  24485. }
  24486. }
  24487. var geometry = new BufferGeometry();
  24488. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24489. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24490. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24491. LineSegments.call( this, geometry, material );
  24492. }
  24493. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24494. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24495. /**
  24496. * @author mrdoob / http://mrdoob.com/
  24497. * @author WestLangley / http://github.com/WestLangley
  24498. */
  24499. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24500. // FaceNormalsHelper only supports THREE.Geometry
  24501. this.object = object;
  24502. this.size = ( size !== undefined ) ? size : 1;
  24503. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24504. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24505. //
  24506. var nNormals = 0;
  24507. var objGeometry = this.object.geometry;
  24508. if ( objGeometry && objGeometry.isGeometry ) {
  24509. nNormals = objGeometry.faces.length;
  24510. } else {
  24511. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24512. }
  24513. //
  24514. var geometry = new BufferGeometry();
  24515. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24516. geometry.addAttribute( 'position', positions );
  24517. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24518. //
  24519. this.matrixAutoUpdate = false;
  24520. this.update();
  24521. }
  24522. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24523. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24524. FaceNormalsHelper.prototype.update = ( function () {
  24525. var v1 = new Vector3();
  24526. var v2 = new Vector3();
  24527. var normalMatrix = new Matrix3();
  24528. return function update() {
  24529. this.object.updateMatrixWorld( true );
  24530. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24531. var matrixWorld = this.object.matrixWorld;
  24532. var position = this.geometry.attributes.position;
  24533. //
  24534. var objGeometry = this.object.geometry;
  24535. var vertices = objGeometry.vertices;
  24536. var faces = objGeometry.faces;
  24537. var idx = 0;
  24538. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24539. var face = faces[ i ];
  24540. var normal = face.normal;
  24541. v1.copy( vertices[ face.a ] )
  24542. .add( vertices[ face.b ] )
  24543. .add( vertices[ face.c ] )
  24544. .divideScalar( 3 )
  24545. .applyMatrix4( matrixWorld );
  24546. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24547. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24548. idx = idx + 1;
  24549. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24550. idx = idx + 1;
  24551. }
  24552. position.needsUpdate = true;
  24553. };
  24554. }() );
  24555. /**
  24556. * @author alteredq / http://alteredqualia.com/
  24557. * @author mrdoob / http://mrdoob.com/
  24558. * @author WestLangley / http://github.com/WestLangley
  24559. */
  24560. function DirectionalLightHelper( light, size ) {
  24561. Object3D.call( this );
  24562. this.light = light;
  24563. this.light.updateMatrixWorld();
  24564. this.matrix = light.matrixWorld;
  24565. this.matrixAutoUpdate = false;
  24566. if ( size === undefined ) size = 1;
  24567. var geometry = new BufferGeometry();
  24568. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24569. - size, size, 0,
  24570. size, size, 0,
  24571. size, - size, 0,
  24572. - size, - size, 0,
  24573. - size, size, 0
  24574. ], 3 ) );
  24575. var material = new LineBasicMaterial( { fog: false } );
  24576. this.add( new Line( geometry, material ) );
  24577. geometry = new BufferGeometry();
  24578. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24579. this.add( new Line( geometry, material ));
  24580. this.update();
  24581. }
  24582. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24583. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24584. DirectionalLightHelper.prototype.dispose = function () {
  24585. var lightPlane = this.children[ 0 ];
  24586. var targetLine = this.children[ 1 ];
  24587. lightPlane.geometry.dispose();
  24588. lightPlane.material.dispose();
  24589. targetLine.geometry.dispose();
  24590. targetLine.material.dispose();
  24591. };
  24592. DirectionalLightHelper.prototype.update = function () {
  24593. var v1 = new Vector3();
  24594. var v2 = new Vector3();
  24595. var v3 = new Vector3();
  24596. return function update() {
  24597. v1.setFromMatrixPosition( this.light.matrixWorld );
  24598. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24599. v3.subVectors( v2, v1 );
  24600. var lightPlane = this.children[ 0 ];
  24601. var targetLine = this.children[ 1 ];
  24602. lightPlane.lookAt( v3 );
  24603. lightPlane.material.color.copy( this.light.color );
  24604. targetLine.lookAt( v3 );
  24605. targetLine.scale.z = v3.length();
  24606. };
  24607. }();
  24608. /**
  24609. * @author alteredq / http://alteredqualia.com/
  24610. * @author Mugen87 / https://github.com/Mugen87
  24611. *
  24612. * - shows frustum, line of sight and up of the camera
  24613. * - suitable for fast updates
  24614. * - based on frustum visualization in lightgl.js shadowmap example
  24615. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24616. */
  24617. function CameraHelper( camera ) {
  24618. var geometry = new BufferGeometry();
  24619. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24620. var vertices = [];
  24621. var colors = [];
  24622. var pointMap = {};
  24623. // colors
  24624. var colorFrustum = new Color( 0xffaa00 );
  24625. var colorCone = new Color( 0xff0000 );
  24626. var colorUp = new Color( 0x00aaff );
  24627. var colorTarget = new Color( 0xffffff );
  24628. var colorCross = new Color( 0x333333 );
  24629. // near
  24630. addLine( "n1", "n2", colorFrustum );
  24631. addLine( "n2", "n4", colorFrustum );
  24632. addLine( "n4", "n3", colorFrustum );
  24633. addLine( "n3", "n1", colorFrustum );
  24634. // far
  24635. addLine( "f1", "f2", colorFrustum );
  24636. addLine( "f2", "f4", colorFrustum );
  24637. addLine( "f4", "f3", colorFrustum );
  24638. addLine( "f3", "f1", colorFrustum );
  24639. // sides
  24640. addLine( "n1", "f1", colorFrustum );
  24641. addLine( "n2", "f2", colorFrustum );
  24642. addLine( "n3", "f3", colorFrustum );
  24643. addLine( "n4", "f4", colorFrustum );
  24644. // cone
  24645. addLine( "p", "n1", colorCone );
  24646. addLine( "p", "n2", colorCone );
  24647. addLine( "p", "n3", colorCone );
  24648. addLine( "p", "n4", colorCone );
  24649. // up
  24650. addLine( "u1", "u2", colorUp );
  24651. addLine( "u2", "u3", colorUp );
  24652. addLine( "u3", "u1", colorUp );
  24653. // target
  24654. addLine( "c", "t", colorTarget );
  24655. addLine( "p", "c", colorCross );
  24656. // cross
  24657. addLine( "cn1", "cn2", colorCross );
  24658. addLine( "cn3", "cn4", colorCross );
  24659. addLine( "cf1", "cf2", colorCross );
  24660. addLine( "cf3", "cf4", colorCross );
  24661. function addLine( a, b, color ) {
  24662. addPoint( a, color );
  24663. addPoint( b, color );
  24664. }
  24665. function addPoint( id, color ) {
  24666. vertices.push( 0, 0, 0 );
  24667. colors.push( color.r, color.g, color.b );
  24668. if ( pointMap[ id ] === undefined ) {
  24669. pointMap[ id ] = [];
  24670. }
  24671. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24672. }
  24673. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24674. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24675. LineSegments.call( this, geometry, material );
  24676. this.camera = camera;
  24677. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24678. this.matrix = camera.matrixWorld;
  24679. this.matrixAutoUpdate = false;
  24680. this.pointMap = pointMap;
  24681. this.update();
  24682. }
  24683. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24684. CameraHelper.prototype.constructor = CameraHelper;
  24685. CameraHelper.prototype.update = function () {
  24686. var geometry, pointMap;
  24687. var vector = new Vector3();
  24688. var camera = new Camera();
  24689. function setPoint( point, x, y, z ) {
  24690. vector.set( x, y, z ).unproject( camera );
  24691. var points = pointMap[ point ];
  24692. if ( points !== undefined ) {
  24693. var position = geometry.getAttribute( 'position' );
  24694. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24695. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24696. }
  24697. }
  24698. }
  24699. return function update() {
  24700. geometry = this.geometry;
  24701. pointMap = this.pointMap;
  24702. var w = 1, h = 1;
  24703. // we need just camera projection matrix
  24704. // world matrix must be identity
  24705. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24706. // center / target
  24707. setPoint( "c", 0, 0, - 1 );
  24708. setPoint( "t", 0, 0, 1 );
  24709. // near
  24710. setPoint( "n1", - w, - h, - 1 );
  24711. setPoint( "n2", w, - h, - 1 );
  24712. setPoint( "n3", - w, h, - 1 );
  24713. setPoint( "n4", w, h, - 1 );
  24714. // far
  24715. setPoint( "f1", - w, - h, 1 );
  24716. setPoint( "f2", w, - h, 1 );
  24717. setPoint( "f3", - w, h, 1 );
  24718. setPoint( "f4", w, h, 1 );
  24719. // up
  24720. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24721. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24722. setPoint( "u3", 0, h * 2, - 1 );
  24723. // cross
  24724. setPoint( "cf1", - w, 0, 1 );
  24725. setPoint( "cf2", w, 0, 1 );
  24726. setPoint( "cf3", 0, - h, 1 );
  24727. setPoint( "cf4", 0, h, 1 );
  24728. setPoint( "cn1", - w, 0, - 1 );
  24729. setPoint( "cn2", w, 0, - 1 );
  24730. setPoint( "cn3", 0, - h, - 1 );
  24731. setPoint( "cn4", 0, h, - 1 );
  24732. geometry.getAttribute( 'position' ).needsUpdate = true;
  24733. };
  24734. }();
  24735. /**
  24736. * @author mrdoob / http://mrdoob.com/
  24737. * @author Mugen87 / http://github.com/Mugen87
  24738. */
  24739. function BoxHelper( object, color ) {
  24740. this.object = object;
  24741. if ( color === undefined ) color = 0xffff00;
  24742. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  24743. var positions = new Float32Array( 8 * 3 );
  24744. var geometry = new BufferGeometry();
  24745. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24746. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24747. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24748. this.matrixAutoUpdate = false;
  24749. this.update();
  24750. }
  24751. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24752. BoxHelper.prototype.constructor = BoxHelper;
  24753. BoxHelper.prototype.update = ( function () {
  24754. var box = new Box3();
  24755. return function update( object ) {
  24756. if ( object !== undefined ) {
  24757. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  24758. }
  24759. if ( this.object !== undefined ) {
  24760. box.setFromObject( this.object );
  24761. }
  24762. if ( box.isEmpty() ) return;
  24763. var min = box.min;
  24764. var max = box.max;
  24765. /*
  24766. 5____4
  24767. 1/___0/|
  24768. | 6__|_7
  24769. 2/___3/
  24770. 0: max.x, max.y, max.z
  24771. 1: min.x, max.y, max.z
  24772. 2: min.x, min.y, max.z
  24773. 3: max.x, min.y, max.z
  24774. 4: max.x, max.y, min.z
  24775. 5: min.x, max.y, min.z
  24776. 6: min.x, min.y, min.z
  24777. 7: max.x, min.y, min.z
  24778. */
  24779. var position = this.geometry.attributes.position;
  24780. var array = position.array;
  24781. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24782. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24783. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24784. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24785. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24786. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24787. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24788. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24789. position.needsUpdate = true;
  24790. this.geometry.computeBoundingSphere();
  24791. };
  24792. } )();
  24793. BoxHelper.prototype.setFromObject = function ( object ) {
  24794. this.object = object;
  24795. this.update();
  24796. return this;
  24797. };
  24798. /**
  24799. * @author WestLangley / http://github.com/WestLangley
  24800. * @author zz85 / http://github.com/zz85
  24801. * @author bhouston / http://clara.io
  24802. *
  24803. * Creates an arrow for visualizing directions
  24804. *
  24805. * Parameters:
  24806. * dir - Vector3
  24807. * origin - Vector3
  24808. * length - Number
  24809. * color - color in hex value
  24810. * headLength - Number
  24811. * headWidth - Number
  24812. */
  24813. var lineGeometry;
  24814. var coneGeometry;
  24815. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24816. // dir is assumed to be normalized
  24817. Object3D.call( this );
  24818. if ( color === undefined ) color = 0xffff00;
  24819. if ( length === undefined ) length = 1;
  24820. if ( headLength === undefined ) headLength = 0.2 * length;
  24821. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24822. if ( lineGeometry === undefined ) {
  24823. lineGeometry = new BufferGeometry();
  24824. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24825. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24826. coneGeometry.translate( 0, - 0.5, 0 );
  24827. }
  24828. this.position.copy( origin );
  24829. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24830. this.line.matrixAutoUpdate = false;
  24831. this.add( this.line );
  24832. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24833. this.cone.matrixAutoUpdate = false;
  24834. this.add( this.cone );
  24835. this.setDirection( dir );
  24836. this.setLength( length, headLength, headWidth );
  24837. }
  24838. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24839. ArrowHelper.prototype.constructor = ArrowHelper;
  24840. ArrowHelper.prototype.setDirection = ( function () {
  24841. var axis = new Vector3();
  24842. var radians;
  24843. return function setDirection( dir ) {
  24844. // dir is assumed to be normalized
  24845. if ( dir.y > 0.99999 ) {
  24846. this.quaternion.set( 0, 0, 0, 1 );
  24847. } else if ( dir.y < - 0.99999 ) {
  24848. this.quaternion.set( 1, 0, 0, 0 );
  24849. } else {
  24850. axis.set( dir.z, 0, - dir.x ).normalize();
  24851. radians = Math.acos( dir.y );
  24852. this.quaternion.setFromAxisAngle( axis, radians );
  24853. }
  24854. };
  24855. }() );
  24856. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24857. if ( headLength === undefined ) headLength = 0.2 * length;
  24858. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24859. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24860. this.line.updateMatrix();
  24861. this.cone.scale.set( headWidth, headLength, headWidth );
  24862. this.cone.position.y = length;
  24863. this.cone.updateMatrix();
  24864. };
  24865. ArrowHelper.prototype.setColor = function ( color ) {
  24866. this.line.material.color.copy( color );
  24867. this.cone.material.color.copy( color );
  24868. };
  24869. /**
  24870. * @author sroucheray / http://sroucheray.org/
  24871. * @author mrdoob / http://mrdoob.com/
  24872. */
  24873. function AxisHelper( size ) {
  24874. size = size || 1;
  24875. var vertices = [
  24876. 0, 0, 0, size, 0, 0,
  24877. 0, 0, 0, 0, size, 0,
  24878. 0, 0, 0, 0, 0, size
  24879. ];
  24880. var colors = [
  24881. 1, 0, 0, 1, 0.6, 0,
  24882. 0, 1, 0, 0.6, 1, 0,
  24883. 0, 0, 1, 0, 0.6, 1
  24884. ];
  24885. var geometry = new BufferGeometry();
  24886. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24887. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24888. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24889. LineSegments.call( this, geometry, material );
  24890. }
  24891. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24892. AxisHelper.prototype.constructor = AxisHelper;
  24893. /**
  24894. * @author zz85 https://github.com/zz85
  24895. *
  24896. * Centripetal CatmullRom Curve - which is useful for avoiding
  24897. * cusps and self-intersections in non-uniform catmull rom curves.
  24898. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24899. *
  24900. * curve.type accepts centripetal(default), chordal and catmullrom
  24901. * curve.tension is used for catmullrom which defaults to 0.5
  24902. */
  24903. /*
  24904. Based on an optimized c++ solution in
  24905. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24906. - http://ideone.com/NoEbVM
  24907. This CubicPoly class could be used for reusing some variables and calculations,
  24908. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24909. which can be placed in CurveUtils.
  24910. */
  24911. function CubicPoly() {
  24912. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24913. /*
  24914. * Compute coefficients for a cubic polynomial
  24915. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24916. * such that
  24917. * p(0) = x0, p(1) = x1
  24918. * and
  24919. * p'(0) = t0, p'(1) = t1.
  24920. */
  24921. function init( x0, x1, t0, t1 ) {
  24922. c0 = x0;
  24923. c1 = t0;
  24924. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24925. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24926. }
  24927. return {
  24928. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24929. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24930. },
  24931. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24932. // compute tangents when parameterized in [t1,t2]
  24933. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24934. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24935. // rescale tangents for parametrization in [0,1]
  24936. t1 *= dt1;
  24937. t2 *= dt1;
  24938. init( x1, x2, t1, t2 );
  24939. },
  24940. calc: function ( t ) {
  24941. var t2 = t * t;
  24942. var t3 = t2 * t;
  24943. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24944. }
  24945. };
  24946. }
  24947. //
  24948. var tmp = new Vector3();
  24949. var px = new CubicPoly();
  24950. var py = new CubicPoly();
  24951. var pz = new CubicPoly();
  24952. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  24953. Curve.call( this );
  24954. this.points = p || [];
  24955. this.closed = false;
  24956. }
  24957. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  24958. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  24959. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  24960. var points = this.points;
  24961. var l = points.length;
  24962. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24963. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24964. var intPoint = Math.floor( point );
  24965. var weight = point - intPoint;
  24966. if ( this.closed ) {
  24967. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24968. } else if ( weight === 0 && intPoint === l - 1 ) {
  24969. intPoint = l - 2;
  24970. weight = 1;
  24971. }
  24972. var p0, p1, p2, p3; // 4 points
  24973. if ( this.closed || intPoint > 0 ) {
  24974. p0 = points[ ( intPoint - 1 ) % l ];
  24975. } else {
  24976. // extrapolate first point
  24977. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24978. p0 = tmp;
  24979. }
  24980. p1 = points[ intPoint % l ];
  24981. p2 = points[ ( intPoint + 1 ) % l ];
  24982. if ( this.closed || intPoint + 2 < l ) {
  24983. p3 = points[ ( intPoint + 2 ) % l ];
  24984. } else {
  24985. // extrapolate last point
  24986. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24987. p3 = tmp;
  24988. }
  24989. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24990. // init Centripetal / Chordal Catmull-Rom
  24991. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24992. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24993. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24994. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24995. // safety check for repeated points
  24996. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24997. if ( dt0 < 1e-4 ) dt0 = dt1;
  24998. if ( dt2 < 1e-4 ) dt2 = dt1;
  24999. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25000. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25001. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25002. } else if ( this.type === 'catmullrom' ) {
  25003. var tension = this.tension !== undefined ? this.tension : 0.5;
  25004. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25005. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25006. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25007. }
  25008. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25009. };
  25010. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25011. Curve.call( this );
  25012. this.v0 = v0;
  25013. this.v1 = v1;
  25014. this.v2 = v2;
  25015. this.v3 = v3;
  25016. }
  25017. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25018. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25019. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25020. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25021. return new Vector3(
  25022. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25023. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25024. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25025. );
  25026. };
  25027. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25028. Curve.call( this );
  25029. this.v0 = v0;
  25030. this.v1 = v1;
  25031. this.v2 = v2;
  25032. }
  25033. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25034. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25035. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25036. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25037. return new Vector3(
  25038. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25039. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25040. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25041. );
  25042. };
  25043. function LineCurve3( v1, v2 ) {
  25044. Curve.call( this );
  25045. this.v1 = v1;
  25046. this.v2 = v2;
  25047. }
  25048. LineCurve3.prototype = Object.create( Curve.prototype );
  25049. LineCurve3.prototype.constructor = LineCurve3;
  25050. LineCurve3.prototype.getPoint = function ( t ) {
  25051. if ( t === 1 ) {
  25052. return this.v2.clone();
  25053. }
  25054. var vector = new Vector3();
  25055. vector.subVectors( this.v2, this.v1 ); // diff
  25056. vector.multiplyScalar( t );
  25057. vector.add( this.v1 );
  25058. return vector;
  25059. };
  25060. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25061. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25062. }
  25063. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25064. ArcCurve.prototype.constructor = ArcCurve;
  25065. /**
  25066. * @author alteredq / http://alteredqualia.com/
  25067. */
  25068. var SceneUtils = {
  25069. createMultiMaterialObject: function ( geometry, materials ) {
  25070. var group = new Group();
  25071. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25072. group.add( new Mesh( geometry, materials[ i ] ) );
  25073. }
  25074. return group;
  25075. },
  25076. detach: function ( child, parent, scene ) {
  25077. child.applyMatrix( parent.matrixWorld );
  25078. parent.remove( child );
  25079. scene.add( child );
  25080. },
  25081. attach: function ( child, scene, parent ) {
  25082. var matrixWorldInverse = new Matrix4();
  25083. matrixWorldInverse.getInverse( parent.matrixWorld );
  25084. child.applyMatrix( matrixWorldInverse );
  25085. scene.remove( child );
  25086. parent.add( child );
  25087. }
  25088. };
  25089. /**
  25090. * @author mrdoob / http://mrdoob.com/
  25091. */
  25092. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25093. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25094. return new Face3( a, b, c, normal, color, materialIndex );
  25095. }
  25096. var LineStrip = 0;
  25097. var LinePieces = 1;
  25098. function MeshFaceMaterial( materials ) {
  25099. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25100. return materials;
  25101. }
  25102. function MultiMaterial( materials ) {
  25103. if ( materials === undefined ) materials = [];
  25104. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25105. materials.isMultiMaterial = true;
  25106. materials.materials = materials;
  25107. materials.clone = function () {
  25108. return materials.slice();
  25109. };
  25110. return materials;
  25111. }
  25112. function PointCloud( geometry, material ) {
  25113. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25114. return new Points( geometry, material );
  25115. }
  25116. function Particle( material ) {
  25117. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25118. return new Sprite( material );
  25119. }
  25120. function ParticleSystem( geometry, material ) {
  25121. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25122. return new Points( geometry, material );
  25123. }
  25124. function PointCloudMaterial( parameters ) {
  25125. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25126. return new PointsMaterial( parameters );
  25127. }
  25128. function ParticleBasicMaterial( parameters ) {
  25129. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25130. return new PointsMaterial( parameters );
  25131. }
  25132. function ParticleSystemMaterial( parameters ) {
  25133. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25134. return new PointsMaterial( parameters );
  25135. }
  25136. function Vertex( x, y, z ) {
  25137. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25138. return new Vector3( x, y, z );
  25139. }
  25140. //
  25141. function DynamicBufferAttribute( array, itemSize ) {
  25142. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25143. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25144. }
  25145. function Int8Attribute( array, itemSize ) {
  25146. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25147. return new Int8BufferAttribute( array, itemSize );
  25148. }
  25149. function Uint8Attribute( array, itemSize ) {
  25150. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25151. return new Uint8BufferAttribute( array, itemSize );
  25152. }
  25153. function Uint8ClampedAttribute( array, itemSize ) {
  25154. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25155. return new Uint8ClampedBufferAttribute( array, itemSize );
  25156. }
  25157. function Int16Attribute( array, itemSize ) {
  25158. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25159. return new Int16BufferAttribute( array, itemSize );
  25160. }
  25161. function Uint16Attribute( array, itemSize ) {
  25162. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25163. return new Uint16BufferAttribute( array, itemSize );
  25164. }
  25165. function Int32Attribute( array, itemSize ) {
  25166. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25167. return new Int32BufferAttribute( array, itemSize );
  25168. }
  25169. function Uint32Attribute( array, itemSize ) {
  25170. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25171. return new Uint32BufferAttribute( array, itemSize );
  25172. }
  25173. function Float32Attribute( array, itemSize ) {
  25174. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25175. return new Float32BufferAttribute( array, itemSize );
  25176. }
  25177. function Float64Attribute( array, itemSize ) {
  25178. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25179. return new Float64BufferAttribute( array, itemSize );
  25180. }
  25181. //
  25182. Curve.create = function ( construct, getPoint ) {
  25183. console.log( 'THREE.Curve.create() has been deprecated' );
  25184. construct.prototype = Object.create( Curve.prototype );
  25185. construct.prototype.constructor = construct;
  25186. construct.prototype.getPoint = getPoint;
  25187. return construct;
  25188. };
  25189. //
  25190. function ClosedSplineCurve3( points ) {
  25191. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25192. CatmullRomCurve3.call( this, points );
  25193. this.type = 'catmullrom';
  25194. this.closed = true;
  25195. }
  25196. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25197. //
  25198. function SplineCurve3( points ) {
  25199. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25200. CatmullRomCurve3.call( this, points );
  25201. this.type = 'catmullrom';
  25202. }
  25203. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25204. //
  25205. function Spline( points ) {
  25206. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25207. CatmullRomCurve3.call( this, points );
  25208. this.type = 'catmullrom';
  25209. }
  25210. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25211. Object.assign( Spline.prototype, {
  25212. initFromArray: function ( a ) {
  25213. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25214. },
  25215. getControlPointsArray: function ( optionalTarget ) {
  25216. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25217. },
  25218. reparametrizeByArcLength: function ( samplingCoef ) {
  25219. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25220. }
  25221. } );
  25222. //
  25223. function BoundingBoxHelper( object, color ) {
  25224. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25225. return new BoxHelper( object, color );
  25226. }
  25227. function EdgesHelper( object, hex ) {
  25228. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25229. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25230. }
  25231. GridHelper.prototype.setColors = function () {
  25232. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25233. };
  25234. function WireframeHelper( object, hex ) {
  25235. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25236. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25237. }
  25238. //
  25239. function XHRLoader( manager ) {
  25240. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25241. return new FileLoader( manager );
  25242. }
  25243. function BinaryTextureLoader( manager ) {
  25244. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25245. return new DataTextureLoader( manager );
  25246. }
  25247. //
  25248. Object.assign( Box2.prototype, {
  25249. center: function ( optionalTarget ) {
  25250. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25251. return this.getCenter( optionalTarget );
  25252. },
  25253. empty: function () {
  25254. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25255. return this.isEmpty();
  25256. },
  25257. isIntersectionBox: function ( box ) {
  25258. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25259. return this.intersectsBox( box );
  25260. },
  25261. size: function ( optionalTarget ) {
  25262. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25263. return this.getSize( optionalTarget );
  25264. }
  25265. } );
  25266. Object.assign( Box3.prototype, {
  25267. center: function ( optionalTarget ) {
  25268. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25269. return this.getCenter( optionalTarget );
  25270. },
  25271. empty: function () {
  25272. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25273. return this.isEmpty();
  25274. },
  25275. isIntersectionBox: function ( box ) {
  25276. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25277. return this.intersectsBox( box );
  25278. },
  25279. isIntersectionSphere: function ( sphere ) {
  25280. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25281. return this.intersectsSphere( sphere );
  25282. },
  25283. size: function ( optionalTarget ) {
  25284. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25285. return this.getSize( optionalTarget );
  25286. }
  25287. } );
  25288. Line3.prototype.center = function ( optionalTarget ) {
  25289. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25290. return this.getCenter( optionalTarget );
  25291. };
  25292. _Math.random16 = function () {
  25293. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25294. return Math.random();
  25295. };
  25296. Object.assign( Matrix3.prototype, {
  25297. flattenToArrayOffset: function ( array, offset ) {
  25298. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25299. return this.toArray( array, offset );
  25300. },
  25301. multiplyVector3: function ( vector ) {
  25302. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25303. return vector.applyMatrix3( this );
  25304. },
  25305. multiplyVector3Array: function ( a ) {
  25306. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25307. return this.applyToVector3Array( a );
  25308. },
  25309. applyToBuffer: function( buffer, offset, length ) {
  25310. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25311. return this.applyToBufferAttribute( buffer );
  25312. },
  25313. applyToVector3Array: function( array, offset, length ) {
  25314. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25315. }
  25316. } );
  25317. Object.assign( Matrix4.prototype, {
  25318. extractPosition: function ( m ) {
  25319. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25320. return this.copyPosition( m );
  25321. },
  25322. flattenToArrayOffset: function ( array, offset ) {
  25323. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25324. return this.toArray( array, offset );
  25325. },
  25326. getPosition: function () {
  25327. var v1;
  25328. return function getPosition() {
  25329. if ( v1 === undefined ) v1 = new Vector3();
  25330. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25331. return v1.setFromMatrixColumn( this, 3 );
  25332. };
  25333. }(),
  25334. setRotationFromQuaternion: function ( q ) {
  25335. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25336. return this.makeRotationFromQuaternion( q );
  25337. },
  25338. multiplyToArray: function () {
  25339. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25340. },
  25341. multiplyVector3: function ( vector ) {
  25342. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25343. return vector.applyMatrix4( this );
  25344. },
  25345. multiplyVector4: function ( vector ) {
  25346. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25347. return vector.applyMatrix4( this );
  25348. },
  25349. multiplyVector3Array: function ( a ) {
  25350. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25351. return this.applyToVector3Array( a );
  25352. },
  25353. rotateAxis: function ( v ) {
  25354. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25355. v.transformDirection( this );
  25356. },
  25357. crossVector: function ( vector ) {
  25358. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25359. return vector.applyMatrix4( this );
  25360. },
  25361. translate: function () {
  25362. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25363. },
  25364. rotateX: function () {
  25365. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25366. },
  25367. rotateY: function () {
  25368. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25369. },
  25370. rotateZ: function () {
  25371. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25372. },
  25373. rotateByAxis: function () {
  25374. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25375. },
  25376. applyToBuffer: function( buffer, offset, length ) {
  25377. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25378. return this.applyToBufferAttribute( buffer );
  25379. },
  25380. applyToVector3Array: function( array, offset, length ) {
  25381. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25382. },
  25383. makeFrustum: function( left, right, bottom, top, near, far ) {
  25384. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25385. return this.makePerspective( left, right, top, bottom, near, far );
  25386. }
  25387. } );
  25388. Plane.prototype.isIntersectionLine = function ( line ) {
  25389. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25390. return this.intersectsLine( line );
  25391. };
  25392. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25393. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25394. return vector.applyQuaternion( this );
  25395. };
  25396. Object.assign( Ray.prototype, {
  25397. isIntersectionBox: function ( box ) {
  25398. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25399. return this.intersectsBox( box );
  25400. },
  25401. isIntersectionPlane: function ( plane ) {
  25402. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25403. return this.intersectsPlane( plane );
  25404. },
  25405. isIntersectionSphere: function ( sphere ) {
  25406. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25407. return this.intersectsSphere( sphere );
  25408. }
  25409. } );
  25410. Object.assign( Shape.prototype, {
  25411. extrude: function ( options ) {
  25412. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25413. return new ExtrudeGeometry( this, options );
  25414. },
  25415. makeGeometry: function ( options ) {
  25416. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25417. return new ShapeGeometry( this, options );
  25418. }
  25419. } );
  25420. Object.assign( Vector2.prototype, {
  25421. fromAttribute: function ( attribute, index, offset ) {
  25422. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25423. return this.fromBufferAttribute( attribute, index, offset );
  25424. }
  25425. } );
  25426. Object.assign( Vector3.prototype, {
  25427. setEulerFromRotationMatrix: function () {
  25428. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25429. },
  25430. setEulerFromQuaternion: function () {
  25431. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25432. },
  25433. getPositionFromMatrix: function ( m ) {
  25434. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25435. return this.setFromMatrixPosition( m );
  25436. },
  25437. getScaleFromMatrix: function ( m ) {
  25438. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25439. return this.setFromMatrixScale( m );
  25440. },
  25441. getColumnFromMatrix: function ( index, matrix ) {
  25442. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25443. return this.setFromMatrixColumn( matrix, index );
  25444. },
  25445. applyProjection: function ( m ) {
  25446. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25447. return this.applyMatrix4( m );
  25448. },
  25449. fromAttribute: function ( attribute, index, offset ) {
  25450. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25451. return this.fromBufferAttribute( attribute, index, offset );
  25452. }
  25453. } );
  25454. Object.assign( Vector4.prototype, {
  25455. fromAttribute: function ( attribute, index, offset ) {
  25456. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25457. return this.fromBufferAttribute( attribute, index, offset );
  25458. }
  25459. } );
  25460. //
  25461. Geometry.prototype.computeTangents = function () {
  25462. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25463. };
  25464. Object.assign( Object3D.prototype, {
  25465. getChildByName: function ( name ) {
  25466. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25467. return this.getObjectByName( name );
  25468. },
  25469. renderDepth: function () {
  25470. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25471. },
  25472. translate: function ( distance, axis ) {
  25473. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25474. return this.translateOnAxis( axis, distance );
  25475. }
  25476. } );
  25477. Object.defineProperties( Object3D.prototype, {
  25478. eulerOrder: {
  25479. get: function () {
  25480. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25481. return this.rotation.order;
  25482. },
  25483. set: function ( value ) {
  25484. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25485. this.rotation.order = value;
  25486. }
  25487. },
  25488. useQuaternion: {
  25489. get: function () {
  25490. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25491. },
  25492. set: function () {
  25493. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25494. }
  25495. }
  25496. } );
  25497. Object.defineProperties( LOD.prototype, {
  25498. objects: {
  25499. get: function () {
  25500. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25501. return this.levels;
  25502. }
  25503. }
  25504. } );
  25505. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25506. get: function () {
  25507. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25508. },
  25509. set: function () {
  25510. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25511. }
  25512. } );
  25513. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25514. get: function () {
  25515. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25516. return this.arcLengthDivisions;
  25517. },
  25518. set: function ( value ) {
  25519. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25520. this.arcLengthDivisions = value;
  25521. }
  25522. } );
  25523. //
  25524. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25525. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25526. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25527. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25528. this.setFocalLength( focalLength );
  25529. };
  25530. //
  25531. Object.defineProperties( Light.prototype, {
  25532. onlyShadow: {
  25533. set: function () {
  25534. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25535. }
  25536. },
  25537. shadowCameraFov: {
  25538. set: function ( value ) {
  25539. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25540. this.shadow.camera.fov = value;
  25541. }
  25542. },
  25543. shadowCameraLeft: {
  25544. set: function ( value ) {
  25545. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25546. this.shadow.camera.left = value;
  25547. }
  25548. },
  25549. shadowCameraRight: {
  25550. set: function ( value ) {
  25551. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25552. this.shadow.camera.right = value;
  25553. }
  25554. },
  25555. shadowCameraTop: {
  25556. set: function ( value ) {
  25557. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25558. this.shadow.camera.top = value;
  25559. }
  25560. },
  25561. shadowCameraBottom: {
  25562. set: function ( value ) {
  25563. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25564. this.shadow.camera.bottom = value;
  25565. }
  25566. },
  25567. shadowCameraNear: {
  25568. set: function ( value ) {
  25569. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25570. this.shadow.camera.near = value;
  25571. }
  25572. },
  25573. shadowCameraFar: {
  25574. set: function ( value ) {
  25575. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25576. this.shadow.camera.far = value;
  25577. }
  25578. },
  25579. shadowCameraVisible: {
  25580. set: function () {
  25581. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25582. }
  25583. },
  25584. shadowBias: {
  25585. set: function ( value ) {
  25586. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25587. this.shadow.bias = value;
  25588. }
  25589. },
  25590. shadowDarkness: {
  25591. set: function () {
  25592. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25593. }
  25594. },
  25595. shadowMapWidth: {
  25596. set: function ( value ) {
  25597. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25598. this.shadow.mapSize.width = value;
  25599. }
  25600. },
  25601. shadowMapHeight: {
  25602. set: function ( value ) {
  25603. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25604. this.shadow.mapSize.height = value;
  25605. }
  25606. }
  25607. } );
  25608. //
  25609. Object.defineProperties( BufferAttribute.prototype, {
  25610. length: {
  25611. get: function () {
  25612. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25613. return this.array.length;
  25614. }
  25615. }
  25616. } );
  25617. Object.assign( BufferGeometry.prototype, {
  25618. addIndex: function ( index ) {
  25619. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25620. this.setIndex( index );
  25621. },
  25622. addDrawCall: function ( start, count, indexOffset ) {
  25623. if ( indexOffset !== undefined ) {
  25624. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25625. }
  25626. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25627. this.addGroup( start, count );
  25628. },
  25629. clearDrawCalls: function () {
  25630. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25631. this.clearGroups();
  25632. },
  25633. computeTangents: function () {
  25634. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25635. },
  25636. computeOffsets: function () {
  25637. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25638. }
  25639. } );
  25640. Object.defineProperties( BufferGeometry.prototype, {
  25641. drawcalls: {
  25642. get: function () {
  25643. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25644. return this.groups;
  25645. }
  25646. },
  25647. offsets: {
  25648. get: function () {
  25649. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25650. return this.groups;
  25651. }
  25652. }
  25653. } );
  25654. //
  25655. Object.defineProperties( Uniform.prototype, {
  25656. dynamic: {
  25657. set: function () {
  25658. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25659. }
  25660. },
  25661. onUpdate: {
  25662. value: function () {
  25663. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25664. return this;
  25665. }
  25666. }
  25667. } );
  25668. //
  25669. Object.defineProperties( Material.prototype, {
  25670. wrapAround: {
  25671. get: function () {
  25672. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25673. },
  25674. set: function () {
  25675. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25676. }
  25677. },
  25678. wrapRGB: {
  25679. get: function () {
  25680. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25681. return new Color();
  25682. }
  25683. }
  25684. } );
  25685. Object.defineProperties( MeshPhongMaterial.prototype, {
  25686. metal: {
  25687. get: function () {
  25688. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25689. return false;
  25690. },
  25691. set: function () {
  25692. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25693. }
  25694. }
  25695. } );
  25696. Object.defineProperties( ShaderMaterial.prototype, {
  25697. derivatives: {
  25698. get: function () {
  25699. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25700. return this.extensions.derivatives;
  25701. },
  25702. set: function ( value ) {
  25703. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25704. this.extensions.derivatives = value;
  25705. }
  25706. }
  25707. } );
  25708. //
  25709. Object.assign( WebGLRenderer.prototype, {
  25710. getCurrentRenderTarget: function () {
  25711. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  25712. return this.getRenderTarget();
  25713. },
  25714. supportsFloatTextures: function () {
  25715. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25716. return this.extensions.get( 'OES_texture_float' );
  25717. },
  25718. supportsHalfFloatTextures: function () {
  25719. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25720. return this.extensions.get( 'OES_texture_half_float' );
  25721. },
  25722. supportsStandardDerivatives: function () {
  25723. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25724. return this.extensions.get( 'OES_standard_derivatives' );
  25725. },
  25726. supportsCompressedTextureS3TC: function () {
  25727. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25728. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25729. },
  25730. supportsCompressedTexturePVRTC: function () {
  25731. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25732. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25733. },
  25734. supportsBlendMinMax: function () {
  25735. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25736. return this.extensions.get( 'EXT_blend_minmax' );
  25737. },
  25738. supportsVertexTextures: function () {
  25739. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25740. return this.capabilities.vertexTextures;
  25741. },
  25742. supportsInstancedArrays: function () {
  25743. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25744. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25745. },
  25746. enableScissorTest: function ( boolean ) {
  25747. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25748. this.setScissorTest( boolean );
  25749. },
  25750. initMaterial: function () {
  25751. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25752. },
  25753. addPrePlugin: function () {
  25754. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25755. },
  25756. addPostPlugin: function () {
  25757. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25758. },
  25759. updateShadowMap: function () {
  25760. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25761. }
  25762. } );
  25763. Object.defineProperties( WebGLRenderer.prototype, {
  25764. shadowMapEnabled: {
  25765. get: function () {
  25766. return this.shadowMap.enabled;
  25767. },
  25768. set: function ( value ) {
  25769. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25770. this.shadowMap.enabled = value;
  25771. }
  25772. },
  25773. shadowMapType: {
  25774. get: function () {
  25775. return this.shadowMap.type;
  25776. },
  25777. set: function ( value ) {
  25778. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25779. this.shadowMap.type = value;
  25780. }
  25781. },
  25782. shadowMapCullFace: {
  25783. get: function () {
  25784. return this.shadowMap.cullFace;
  25785. },
  25786. set: function ( value ) {
  25787. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25788. this.shadowMap.cullFace = value;
  25789. }
  25790. }
  25791. } );
  25792. Object.defineProperties( WebGLShadowMap.prototype, {
  25793. cullFace: {
  25794. get: function () {
  25795. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25796. },
  25797. set: function ( cullFace ) {
  25798. var value = ( cullFace !== CullFaceBack );
  25799. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25800. this.renderReverseSided = value;
  25801. }
  25802. }
  25803. } );
  25804. //
  25805. Object.defineProperties( WebGLRenderTarget.prototype, {
  25806. wrapS: {
  25807. get: function () {
  25808. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25809. return this.texture.wrapS;
  25810. },
  25811. set: function ( value ) {
  25812. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25813. this.texture.wrapS = value;
  25814. }
  25815. },
  25816. wrapT: {
  25817. get: function () {
  25818. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25819. return this.texture.wrapT;
  25820. },
  25821. set: function ( value ) {
  25822. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25823. this.texture.wrapT = value;
  25824. }
  25825. },
  25826. magFilter: {
  25827. get: function () {
  25828. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25829. return this.texture.magFilter;
  25830. },
  25831. set: function ( value ) {
  25832. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25833. this.texture.magFilter = value;
  25834. }
  25835. },
  25836. minFilter: {
  25837. get: function () {
  25838. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25839. return this.texture.minFilter;
  25840. },
  25841. set: function ( value ) {
  25842. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25843. this.texture.minFilter = value;
  25844. }
  25845. },
  25846. anisotropy: {
  25847. get: function () {
  25848. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25849. return this.texture.anisotropy;
  25850. },
  25851. set: function ( value ) {
  25852. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25853. this.texture.anisotropy = value;
  25854. }
  25855. },
  25856. offset: {
  25857. get: function () {
  25858. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25859. return this.texture.offset;
  25860. },
  25861. set: function ( value ) {
  25862. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25863. this.texture.offset = value;
  25864. }
  25865. },
  25866. repeat: {
  25867. get: function () {
  25868. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25869. return this.texture.repeat;
  25870. },
  25871. set: function ( value ) {
  25872. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25873. this.texture.repeat = value;
  25874. }
  25875. },
  25876. format: {
  25877. get: function () {
  25878. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25879. return this.texture.format;
  25880. },
  25881. set: function ( value ) {
  25882. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25883. this.texture.format = value;
  25884. }
  25885. },
  25886. type: {
  25887. get: function () {
  25888. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25889. return this.texture.type;
  25890. },
  25891. set: function ( value ) {
  25892. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25893. this.texture.type = value;
  25894. }
  25895. },
  25896. generateMipmaps: {
  25897. get: function () {
  25898. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25899. return this.texture.generateMipmaps;
  25900. },
  25901. set: function ( value ) {
  25902. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25903. this.texture.generateMipmaps = value;
  25904. }
  25905. }
  25906. } );
  25907. //
  25908. Audio.prototype.load = function ( file ) {
  25909. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25910. var scope = this;
  25911. var audioLoader = new AudioLoader();
  25912. audioLoader.load( file, function ( buffer ) {
  25913. scope.setBuffer( buffer );
  25914. } );
  25915. return this;
  25916. };
  25917. AudioAnalyser.prototype.getData = function () {
  25918. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25919. return this.getFrequencyData();
  25920. };
  25921. //
  25922. var GeometryUtils = {
  25923. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25924. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25925. var matrix;
  25926. if ( geometry2.isMesh ) {
  25927. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25928. matrix = geometry2.matrix;
  25929. geometry2 = geometry2.geometry;
  25930. }
  25931. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25932. },
  25933. center: function ( geometry ) {
  25934. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25935. return geometry.center();
  25936. }
  25937. };
  25938. var ImageUtils = {
  25939. crossOrigin: undefined,
  25940. loadTexture: function ( url, mapping, onLoad, onError ) {
  25941. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25942. var loader = new TextureLoader();
  25943. loader.setCrossOrigin( this.crossOrigin );
  25944. var texture = loader.load( url, onLoad, undefined, onError );
  25945. if ( mapping ) texture.mapping = mapping;
  25946. return texture;
  25947. },
  25948. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25949. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25950. var loader = new CubeTextureLoader();
  25951. loader.setCrossOrigin( this.crossOrigin );
  25952. var texture = loader.load( urls, onLoad, undefined, onError );
  25953. if ( mapping ) texture.mapping = mapping;
  25954. return texture;
  25955. },
  25956. loadCompressedTexture: function () {
  25957. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25958. },
  25959. loadCompressedTextureCube: function () {
  25960. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25961. }
  25962. };
  25963. //
  25964. function Projector() {
  25965. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25966. this.projectVector = function ( vector, camera ) {
  25967. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25968. vector.project( camera );
  25969. };
  25970. this.unprojectVector = function ( vector, camera ) {
  25971. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25972. vector.unproject( camera );
  25973. };
  25974. this.pickingRay = function () {
  25975. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25976. };
  25977. }
  25978. //
  25979. function CanvasRenderer() {
  25980. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25981. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25982. this.clear = function () {};
  25983. this.render = function () {};
  25984. this.setClearColor = function () {};
  25985. this.setSize = function () {};
  25986. }
  25987. export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, LineLoop, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, DataTextureLoader, CubeTextureLoader, TextureLoader, ObjectLoader, MaterialLoader, BufferGeometryLoader, DefaultLoadingManager, LoadingManager, JSONLoader, ImageLoader, FontLoader, FileLoader, Loader, Cache, AudioLoader, SpotLightShadow, SpotLight, PointLight, RectAreaLight, HemisphereLight, DirectionalLightShadow, DirectionalLight, AmbientLight, LightShadow, Light, StereoCamera, PerspectiveCamera, OrthographicCamera, CubeCamera, ArrayCamera, Camera, AudioListener, PositionalAudio, AudioContext, AudioAnalyser, Audio, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, PropertyMixer, PropertyBinding, KeyframeTrack, AnimationUtils, AnimationObjectGroup, AnimationMixer, AnimationClip, Uniform, InstancedBufferGeometry, BufferGeometry, GeometryIdCount, Geometry, InterleavedBufferAttribute, InstancedInterleavedBuffer, InterleavedBuffer, InstancedBufferAttribute, Face3, Object3D, Raycaster, Layers, EventDispatcher, Clock, QuaternionLinearInterpolant, LinearInterpolant, DiscreteInterpolant, CubicInterpolant, Interpolant, Triangle, _Math as Math, Spherical, Cylindrical, Plane, Frustum, Sphere, Ray, Matrix4, Matrix3, Box3, Box2, Line3, Euler, Vector4, Vector3, Vector2, Quaternion, Color, MorphBlendMesh, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, TextBufferGeometry, SphereGeometry, SphereBufferGeometry, RingGeometry, RingBufferGeometry, PlaneGeometry, PlaneBufferGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, ExtrudeBufferGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleGeometry, CircleBufferGeometry, BoxGeometry, BoxBufferGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshPhongMaterial, MeshToonMaterial, MeshNormalMaterial, MeshLambertMaterial, MeshDepthMaterial, MeshBasicMaterial, LineDashedMaterial, LineBasicMaterial, Material, Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute, REVISION, MOUSE, CullFaceNone, CullFaceBack, CullFaceFront, CullFaceFrontBack, FrontFaceDirectionCW, FrontFaceDirectionCCW, BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, FrontSide, BackSide, DoubleSide, FlatShading, SmoothShading, NoColors, FaceColors, VertexColors, NoBlending, NormalBlending, AdditiveBlending, SubtractiveBlending, MultiplyBlending, CustomBlending, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, OneMinusSrcColorFactor, SrcAlphaFactor, OneMinusSrcAlphaFactor, DstAlphaFactor, OneMinusDstAlphaFactor, DstColorFactor, OneMinusDstColorFactor, SrcAlphaSaturateFactor, NeverDepth, AlwaysDepth, LessDepth, LessEqualDepth, EqualDepth, GreaterEqualDepth, GreaterDepth, NotEqualDepth, MultiplyOperation, MixOperation, AddOperation, NoToneMapping, LinearToneMapping, ReinhardToneMapping, Uncharted2ToneMapping, CineonToneMapping, UVMapping, CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping, SphericalReflectionMapping, CubeUVReflectionMapping, CubeUVRefractionMapping, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, UnsignedByteType, ByteType, ShortType, UnsignedShortType, IntType, UnsignedIntType, FloatType, HalfFloatType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedInt248Type, AlphaFormat, RGBFormat, RGBAFormat, LuminanceFormat, LuminanceAlphaFormat, RGBEFormat, DepthFormat, DepthStencilFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, LoopOnce, LoopRepeat, LoopPingPong, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, ZeroCurvatureEnding, ZeroSlopeEnding, WrapAroundEnding, TrianglesDrawMode, TriangleStripDrawMode, TriangleFanDrawMode, LinearEncoding, sRGBEncoding, GammaEncoding, RGBEEncoding, LogLuvEncoding, RGBM7Encoding, RGBM16Encoding, RGBDEncoding, BasicDepthPacking, RGBADepthPacking, BoxGeometry as CubeGeometry, Face4, LineStrip, LinePieces, MeshFaceMaterial, MultiMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, SplineCurve3, Spline, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, BinaryTextureLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };