three.module.js 986 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953
  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 = listenerArray.slice( 0 );
  90. for ( var i = 0, l = array.length; i < l; i ++ ) {
  91. array[ i ].call( this, event );
  92. }
  93. }
  94. }
  95. } );
  96. var REVISION = '88dev';
  97. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  98. var CullFaceNone = 0;
  99. var CullFaceBack = 1;
  100. var CullFaceFront = 2;
  101. var CullFaceFrontBack = 3;
  102. var FrontFaceDirectionCW = 0;
  103. var FrontFaceDirectionCCW = 1;
  104. var BasicShadowMap = 0;
  105. var PCFShadowMap = 1;
  106. var PCFSoftShadowMap = 2;
  107. var FrontSide = 0;
  108. var BackSide = 1;
  109. var DoubleSide = 2;
  110. var FlatShading = 1;
  111. var SmoothShading = 2;
  112. var NoColors = 0;
  113. var FaceColors = 1;
  114. var VertexColors = 2;
  115. var NoBlending = 0;
  116. var NormalBlending = 1;
  117. var AdditiveBlending = 2;
  118. var SubtractiveBlending = 3;
  119. var MultiplyBlending = 4;
  120. var CustomBlending = 5;
  121. var AddEquation = 100;
  122. var SubtractEquation = 101;
  123. var ReverseSubtractEquation = 102;
  124. var MinEquation = 103;
  125. var MaxEquation = 104;
  126. var ZeroFactor = 200;
  127. var OneFactor = 201;
  128. var SrcColorFactor = 202;
  129. var OneMinusSrcColorFactor = 203;
  130. var SrcAlphaFactor = 204;
  131. var OneMinusSrcAlphaFactor = 205;
  132. var DstAlphaFactor = 206;
  133. var OneMinusDstAlphaFactor = 207;
  134. var DstColorFactor = 208;
  135. var OneMinusDstColorFactor = 209;
  136. var SrcAlphaSaturateFactor = 210;
  137. var NeverDepth = 0;
  138. var AlwaysDepth = 1;
  139. var LessDepth = 2;
  140. var LessEqualDepth = 3;
  141. var EqualDepth = 4;
  142. var GreaterEqualDepth = 5;
  143. var GreaterDepth = 6;
  144. var NotEqualDepth = 7;
  145. var MultiplyOperation = 0;
  146. var MixOperation = 1;
  147. var AddOperation = 2;
  148. var NoToneMapping = 0;
  149. var LinearToneMapping = 1;
  150. var ReinhardToneMapping = 2;
  151. var Uncharted2ToneMapping = 3;
  152. var CineonToneMapping = 4;
  153. var UVMapping = 300;
  154. var CubeReflectionMapping = 301;
  155. var CubeRefractionMapping = 302;
  156. var EquirectangularReflectionMapping = 303;
  157. var EquirectangularRefractionMapping = 304;
  158. var SphericalReflectionMapping = 305;
  159. var CubeUVReflectionMapping = 306;
  160. var CubeUVRefractionMapping = 307;
  161. var RepeatWrapping = 1000;
  162. var ClampToEdgeWrapping = 1001;
  163. var MirroredRepeatWrapping = 1002;
  164. var NearestFilter = 1003;
  165. var NearestMipMapNearestFilter = 1004;
  166. var NearestMipMapLinearFilter = 1005;
  167. var LinearFilter = 1006;
  168. var LinearMipMapNearestFilter = 1007;
  169. var LinearMipMapLinearFilter = 1008;
  170. var UnsignedByteType = 1009;
  171. var ByteType = 1010;
  172. var ShortType = 1011;
  173. var UnsignedShortType = 1012;
  174. var IntType = 1013;
  175. var UnsignedIntType = 1014;
  176. var FloatType = 1015;
  177. var HalfFloatType = 1016;
  178. var UnsignedShort4444Type = 1017;
  179. var UnsignedShort5551Type = 1018;
  180. var UnsignedShort565Type = 1019;
  181. var UnsignedInt248Type = 1020;
  182. var AlphaFormat = 1021;
  183. var RGBFormat = 1022;
  184. var RGBAFormat = 1023;
  185. var LuminanceFormat = 1024;
  186. var LuminanceAlphaFormat = 1025;
  187. var RGBEFormat = RGBAFormat;
  188. var DepthFormat = 1026;
  189. var DepthStencilFormat = 1027;
  190. var RGB_S3TC_DXT1_Format = 2001;
  191. var RGBA_S3TC_DXT1_Format = 2002;
  192. var RGBA_S3TC_DXT3_Format = 2003;
  193. var RGBA_S3TC_DXT5_Format = 2004;
  194. var RGB_PVRTC_4BPPV1_Format = 2100;
  195. var RGB_PVRTC_2BPPV1_Format = 2101;
  196. var RGBA_PVRTC_4BPPV1_Format = 2102;
  197. var RGBA_PVRTC_2BPPV1_Format = 2103;
  198. var RGB_ETC1_Format = 2151;
  199. var LoopOnce = 2200;
  200. var LoopRepeat = 2201;
  201. var LoopPingPong = 2202;
  202. var InterpolateDiscrete = 2300;
  203. var InterpolateLinear = 2301;
  204. var InterpolateSmooth = 2302;
  205. var ZeroCurvatureEnding = 2400;
  206. var ZeroSlopeEnding = 2401;
  207. var WrapAroundEnding = 2402;
  208. var TrianglesDrawMode = 0;
  209. var TriangleStripDrawMode = 1;
  210. var TriangleFanDrawMode = 2;
  211. var LinearEncoding = 3000;
  212. var sRGBEncoding = 3001;
  213. var GammaEncoding = 3007;
  214. var RGBEEncoding = 3002;
  215. var LogLuvEncoding = 3003;
  216. var RGBM7Encoding = 3004;
  217. var RGBM16Encoding = 3005;
  218. var RGBDEncoding = 3006;
  219. var BasicDepthPacking = 3200;
  220. var RGBADepthPacking = 3201;
  221. /**
  222. * @author alteredq / http://alteredqualia.com/
  223. * @author mrdoob / http://mrdoob.com/
  224. */
  225. var _Math = {
  226. DEG2RAD: Math.PI / 180,
  227. RAD2DEG: 180 / Math.PI,
  228. generateUUID: function () {
  229. // http://www.broofa.com/Tools/Math.uuid.htm
  230. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  231. var uuid = new Array( 36 );
  232. var rnd = 0, r;
  233. return function generateUUID() {
  234. for ( var i = 0; i < 36; i ++ ) {
  235. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  236. uuid[ i ] = '-';
  237. } else if ( i === 14 ) {
  238. uuid[ i ] = '4';
  239. } else {
  240. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  241. r = rnd & 0xf;
  242. rnd = rnd >> 4;
  243. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  244. }
  245. }
  246. return uuid.join( '' );
  247. };
  248. }(),
  249. clamp: function ( value, min, max ) {
  250. return Math.max( min, Math.min( max, value ) );
  251. },
  252. // compute euclidian modulo of m % n
  253. // https://en.wikipedia.org/wiki/Modulo_operation
  254. euclideanModulo: function ( n, m ) {
  255. return ( ( n % m ) + m ) % m;
  256. },
  257. // Linear mapping from range <a1, a2> to range <b1, b2>
  258. mapLinear: function ( x, a1, a2, b1, b2 ) {
  259. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  260. },
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. lerp: function ( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. },
  265. // http://en.wikipedia.org/wiki/Smoothstep
  266. smoothstep: function ( x, min, max ) {
  267. if ( x <= min ) return 0;
  268. if ( x >= max ) return 1;
  269. x = ( x - min ) / ( max - min );
  270. return x * x * ( 3 - 2 * x );
  271. },
  272. smootherstep: function ( x, min, max ) {
  273. if ( x <= min ) return 0;
  274. if ( x >= max ) return 1;
  275. x = ( x - min ) / ( max - min );
  276. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  277. },
  278. // Random integer from <low, high> interval
  279. randInt: function ( low, high ) {
  280. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  281. },
  282. // Random float from <low, high> interval
  283. randFloat: function ( low, high ) {
  284. return low + Math.random() * ( high - low );
  285. },
  286. // Random float from <-range/2, range/2> interval
  287. randFloatSpread: function ( range ) {
  288. return range * ( 0.5 - Math.random() );
  289. },
  290. degToRad: function ( degrees ) {
  291. return degrees * _Math.DEG2RAD;
  292. },
  293. radToDeg: function ( radians ) {
  294. return radians * _Math.RAD2DEG;
  295. },
  296. isPowerOfTwo: function ( value ) {
  297. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  298. },
  299. nearestPowerOfTwo: function ( value ) {
  300. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  301. },
  302. nextPowerOfTwo: function ( value ) {
  303. value --;
  304. value |= value >> 1;
  305. value |= value >> 2;
  306. value |= value >> 4;
  307. value |= value >> 8;
  308. value |= value >> 16;
  309. value ++;
  310. return value;
  311. }
  312. };
  313. /**
  314. * @author mrdoob / http://mrdoob.com/
  315. * @author philogb / http://blog.thejit.org/
  316. * @author egraether / http://egraether.com/
  317. * @author zz85 / http://www.lab4games.net/zz85/blog
  318. */
  319. function Vector2( x, y ) {
  320. this.x = x || 0;
  321. this.y = y || 0;
  322. }
  323. Object.defineProperties( Vector2.prototype, {
  324. "width" : {
  325. get: function () {
  326. return this.x;
  327. },
  328. set: function ( value ) {
  329. this.x = value;
  330. }
  331. },
  332. "height" : {
  333. get: function () {
  334. return this.y;
  335. },
  336. set: function ( value ) {
  337. this.y = value;
  338. }
  339. }
  340. } );
  341. Object.assign( Vector2.prototype, {
  342. isVector2: true,
  343. set: function ( x, y ) {
  344. this.x = x;
  345. this.y = y;
  346. return this;
  347. },
  348. setScalar: function ( scalar ) {
  349. this.x = scalar;
  350. this.y = scalar;
  351. return this;
  352. },
  353. setX: function ( x ) {
  354. this.x = x;
  355. return this;
  356. },
  357. setY: function ( y ) {
  358. this.y = y;
  359. return this;
  360. },
  361. setComponent: function ( index, value ) {
  362. switch ( index ) {
  363. case 0: this.x = value; break;
  364. case 1: this.y = value; break;
  365. default: throw new Error( 'index is out of range: ' + index );
  366. }
  367. return this;
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. this.x *= scalar;
  434. this.y *= scalar;
  435. return this;
  436. },
  437. divide: function ( v ) {
  438. this.x /= v.x;
  439. this.y /= v.y;
  440. return this;
  441. },
  442. divideScalar: function ( scalar ) {
  443. return this.multiplyScalar( 1 / scalar );
  444. },
  445. applyMatrix3: function ( m ) {
  446. var x = this.x, y = this.y;
  447. var e = m.elements;
  448. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  449. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  450. return this;
  451. },
  452. min: function ( v ) {
  453. this.x = Math.min( this.x, v.x );
  454. this.y = Math.min( this.y, v.y );
  455. return this;
  456. },
  457. max: function ( v ) {
  458. this.x = Math.max( this.x, v.x );
  459. this.y = Math.max( this.y, v.y );
  460. return this;
  461. },
  462. clamp: function ( min, max ) {
  463. // assumes min < max, componentwise
  464. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  465. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  466. return this;
  467. },
  468. clampScalar: function () {
  469. var min = new Vector2();
  470. var max = new Vector2();
  471. return function clampScalar( minVal, maxVal ) {
  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.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, 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() || 1 );
  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.normalize().multiplyScalar( 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 supereggbert / http://www.paulbrunt.co.uk/
  584. * @author philogb / http://blog.thejit.org/
  585. * @author jordi_ros / http://plattsoft.com
  586. * @author D1plo1d / http://github.com/D1plo1d
  587. * @author alteredq / http://alteredqualia.com/
  588. * @author mikael emtinger / http://gomo.se/
  589. * @author timknip / http://www.floorplanner.com/
  590. * @author bhouston / http://clara.io
  591. * @author WestLangley / http://github.com/WestLangley
  592. */
  593. function Matrix4() {
  594. this.elements = [
  595. 1, 0, 0, 0,
  596. 0, 1, 0, 0,
  597. 0, 0, 1, 0,
  598. 0, 0, 0, 1
  599. ];
  600. if ( arguments.length > 0 ) {
  601. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  602. }
  603. }
  604. Object.assign( Matrix4.prototype, {
  605. isMatrix4: true,
  606. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  607. var te = this.elements;
  608. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  609. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  610. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  611. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  612. return this;
  613. },
  614. identity: function () {
  615. this.set(
  616. 1, 0, 0, 0,
  617. 0, 1, 0, 0,
  618. 0, 0, 1, 0,
  619. 0, 0, 0, 1
  620. );
  621. return this;
  622. },
  623. clone: function () {
  624. return new Matrix4().fromArray( this.elements );
  625. },
  626. copy: function ( m ) {
  627. var te = this.elements;
  628. var me = m.elements;
  629. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  630. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  631. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  632. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  633. return this;
  634. },
  635. copyPosition: function ( m ) {
  636. var te = this.elements, me = m.elements;
  637. te[ 12 ] = me[ 12 ];
  638. te[ 13 ] = me[ 13 ];
  639. te[ 14 ] = me[ 14 ];
  640. return this;
  641. },
  642. extractBasis: function ( xAxis, yAxis, zAxis ) {
  643. xAxis.setFromMatrixColumn( this, 0 );
  644. yAxis.setFromMatrixColumn( this, 1 );
  645. zAxis.setFromMatrixColumn( this, 2 );
  646. return this;
  647. },
  648. makeBasis: function ( xAxis, yAxis, zAxis ) {
  649. this.set(
  650. xAxis.x, yAxis.x, zAxis.x, 0,
  651. xAxis.y, yAxis.y, zAxis.y, 0,
  652. xAxis.z, yAxis.z, zAxis.z, 0,
  653. 0, 0, 0, 1
  654. );
  655. return this;
  656. },
  657. extractRotation: function () {
  658. var v1 = new Vector3();
  659. return function extractRotation( m ) {
  660. var te = this.elements;
  661. var me = m.elements;
  662. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  663. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  664. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  665. te[ 0 ] = me[ 0 ] * scaleX;
  666. te[ 1 ] = me[ 1 ] * scaleX;
  667. te[ 2 ] = me[ 2 ] * scaleX;
  668. te[ 4 ] = me[ 4 ] * scaleY;
  669. te[ 5 ] = me[ 5 ] * scaleY;
  670. te[ 6 ] = me[ 6 ] * scaleY;
  671. te[ 8 ] = me[ 8 ] * scaleZ;
  672. te[ 9 ] = me[ 9 ] * scaleZ;
  673. te[ 10 ] = me[ 10 ] * scaleZ;
  674. return this;
  675. };
  676. }(),
  677. makeRotationFromEuler: function ( euler ) {
  678. if ( ! ( euler && euler.isEuler ) ) {
  679. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  680. }
  681. var te = this.elements;
  682. var x = euler.x, y = euler.y, z = euler.z;
  683. var a = Math.cos( x ), b = Math.sin( x );
  684. var c = Math.cos( y ), d = Math.sin( y );
  685. var e = Math.cos( z ), f = Math.sin( z );
  686. if ( euler.order === 'XYZ' ) {
  687. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  688. te[ 0 ] = c * e;
  689. te[ 4 ] = - c * f;
  690. te[ 8 ] = d;
  691. te[ 1 ] = af + be * d;
  692. te[ 5 ] = ae - bf * d;
  693. te[ 9 ] = - b * c;
  694. te[ 2 ] = bf - ae * d;
  695. te[ 6 ] = be + af * d;
  696. te[ 10 ] = a * c;
  697. } else if ( euler.order === 'YXZ' ) {
  698. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  699. te[ 0 ] = ce + df * b;
  700. te[ 4 ] = de * b - cf;
  701. te[ 8 ] = a * d;
  702. te[ 1 ] = a * f;
  703. te[ 5 ] = a * e;
  704. te[ 9 ] = - b;
  705. te[ 2 ] = cf * b - de;
  706. te[ 6 ] = df + ce * b;
  707. te[ 10 ] = a * c;
  708. } else if ( euler.order === 'ZXY' ) {
  709. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  710. te[ 0 ] = ce - df * b;
  711. te[ 4 ] = - a * f;
  712. te[ 8 ] = de + cf * b;
  713. te[ 1 ] = cf + de * b;
  714. te[ 5 ] = a * e;
  715. te[ 9 ] = df - ce * b;
  716. te[ 2 ] = - a * d;
  717. te[ 6 ] = b;
  718. te[ 10 ] = a * c;
  719. } else if ( euler.order === 'ZYX' ) {
  720. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  721. te[ 0 ] = c * e;
  722. te[ 4 ] = be * d - af;
  723. te[ 8 ] = ae * d + bf;
  724. te[ 1 ] = c * f;
  725. te[ 5 ] = bf * d + ae;
  726. te[ 9 ] = af * d - be;
  727. te[ 2 ] = - d;
  728. te[ 6 ] = b * c;
  729. te[ 10 ] = a * c;
  730. } else if ( euler.order === 'YZX' ) {
  731. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  732. te[ 0 ] = c * e;
  733. te[ 4 ] = bd - ac * f;
  734. te[ 8 ] = bc * f + ad;
  735. te[ 1 ] = f;
  736. te[ 5 ] = a * e;
  737. te[ 9 ] = - b * e;
  738. te[ 2 ] = - d * e;
  739. te[ 6 ] = ad * f + bc;
  740. te[ 10 ] = ac - bd * f;
  741. } else if ( euler.order === 'XZY' ) {
  742. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  743. te[ 0 ] = c * e;
  744. te[ 4 ] = - f;
  745. te[ 8 ] = d * e;
  746. te[ 1 ] = ac * f + bd;
  747. te[ 5 ] = a * e;
  748. te[ 9 ] = ad * f - bc;
  749. te[ 2 ] = bc * f - ad;
  750. te[ 6 ] = b * e;
  751. te[ 10 ] = bd * f + ac;
  752. }
  753. // last column
  754. te[ 3 ] = 0;
  755. te[ 7 ] = 0;
  756. te[ 11 ] = 0;
  757. // bottom row
  758. te[ 12 ] = 0;
  759. te[ 13 ] = 0;
  760. te[ 14 ] = 0;
  761. te[ 15 ] = 1;
  762. return this;
  763. },
  764. makeRotationFromQuaternion: function ( q ) {
  765. var te = this.elements;
  766. var x = q._x, y = q._y, z = q._z, w = q._w;
  767. var x2 = x + x, y2 = y + y, z2 = z + z;
  768. var xx = x * x2, xy = x * y2, xz = x * z2;
  769. var yy = y * y2, yz = y * z2, zz = z * z2;
  770. var wx = w * x2, wy = w * y2, wz = w * z2;
  771. te[ 0 ] = 1 - ( yy + zz );
  772. te[ 4 ] = xy - wz;
  773. te[ 8 ] = xz + wy;
  774. te[ 1 ] = xy + wz;
  775. te[ 5 ] = 1 - ( xx + zz );
  776. te[ 9 ] = yz - wx;
  777. te[ 2 ] = xz - wy;
  778. te[ 6 ] = yz + wx;
  779. te[ 10 ] = 1 - ( xx + yy );
  780. // last column
  781. te[ 3 ] = 0;
  782. te[ 7 ] = 0;
  783. te[ 11 ] = 0;
  784. // bottom row
  785. te[ 12 ] = 0;
  786. te[ 13 ] = 0;
  787. te[ 14 ] = 0;
  788. te[ 15 ] = 1;
  789. return this;
  790. },
  791. lookAt: function () {
  792. var x = new Vector3();
  793. var y = new Vector3();
  794. var z = new Vector3();
  795. return function lookAt( eye, target, up ) {
  796. var te = this.elements;
  797. z.subVectors( eye, target );
  798. if ( z.lengthSq() === 0 ) {
  799. // eye and target are in the same position
  800. z.z = 1;
  801. }
  802. z.normalize();
  803. x.crossVectors( up, z );
  804. if ( x.lengthSq() === 0 ) {
  805. // up and z are parallel
  806. if ( Math.abs( up.z ) === 1 ) {
  807. z.x += 0.0001;
  808. } else {
  809. z.z += 0.0001;
  810. }
  811. z.normalize();
  812. x.crossVectors( up, z );
  813. }
  814. x.normalize();
  815. y.crossVectors( z, x );
  816. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  817. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  818. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  819. return this;
  820. };
  821. }(),
  822. multiply: function ( m, n ) {
  823. if ( n !== undefined ) {
  824. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  825. return this.multiplyMatrices( m, n );
  826. }
  827. return this.multiplyMatrices( this, m );
  828. },
  829. premultiply: function ( m ) {
  830. return this.multiplyMatrices( m, this );
  831. },
  832. multiplyMatrices: function ( a, b ) {
  833. var ae = a.elements;
  834. var be = b.elements;
  835. var te = this.elements;
  836. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  837. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  838. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  839. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  840. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  841. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  842. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  843. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  844. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  845. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  846. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  847. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  848. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  849. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  850. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  851. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  852. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  853. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  854. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  855. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  856. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  857. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  858. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  859. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  860. return this;
  861. },
  862. multiplyScalar: function ( s ) {
  863. var te = this.elements;
  864. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  865. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  866. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  867. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  868. return this;
  869. },
  870. applyToBufferAttribute: function () {
  871. var v1 = new Vector3();
  872. return function applyToBufferAttribute( attribute ) {
  873. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  874. v1.x = attribute.getX( i );
  875. v1.y = attribute.getY( i );
  876. v1.z = attribute.getZ( i );
  877. v1.applyMatrix4( this );
  878. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  879. }
  880. return attribute;
  881. };
  882. }(),
  883. determinant: function () {
  884. var te = this.elements;
  885. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  886. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  887. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  888. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  889. //TODO: make this more efficient
  890. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  891. return (
  892. n41 * (
  893. + n14 * n23 * n32
  894. - n13 * n24 * n32
  895. - n14 * n22 * n33
  896. + n12 * n24 * n33
  897. + n13 * n22 * n34
  898. - n12 * n23 * n34
  899. ) +
  900. n42 * (
  901. + n11 * n23 * n34
  902. - n11 * n24 * n33
  903. + n14 * n21 * n33
  904. - n13 * n21 * n34
  905. + n13 * n24 * n31
  906. - n14 * n23 * n31
  907. ) +
  908. n43 * (
  909. + n11 * n24 * n32
  910. - n11 * n22 * n34
  911. - n14 * n21 * n32
  912. + n12 * n21 * n34
  913. + n14 * n22 * n31
  914. - n12 * n24 * n31
  915. ) +
  916. n44 * (
  917. - n13 * n22 * n31
  918. - n11 * n23 * n32
  919. + n11 * n22 * n33
  920. + n13 * n21 * n32
  921. - n12 * n21 * n33
  922. + n12 * n23 * n31
  923. )
  924. );
  925. },
  926. transpose: function () {
  927. var te = this.elements;
  928. var tmp;
  929. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  930. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  931. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  932. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  933. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  934. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  935. return this;
  936. },
  937. setPosition: function ( v ) {
  938. var te = this.elements;
  939. te[ 12 ] = v.x;
  940. te[ 13 ] = v.y;
  941. te[ 14 ] = v.z;
  942. return this;
  943. },
  944. getInverse: function ( m, throwOnDegenerate ) {
  945. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  946. var te = this.elements,
  947. me = m.elements,
  948. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  949. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  950. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  951. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  952. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  953. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  954. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  955. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  956. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  957. if ( det === 0 ) {
  958. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  959. if ( throwOnDegenerate === true ) {
  960. throw new Error( msg );
  961. } else {
  962. console.warn( msg );
  963. }
  964. return this.identity();
  965. }
  966. var detInv = 1 / det;
  967. te[ 0 ] = t11 * detInv;
  968. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  969. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  970. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  971. te[ 4 ] = t12 * detInv;
  972. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  973. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  974. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  975. te[ 8 ] = t13 * detInv;
  976. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  977. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  978. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  979. te[ 12 ] = t14 * detInv;
  980. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  981. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  982. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  983. return this;
  984. },
  985. scale: function ( v ) {
  986. var te = this.elements;
  987. var x = v.x, y = v.y, z = v.z;
  988. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  989. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  990. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  991. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  992. return this;
  993. },
  994. getMaxScaleOnAxis: function () {
  995. var te = this.elements;
  996. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  997. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  998. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  999. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  1000. },
  1001. makeTranslation: function ( x, y, z ) {
  1002. this.set(
  1003. 1, 0, 0, x,
  1004. 0, 1, 0, y,
  1005. 0, 0, 1, z,
  1006. 0, 0, 0, 1
  1007. );
  1008. return this;
  1009. },
  1010. makeRotationX: function ( theta ) {
  1011. var c = Math.cos( theta ), s = Math.sin( theta );
  1012. this.set(
  1013. 1, 0, 0, 0,
  1014. 0, c, - s, 0,
  1015. 0, s, c, 0,
  1016. 0, 0, 0, 1
  1017. );
  1018. return this;
  1019. },
  1020. makeRotationY: function ( theta ) {
  1021. var c = Math.cos( theta ), s = Math.sin( theta );
  1022. this.set(
  1023. c, 0, s, 0,
  1024. 0, 1, 0, 0,
  1025. - s, 0, c, 0,
  1026. 0, 0, 0, 1
  1027. );
  1028. return this;
  1029. },
  1030. makeRotationZ: function ( theta ) {
  1031. var c = Math.cos( theta ), s = Math.sin( theta );
  1032. this.set(
  1033. c, - s, 0, 0,
  1034. s, c, 0, 0,
  1035. 0, 0, 1, 0,
  1036. 0, 0, 0, 1
  1037. );
  1038. return this;
  1039. },
  1040. makeRotationAxis: function ( axis, angle ) {
  1041. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1042. var c = Math.cos( angle );
  1043. var s = Math.sin( angle );
  1044. var t = 1 - c;
  1045. var x = axis.x, y = axis.y, z = axis.z;
  1046. var tx = t * x, ty = t * y;
  1047. this.set(
  1048. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1049. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1050. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1051. 0, 0, 0, 1
  1052. );
  1053. return this;
  1054. },
  1055. makeScale: function ( x, y, z ) {
  1056. this.set(
  1057. x, 0, 0, 0,
  1058. 0, y, 0, 0,
  1059. 0, 0, z, 0,
  1060. 0, 0, 0, 1
  1061. );
  1062. return this;
  1063. },
  1064. makeShear: function ( x, y, z ) {
  1065. this.set(
  1066. 1, y, z, 0,
  1067. x, 1, z, 0,
  1068. x, y, 1, 0,
  1069. 0, 0, 0, 1
  1070. );
  1071. return this;
  1072. },
  1073. compose: function ( position, quaternion, scale ) {
  1074. this.makeRotationFromQuaternion( quaternion );
  1075. this.scale( scale );
  1076. this.setPosition( position );
  1077. return this;
  1078. },
  1079. decompose: function () {
  1080. var vector = new Vector3();
  1081. var matrix = new Matrix4();
  1082. return function decompose( position, quaternion, scale ) {
  1083. var te = this.elements;
  1084. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  1085. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  1086. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  1087. // if determine is negative, we need to invert one scale
  1088. var det = this.determinant();
  1089. if ( det < 0 ) sx = - sx;
  1090. position.x = te[ 12 ];
  1091. position.y = te[ 13 ];
  1092. position.z = te[ 14 ];
  1093. // scale the rotation part
  1094. matrix.copy( this );
  1095. var invSX = 1 / sx;
  1096. var invSY = 1 / sy;
  1097. var invSZ = 1 / sz;
  1098. matrix.elements[ 0 ] *= invSX;
  1099. matrix.elements[ 1 ] *= invSX;
  1100. matrix.elements[ 2 ] *= invSX;
  1101. matrix.elements[ 4 ] *= invSY;
  1102. matrix.elements[ 5 ] *= invSY;
  1103. matrix.elements[ 6 ] *= invSY;
  1104. matrix.elements[ 8 ] *= invSZ;
  1105. matrix.elements[ 9 ] *= invSZ;
  1106. matrix.elements[ 10 ] *= invSZ;
  1107. quaternion.setFromRotationMatrix( matrix );
  1108. scale.x = sx;
  1109. scale.y = sy;
  1110. scale.z = sz;
  1111. return this;
  1112. };
  1113. }(),
  1114. makePerspective: function ( left, right, top, bottom, near, far ) {
  1115. if ( far === undefined ) {
  1116. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  1117. }
  1118. var te = this.elements;
  1119. var x = 2 * near / ( right - left );
  1120. var y = 2 * near / ( top - bottom );
  1121. var a = ( right + left ) / ( right - left );
  1122. var b = ( top + bottom ) / ( top - bottom );
  1123. var c = - ( far + near ) / ( far - near );
  1124. var d = - 2 * far * near / ( far - near );
  1125. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  1126. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  1127. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  1128. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  1129. return this;
  1130. },
  1131. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1132. var te = this.elements;
  1133. var w = 1.0 / ( right - left );
  1134. var h = 1.0 / ( top - bottom );
  1135. var p = 1.0 / ( far - near );
  1136. var x = ( right + left ) * w;
  1137. var y = ( top + bottom ) * h;
  1138. var z = ( far + near ) * p;
  1139. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  1140. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  1141. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  1142. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  1143. return this;
  1144. },
  1145. equals: function ( matrix ) {
  1146. var te = this.elements;
  1147. var me = matrix.elements;
  1148. for ( var i = 0; i < 16; i ++ ) {
  1149. if ( te[ i ] !== me[ i ] ) return false;
  1150. }
  1151. return true;
  1152. },
  1153. fromArray: function ( array, offset ) {
  1154. if ( offset === undefined ) offset = 0;
  1155. for ( var i = 0; i < 16; i ++ ) {
  1156. this.elements[ i ] = array[ i + offset ];
  1157. }
  1158. return this;
  1159. },
  1160. toArray: function ( array, offset ) {
  1161. if ( array === undefined ) array = [];
  1162. if ( offset === undefined ) offset = 0;
  1163. var te = this.elements;
  1164. array[ offset ] = te[ 0 ];
  1165. array[ offset + 1 ] = te[ 1 ];
  1166. array[ offset + 2 ] = te[ 2 ];
  1167. array[ offset + 3 ] = te[ 3 ];
  1168. array[ offset + 4 ] = te[ 4 ];
  1169. array[ offset + 5 ] = te[ 5 ];
  1170. array[ offset + 6 ] = te[ 6 ];
  1171. array[ offset + 7 ] = te[ 7 ];
  1172. array[ offset + 8 ] = te[ 8 ];
  1173. array[ offset + 9 ] = te[ 9 ];
  1174. array[ offset + 10 ] = te[ 10 ];
  1175. array[ offset + 11 ] = te[ 11 ];
  1176. array[ offset + 12 ] = te[ 12 ];
  1177. array[ offset + 13 ] = te[ 13 ];
  1178. array[ offset + 14 ] = te[ 14 ];
  1179. array[ offset + 15 ] = te[ 15 ];
  1180. return array;
  1181. }
  1182. } );
  1183. /**
  1184. * @author mikael emtinger / http://gomo.se/
  1185. * @author alteredq / http://alteredqualia.com/
  1186. * @author WestLangley / http://github.com/WestLangley
  1187. * @author bhouston / http://clara.io
  1188. */
  1189. function Quaternion( x, y, z, w ) {
  1190. this._x = x || 0;
  1191. this._y = y || 0;
  1192. this._z = z || 0;
  1193. this._w = ( w !== undefined ) ? w : 1;
  1194. }
  1195. Object.assign( Quaternion, {
  1196. slerp: function ( qa, qb, qm, t ) {
  1197. return qm.copy( qa ).slerp( qb, t );
  1198. },
  1199. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1200. // fuzz-free, array-based Quaternion SLERP operation
  1201. var x0 = src0[ srcOffset0 + 0 ],
  1202. y0 = src0[ srcOffset0 + 1 ],
  1203. z0 = src0[ srcOffset0 + 2 ],
  1204. w0 = src0[ srcOffset0 + 3 ],
  1205. x1 = src1[ srcOffset1 + 0 ],
  1206. y1 = src1[ srcOffset1 + 1 ],
  1207. z1 = src1[ srcOffset1 + 2 ],
  1208. w1 = src1[ srcOffset1 + 3 ];
  1209. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1210. var s = 1 - t,
  1211. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1212. dir = ( cos >= 0 ? 1 : - 1 ),
  1213. sqrSin = 1 - cos * cos;
  1214. // Skip the Slerp for tiny steps to avoid numeric problems:
  1215. if ( sqrSin > Number.EPSILON ) {
  1216. var sin = Math.sqrt( sqrSin ),
  1217. len = Math.atan2( sin, cos * dir );
  1218. s = Math.sin( s * len ) / sin;
  1219. t = Math.sin( t * len ) / sin;
  1220. }
  1221. var tDir = t * dir;
  1222. x0 = x0 * s + x1 * tDir;
  1223. y0 = y0 * s + y1 * tDir;
  1224. z0 = z0 * s + z1 * tDir;
  1225. w0 = w0 * s + w1 * tDir;
  1226. // Normalize in case we just did a lerp:
  1227. if ( s === 1 - t ) {
  1228. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1229. x0 *= f;
  1230. y0 *= f;
  1231. z0 *= f;
  1232. w0 *= f;
  1233. }
  1234. }
  1235. dst[ dstOffset ] = x0;
  1236. dst[ dstOffset + 1 ] = y0;
  1237. dst[ dstOffset + 2 ] = z0;
  1238. dst[ dstOffset + 3 ] = w0;
  1239. }
  1240. } );
  1241. Object.defineProperties( Quaternion.prototype, {
  1242. x: {
  1243. get: function () {
  1244. return this._x;
  1245. },
  1246. set: function ( value ) {
  1247. this._x = value;
  1248. this.onChangeCallback();
  1249. }
  1250. },
  1251. y: {
  1252. get: function () {
  1253. return this._y;
  1254. },
  1255. set: function ( value ) {
  1256. this._y = value;
  1257. this.onChangeCallback();
  1258. }
  1259. },
  1260. z: {
  1261. get: function () {
  1262. return this._z;
  1263. },
  1264. set: function ( value ) {
  1265. this._z = value;
  1266. this.onChangeCallback();
  1267. }
  1268. },
  1269. w: {
  1270. get: function () {
  1271. return this._w;
  1272. },
  1273. set: function ( value ) {
  1274. this._w = value;
  1275. this.onChangeCallback();
  1276. }
  1277. }
  1278. } );
  1279. Object.assign( Quaternion.prototype, {
  1280. set: function ( x, y, z, w ) {
  1281. this._x = x;
  1282. this._y = y;
  1283. this._z = z;
  1284. this._w = w;
  1285. this.onChangeCallback();
  1286. return this;
  1287. },
  1288. clone: function () {
  1289. return new this.constructor( this._x, this._y, this._z, this._w );
  1290. },
  1291. copy: function ( quaternion ) {
  1292. this._x = quaternion.x;
  1293. this._y = quaternion.y;
  1294. this._z = quaternion.z;
  1295. this._w = quaternion.w;
  1296. this.onChangeCallback();
  1297. return this;
  1298. },
  1299. setFromEuler: function ( euler, update ) {
  1300. if ( ! ( euler && euler.isEuler ) ) {
  1301. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1302. }
  1303. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1304. // http://www.mathworks.com/matlabcentral/fileexchange/
  1305. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1306. // content/SpinCalc.m
  1307. var cos = Math.cos;
  1308. var sin = Math.sin;
  1309. var c1 = cos( x / 2 );
  1310. var c2 = cos( y / 2 );
  1311. var c3 = cos( z / 2 );
  1312. var s1 = sin( x / 2 );
  1313. var s2 = sin( y / 2 );
  1314. var s3 = sin( z / 2 );
  1315. if ( order === 'XYZ' ) {
  1316. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1317. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1318. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1319. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1320. } else if ( order === 'YXZ' ) {
  1321. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1322. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1323. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1324. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1325. } else if ( order === 'ZXY' ) {
  1326. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1327. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1328. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1329. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1330. } else if ( order === 'ZYX' ) {
  1331. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1332. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1333. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1334. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1335. } else if ( order === 'YZX' ) {
  1336. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1337. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1338. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1339. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1340. } else if ( order === 'XZY' ) {
  1341. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1342. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1343. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1344. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1345. }
  1346. if ( update !== false ) this.onChangeCallback();
  1347. return this;
  1348. },
  1349. setFromAxisAngle: function ( axis, angle ) {
  1350. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1351. // assumes axis is normalized
  1352. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1353. this._x = axis.x * s;
  1354. this._y = axis.y * s;
  1355. this._z = axis.z * s;
  1356. this._w = Math.cos( halfAngle );
  1357. this.onChangeCallback();
  1358. return this;
  1359. },
  1360. setFromRotationMatrix: function ( m ) {
  1361. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1362. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1363. var te = m.elements,
  1364. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1365. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1366. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1367. trace = m11 + m22 + m33,
  1368. s;
  1369. if ( trace > 0 ) {
  1370. s = 0.5 / Math.sqrt( trace + 1.0 );
  1371. this._w = 0.25 / s;
  1372. this._x = ( m32 - m23 ) * s;
  1373. this._y = ( m13 - m31 ) * s;
  1374. this._z = ( m21 - m12 ) * s;
  1375. } else if ( m11 > m22 && m11 > m33 ) {
  1376. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1377. this._w = ( m32 - m23 ) / s;
  1378. this._x = 0.25 * s;
  1379. this._y = ( m12 + m21 ) / s;
  1380. this._z = ( m13 + m31 ) / s;
  1381. } else if ( m22 > m33 ) {
  1382. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1383. this._w = ( m13 - m31 ) / s;
  1384. this._x = ( m12 + m21 ) / s;
  1385. this._y = 0.25 * s;
  1386. this._z = ( m23 + m32 ) / s;
  1387. } else {
  1388. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1389. this._w = ( m21 - m12 ) / s;
  1390. this._x = ( m13 + m31 ) / s;
  1391. this._y = ( m23 + m32 ) / s;
  1392. this._z = 0.25 * s;
  1393. }
  1394. this.onChangeCallback();
  1395. return this;
  1396. },
  1397. setFromUnitVectors: function () {
  1398. // assumes direction vectors vFrom and vTo are normalized
  1399. var v1 = new Vector3();
  1400. var r;
  1401. var EPS = 0.000001;
  1402. return function setFromUnitVectors( vFrom, vTo ) {
  1403. if ( v1 === undefined ) v1 = new Vector3();
  1404. r = vFrom.dot( vTo ) + 1;
  1405. if ( r < EPS ) {
  1406. r = 0;
  1407. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1408. v1.set( - vFrom.y, vFrom.x, 0 );
  1409. } else {
  1410. v1.set( 0, - vFrom.z, vFrom.y );
  1411. }
  1412. } else {
  1413. v1.crossVectors( vFrom, vTo );
  1414. }
  1415. this._x = v1.x;
  1416. this._y = v1.y;
  1417. this._z = v1.z;
  1418. this._w = r;
  1419. return this.normalize();
  1420. };
  1421. }(),
  1422. inverse: function () {
  1423. return this.conjugate().normalize();
  1424. },
  1425. conjugate: function () {
  1426. this._x *= - 1;
  1427. this._y *= - 1;
  1428. this._z *= - 1;
  1429. this.onChangeCallback();
  1430. return this;
  1431. },
  1432. dot: function ( v ) {
  1433. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1434. },
  1435. lengthSq: function () {
  1436. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1437. },
  1438. length: function () {
  1439. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1440. },
  1441. normalize: function () {
  1442. var l = this.length();
  1443. if ( l === 0 ) {
  1444. this._x = 0;
  1445. this._y = 0;
  1446. this._z = 0;
  1447. this._w = 1;
  1448. } else {
  1449. l = 1 / l;
  1450. this._x = this._x * l;
  1451. this._y = this._y * l;
  1452. this._z = this._z * l;
  1453. this._w = this._w * l;
  1454. }
  1455. this.onChangeCallback();
  1456. return this;
  1457. },
  1458. multiply: function ( q, p ) {
  1459. if ( p !== undefined ) {
  1460. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1461. return this.multiplyQuaternions( q, p );
  1462. }
  1463. return this.multiplyQuaternions( this, q );
  1464. },
  1465. premultiply: function ( q ) {
  1466. return this.multiplyQuaternions( q, this );
  1467. },
  1468. multiplyQuaternions: function ( a, b ) {
  1469. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1470. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1471. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1472. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1473. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1474. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1475. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1476. this.onChangeCallback();
  1477. return this;
  1478. },
  1479. slerp: function ( qb, t ) {
  1480. if ( t === 0 ) return this;
  1481. if ( t === 1 ) return this.copy( qb );
  1482. var x = this._x, y = this._y, z = this._z, w = this._w;
  1483. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1484. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1485. if ( cosHalfTheta < 0 ) {
  1486. this._w = - qb._w;
  1487. this._x = - qb._x;
  1488. this._y = - qb._y;
  1489. this._z = - qb._z;
  1490. cosHalfTheta = - cosHalfTheta;
  1491. } else {
  1492. this.copy( qb );
  1493. }
  1494. if ( cosHalfTheta >= 1.0 ) {
  1495. this._w = w;
  1496. this._x = x;
  1497. this._y = y;
  1498. this._z = z;
  1499. return this;
  1500. }
  1501. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1502. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1503. this._w = 0.5 * ( w + this._w );
  1504. this._x = 0.5 * ( x + this._x );
  1505. this._y = 0.5 * ( y + this._y );
  1506. this._z = 0.5 * ( z + this._z );
  1507. return this;
  1508. }
  1509. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1510. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1511. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1512. this._w = ( w * ratioA + this._w * ratioB );
  1513. this._x = ( x * ratioA + this._x * ratioB );
  1514. this._y = ( y * ratioA + this._y * ratioB );
  1515. this._z = ( z * ratioA + this._z * ratioB );
  1516. this.onChangeCallback();
  1517. return this;
  1518. },
  1519. equals: function ( quaternion ) {
  1520. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1521. },
  1522. fromArray: function ( array, offset ) {
  1523. if ( offset === undefined ) offset = 0;
  1524. this._x = array[ offset ];
  1525. this._y = array[ offset + 1 ];
  1526. this._z = array[ offset + 2 ];
  1527. this._w = array[ offset + 3 ];
  1528. this.onChangeCallback();
  1529. return this;
  1530. },
  1531. toArray: function ( array, offset ) {
  1532. if ( array === undefined ) array = [];
  1533. if ( offset === undefined ) offset = 0;
  1534. array[ offset ] = this._x;
  1535. array[ offset + 1 ] = this._y;
  1536. array[ offset + 2 ] = this._z;
  1537. array[ offset + 3 ] = this._w;
  1538. return array;
  1539. },
  1540. onChange: function ( callback ) {
  1541. this.onChangeCallback = callback;
  1542. return this;
  1543. },
  1544. onChangeCallback: function () {}
  1545. } );
  1546. /**
  1547. * @author mrdoob / http://mrdoob.com/
  1548. * @author kile / http://kile.stravaganza.org/
  1549. * @author philogb / http://blog.thejit.org/
  1550. * @author mikael emtinger / http://gomo.se/
  1551. * @author egraether / http://egraether.com/
  1552. * @author WestLangley / http://github.com/WestLangley
  1553. */
  1554. function Vector3( x, y, z ) {
  1555. this.x = x || 0;
  1556. this.y = y || 0;
  1557. this.z = z || 0;
  1558. }
  1559. Object.assign( Vector3.prototype, {
  1560. isVector3: true,
  1561. set: function ( x, y, z ) {
  1562. this.x = x;
  1563. this.y = y;
  1564. this.z = z;
  1565. return this;
  1566. },
  1567. setScalar: function ( scalar ) {
  1568. this.x = scalar;
  1569. this.y = scalar;
  1570. this.z = scalar;
  1571. return this;
  1572. },
  1573. setX: function ( x ) {
  1574. this.x = x;
  1575. return this;
  1576. },
  1577. setY: function ( y ) {
  1578. this.y = y;
  1579. return this;
  1580. },
  1581. setZ: function ( z ) {
  1582. this.z = z;
  1583. return this;
  1584. },
  1585. setComponent: function ( index, value ) {
  1586. switch ( index ) {
  1587. case 0: this.x = value; break;
  1588. case 1: this.y = value; break;
  1589. case 2: this.z = value; break;
  1590. default: throw new Error( 'index is out of range: ' + index );
  1591. }
  1592. return this;
  1593. },
  1594. getComponent: function ( index ) {
  1595. switch ( index ) {
  1596. case 0: return this.x;
  1597. case 1: return this.y;
  1598. case 2: return this.z;
  1599. default: throw new Error( 'index is out of range: ' + index );
  1600. }
  1601. },
  1602. clone: function () {
  1603. return new this.constructor( this.x, this.y, this.z );
  1604. },
  1605. copy: function ( v ) {
  1606. this.x = v.x;
  1607. this.y = v.y;
  1608. this.z = v.z;
  1609. return this;
  1610. },
  1611. add: function ( v, w ) {
  1612. if ( w !== undefined ) {
  1613. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1614. return this.addVectors( v, w );
  1615. }
  1616. this.x += v.x;
  1617. this.y += v.y;
  1618. this.z += v.z;
  1619. return this;
  1620. },
  1621. addScalar: function ( s ) {
  1622. this.x += s;
  1623. this.y += s;
  1624. this.z += s;
  1625. return this;
  1626. },
  1627. addVectors: function ( a, b ) {
  1628. this.x = a.x + b.x;
  1629. this.y = a.y + b.y;
  1630. this.z = a.z + b.z;
  1631. return this;
  1632. },
  1633. addScaledVector: function ( v, s ) {
  1634. this.x += v.x * s;
  1635. this.y += v.y * s;
  1636. this.z += v.z * s;
  1637. return this;
  1638. },
  1639. sub: function ( v, w ) {
  1640. if ( w !== undefined ) {
  1641. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1642. return this.subVectors( v, w );
  1643. }
  1644. this.x -= v.x;
  1645. this.y -= v.y;
  1646. this.z -= v.z;
  1647. return this;
  1648. },
  1649. subScalar: function ( s ) {
  1650. this.x -= s;
  1651. this.y -= s;
  1652. this.z -= s;
  1653. return this;
  1654. },
  1655. subVectors: function ( a, b ) {
  1656. this.x = a.x - b.x;
  1657. this.y = a.y - b.y;
  1658. this.z = a.z - b.z;
  1659. return this;
  1660. },
  1661. multiply: function ( v, w ) {
  1662. if ( w !== undefined ) {
  1663. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1664. return this.multiplyVectors( v, w );
  1665. }
  1666. this.x *= v.x;
  1667. this.y *= v.y;
  1668. this.z *= v.z;
  1669. return this;
  1670. },
  1671. multiplyScalar: function ( scalar ) {
  1672. this.x *= scalar;
  1673. this.y *= scalar;
  1674. this.z *= scalar;
  1675. return this;
  1676. },
  1677. multiplyVectors: function ( a, b ) {
  1678. this.x = a.x * b.x;
  1679. this.y = a.y * b.y;
  1680. this.z = a.z * b.z;
  1681. return this;
  1682. },
  1683. applyEuler: function () {
  1684. var quaternion = new Quaternion();
  1685. return function applyEuler( euler ) {
  1686. if ( ! ( euler && euler.isEuler ) ) {
  1687. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1688. }
  1689. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1690. };
  1691. }(),
  1692. applyAxisAngle: function () {
  1693. var quaternion = new Quaternion();
  1694. return function applyAxisAngle( axis, angle ) {
  1695. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1696. };
  1697. }(),
  1698. applyMatrix3: function ( m ) {
  1699. var x = this.x, y = this.y, z = this.z;
  1700. var e = m.elements;
  1701. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1702. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1703. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1704. return this;
  1705. },
  1706. applyMatrix4: function ( m ) {
  1707. var x = this.x, y = this.y, z = this.z;
  1708. var e = m.elements;
  1709. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1710. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1711. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1712. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1713. return this;
  1714. },
  1715. applyQuaternion: function ( q ) {
  1716. var x = this.x, y = this.y, z = this.z;
  1717. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1718. // calculate quat * vector
  1719. var ix = qw * x + qy * z - qz * y;
  1720. var iy = qw * y + qz * x - qx * z;
  1721. var iz = qw * z + qx * y - qy * x;
  1722. var iw = - qx * x - qy * y - qz * z;
  1723. // calculate result * inverse quat
  1724. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1725. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1726. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1727. return this;
  1728. },
  1729. project: function () {
  1730. var matrix = new Matrix4();
  1731. return function project( camera ) {
  1732. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1733. return this.applyMatrix4( matrix );
  1734. };
  1735. }(),
  1736. unproject: function () {
  1737. var matrix = new Matrix4();
  1738. return function unproject( camera ) {
  1739. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1740. return this.applyMatrix4( matrix );
  1741. };
  1742. }(),
  1743. transformDirection: function ( m ) {
  1744. // input: THREE.Matrix4 affine matrix
  1745. // vector interpreted as a direction
  1746. var x = this.x, y = this.y, z = this.z;
  1747. var e = m.elements;
  1748. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1749. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1750. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1751. return this.normalize();
  1752. },
  1753. divide: function ( v ) {
  1754. this.x /= v.x;
  1755. this.y /= v.y;
  1756. this.z /= v.z;
  1757. return this;
  1758. },
  1759. divideScalar: function ( scalar ) {
  1760. return this.multiplyScalar( 1 / scalar );
  1761. },
  1762. min: function ( v ) {
  1763. this.x = Math.min( this.x, v.x );
  1764. this.y = Math.min( this.y, v.y );
  1765. this.z = Math.min( this.z, v.z );
  1766. return this;
  1767. },
  1768. max: function ( v ) {
  1769. this.x = Math.max( this.x, v.x );
  1770. this.y = Math.max( this.y, v.y );
  1771. this.z = Math.max( this.z, v.z );
  1772. return this;
  1773. },
  1774. clamp: function ( min, max ) {
  1775. // assumes min < max, componentwise
  1776. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1777. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1778. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1779. return this;
  1780. },
  1781. clampScalar: function () {
  1782. var min = new Vector3();
  1783. var max = new Vector3();
  1784. return function clampScalar( minVal, maxVal ) {
  1785. min.set( minVal, minVal, minVal );
  1786. max.set( maxVal, maxVal, maxVal );
  1787. return this.clamp( min, max );
  1788. };
  1789. }(),
  1790. clampLength: function ( min, max ) {
  1791. var length = this.length();
  1792. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1793. },
  1794. floor: function () {
  1795. this.x = Math.floor( this.x );
  1796. this.y = Math.floor( this.y );
  1797. this.z = Math.floor( this.z );
  1798. return this;
  1799. },
  1800. ceil: function () {
  1801. this.x = Math.ceil( this.x );
  1802. this.y = Math.ceil( this.y );
  1803. this.z = Math.ceil( this.z );
  1804. return this;
  1805. },
  1806. round: function () {
  1807. this.x = Math.round( this.x );
  1808. this.y = Math.round( this.y );
  1809. this.z = Math.round( this.z );
  1810. return this;
  1811. },
  1812. roundToZero: function () {
  1813. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1814. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1815. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1816. return this;
  1817. },
  1818. negate: function () {
  1819. this.x = - this.x;
  1820. this.y = - this.y;
  1821. this.z = - this.z;
  1822. return this;
  1823. },
  1824. dot: function ( v ) {
  1825. return this.x * v.x + this.y * v.y + this.z * v.z;
  1826. },
  1827. // TODO lengthSquared?
  1828. lengthSq: function () {
  1829. return this.x * this.x + this.y * this.y + this.z * this.z;
  1830. },
  1831. length: function () {
  1832. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1833. },
  1834. lengthManhattan: function () {
  1835. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1836. },
  1837. normalize: function () {
  1838. return this.divideScalar( this.length() || 1 );
  1839. },
  1840. setLength: function ( length ) {
  1841. return this.normalize().multiplyScalar( length );
  1842. },
  1843. lerp: function ( v, alpha ) {
  1844. this.x += ( v.x - this.x ) * alpha;
  1845. this.y += ( v.y - this.y ) * alpha;
  1846. this.z += ( v.z - this.z ) * alpha;
  1847. return this;
  1848. },
  1849. lerpVectors: function ( v1, v2, alpha ) {
  1850. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1851. },
  1852. cross: function ( v, w ) {
  1853. if ( w !== undefined ) {
  1854. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1855. return this.crossVectors( v, w );
  1856. }
  1857. var x = this.x, y = this.y, z = this.z;
  1858. this.x = y * v.z - z * v.y;
  1859. this.y = z * v.x - x * v.z;
  1860. this.z = x * v.y - y * v.x;
  1861. return this;
  1862. },
  1863. crossVectors: function ( a, b ) {
  1864. var ax = a.x, ay = a.y, az = a.z;
  1865. var bx = b.x, by = b.y, bz = b.z;
  1866. this.x = ay * bz - az * by;
  1867. this.y = az * bx - ax * bz;
  1868. this.z = ax * by - ay * bx;
  1869. return this;
  1870. },
  1871. projectOnVector: function ( vector ) {
  1872. var scalar = vector.dot( this ) / vector.lengthSq();
  1873. return this.copy( vector ).multiplyScalar( scalar );
  1874. },
  1875. projectOnPlane: function () {
  1876. var v1 = new Vector3();
  1877. return function projectOnPlane( planeNormal ) {
  1878. v1.copy( this ).projectOnVector( planeNormal );
  1879. return this.sub( v1 );
  1880. };
  1881. }(),
  1882. reflect: function () {
  1883. // reflect incident vector off plane orthogonal to normal
  1884. // normal is assumed to have unit length
  1885. var v1 = new Vector3();
  1886. return function reflect( normal ) {
  1887. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1888. };
  1889. }(),
  1890. angleTo: function ( v ) {
  1891. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1892. // clamp, to handle numerical problems
  1893. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1894. },
  1895. distanceTo: function ( v ) {
  1896. return Math.sqrt( this.distanceToSquared( v ) );
  1897. },
  1898. distanceToSquared: function ( v ) {
  1899. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1900. return dx * dx + dy * dy + dz * dz;
  1901. },
  1902. distanceToManhattan: function ( v ) {
  1903. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1904. },
  1905. setFromSpherical: function ( s ) {
  1906. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1907. this.x = sinPhiRadius * Math.sin( s.theta );
  1908. this.y = Math.cos( s.phi ) * s.radius;
  1909. this.z = sinPhiRadius * Math.cos( s.theta );
  1910. return this;
  1911. },
  1912. setFromCylindrical: function ( c ) {
  1913. this.x = c.radius * Math.sin( c.theta );
  1914. this.y = c.y;
  1915. this.z = c.radius * Math.cos( c.theta );
  1916. return this;
  1917. },
  1918. setFromMatrixPosition: function ( m ) {
  1919. var e = m.elements;
  1920. this.x = e[ 12 ];
  1921. this.y = e[ 13 ];
  1922. this.z = e[ 14 ];
  1923. return this;
  1924. },
  1925. setFromMatrixScale: function ( m ) {
  1926. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1927. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1928. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1929. this.x = sx;
  1930. this.y = sy;
  1931. this.z = sz;
  1932. return this;
  1933. },
  1934. setFromMatrixColumn: function ( m, index ) {
  1935. return this.fromArray( m.elements, index * 4 );
  1936. },
  1937. equals: function ( v ) {
  1938. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1939. },
  1940. fromArray: function ( array, offset ) {
  1941. if ( offset === undefined ) offset = 0;
  1942. this.x = array[ offset ];
  1943. this.y = array[ offset + 1 ];
  1944. this.z = array[ offset + 2 ];
  1945. return this;
  1946. },
  1947. toArray: function ( array, offset ) {
  1948. if ( array === undefined ) array = [];
  1949. if ( offset === undefined ) offset = 0;
  1950. array[ offset ] = this.x;
  1951. array[ offset + 1 ] = this.y;
  1952. array[ offset + 2 ] = this.z;
  1953. return array;
  1954. },
  1955. fromBufferAttribute: function ( attribute, index, offset ) {
  1956. if ( offset !== undefined ) {
  1957. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1958. }
  1959. this.x = attribute.getX( index );
  1960. this.y = attribute.getY( index );
  1961. this.z = attribute.getZ( index );
  1962. return this;
  1963. }
  1964. } );
  1965. /**
  1966. * @author alteredq / http://alteredqualia.com/
  1967. * @author WestLangley / http://github.com/WestLangley
  1968. * @author bhouston / http://clara.io
  1969. * @author tschw
  1970. */
  1971. function Matrix3() {
  1972. this.elements = [
  1973. 1, 0, 0,
  1974. 0, 1, 0,
  1975. 0, 0, 1
  1976. ];
  1977. if ( arguments.length > 0 ) {
  1978. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1979. }
  1980. }
  1981. Object.assign( Matrix3.prototype, {
  1982. isMatrix3: true,
  1983. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1984. var te = this.elements;
  1985. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1986. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1987. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1988. return this;
  1989. },
  1990. identity: function () {
  1991. this.set(
  1992. 1, 0, 0,
  1993. 0, 1, 0,
  1994. 0, 0, 1
  1995. );
  1996. return this;
  1997. },
  1998. clone: function () {
  1999. return new this.constructor().fromArray( this.elements );
  2000. },
  2001. copy: function ( m ) {
  2002. var te = this.elements;
  2003. var me = m.elements;
  2004. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  2005. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  2006. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  2007. return this;
  2008. },
  2009. setFromMatrix4: function ( m ) {
  2010. var me = m.elements;
  2011. this.set(
  2012. me[ 0 ], me[ 4 ], me[ 8 ],
  2013. me[ 1 ], me[ 5 ], me[ 9 ],
  2014. me[ 2 ], me[ 6 ], me[ 10 ]
  2015. );
  2016. return this;
  2017. },
  2018. applyToBufferAttribute: function () {
  2019. var v1 = new Vector3();
  2020. return function applyToBufferAttribute( attribute ) {
  2021. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2022. v1.x = attribute.getX( i );
  2023. v1.y = attribute.getY( i );
  2024. v1.z = attribute.getZ( i );
  2025. v1.applyMatrix3( this );
  2026. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2027. }
  2028. return attribute;
  2029. };
  2030. }(),
  2031. multiply: function ( m ) {
  2032. return this.multiplyMatrices( this, m );
  2033. },
  2034. premultiply: function ( m ) {
  2035. return this.multiplyMatrices( m, this );
  2036. },
  2037. multiplyMatrices: function ( a, b ) {
  2038. var ae = a.elements;
  2039. var be = b.elements;
  2040. var te = this.elements;
  2041. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  2042. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  2043. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  2044. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  2045. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  2046. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  2047. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  2048. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  2049. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  2050. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  2051. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  2052. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  2053. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  2054. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  2055. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  2056. return this;
  2057. },
  2058. multiplyScalar: function ( s ) {
  2059. var te = this.elements;
  2060. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2061. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2062. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2063. return this;
  2064. },
  2065. determinant: function () {
  2066. var te = this.elements;
  2067. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2068. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2069. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2070. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2071. },
  2072. getInverse: function ( matrix, throwOnDegenerate ) {
  2073. if ( matrix && matrix.isMatrix4 ) {
  2074. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  2075. }
  2076. var me = matrix.elements,
  2077. te = this.elements,
  2078. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  2079. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  2080. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  2081. t11 = n33 * n22 - n32 * n23,
  2082. t12 = n32 * n13 - n33 * n12,
  2083. t13 = n23 * n12 - n22 * n13,
  2084. det = n11 * t11 + n21 * t12 + n31 * t13;
  2085. if ( det === 0 ) {
  2086. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  2087. if ( throwOnDegenerate === true ) {
  2088. throw new Error( msg );
  2089. } else {
  2090. console.warn( msg );
  2091. }
  2092. return this.identity();
  2093. }
  2094. var detInv = 1 / det;
  2095. te[ 0 ] = t11 * detInv;
  2096. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  2097. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  2098. te[ 3 ] = t12 * detInv;
  2099. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  2100. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  2101. te[ 6 ] = t13 * detInv;
  2102. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  2103. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  2104. return this;
  2105. },
  2106. transpose: function () {
  2107. var tmp, m = this.elements;
  2108. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2109. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2110. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2111. return this;
  2112. },
  2113. getNormalMatrix: function ( matrix4 ) {
  2114. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  2115. },
  2116. transposeIntoArray: function ( r ) {
  2117. var m = this.elements;
  2118. r[ 0 ] = m[ 0 ];
  2119. r[ 1 ] = m[ 3 ];
  2120. r[ 2 ] = m[ 6 ];
  2121. r[ 3 ] = m[ 1 ];
  2122. r[ 4 ] = m[ 4 ];
  2123. r[ 5 ] = m[ 7 ];
  2124. r[ 6 ] = m[ 2 ];
  2125. r[ 7 ] = m[ 5 ];
  2126. r[ 8 ] = m[ 8 ];
  2127. return this;
  2128. },
  2129. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  2130. var c = Math.cos( rotation );
  2131. var s = Math.sin( rotation );
  2132. this.set(
  2133. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  2134. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  2135. 0, 0, 1
  2136. );
  2137. },
  2138. scale: function ( sx, sy ) {
  2139. var te = this.elements;
  2140. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  2141. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  2142. return this;
  2143. },
  2144. rotate: function ( theta ) {
  2145. var c = Math.cos( theta );
  2146. var s = Math.sin( theta );
  2147. var te = this.elements;
  2148. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  2149. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  2150. te[ 0 ] = c * a11 + s * a21;
  2151. te[ 3 ] = c * a12 + s * a22;
  2152. te[ 6 ] = c * a13 + s * a23;
  2153. te[ 1 ] = - s * a11 + c * a21;
  2154. te[ 4 ] = - s * a12 + c * a22;
  2155. te[ 7 ] = - s * a13 + c * a23;
  2156. return this;
  2157. },
  2158. translate: function ( tx, ty ) {
  2159. var te = this.elements;
  2160. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  2161. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  2162. return this;
  2163. },
  2164. equals: function ( matrix ) {
  2165. var te = this.elements;
  2166. var me = matrix.elements;
  2167. for ( var i = 0; i < 9; i ++ ) {
  2168. if ( te[ i ] !== me[ i ] ) return false;
  2169. }
  2170. return true;
  2171. },
  2172. fromArray: function ( array, offset ) {
  2173. if ( offset === undefined ) offset = 0;
  2174. for ( var i = 0; i < 9; i ++ ) {
  2175. this.elements[ i ] = array[ i + offset ];
  2176. }
  2177. return this;
  2178. },
  2179. toArray: function ( array, offset ) {
  2180. if ( array === undefined ) array = [];
  2181. if ( offset === undefined ) offset = 0;
  2182. var te = this.elements;
  2183. array[ offset ] = te[ 0 ];
  2184. array[ offset + 1 ] = te[ 1 ];
  2185. array[ offset + 2 ] = te[ 2 ];
  2186. array[ offset + 3 ] = te[ 3 ];
  2187. array[ offset + 4 ] = te[ 4 ];
  2188. array[ offset + 5 ] = te[ 5 ];
  2189. array[ offset + 6 ] = te[ 6 ];
  2190. array[ offset + 7 ] = te[ 7 ];
  2191. array[ offset + 8 ] = te[ 8 ];
  2192. return array;
  2193. }
  2194. } );
  2195. /**
  2196. * @author mrdoob / http://mrdoob.com/
  2197. * @author alteredq / http://alteredqualia.com/
  2198. * @author szimek / https://github.com/szimek/
  2199. */
  2200. var textureId = 0;
  2201. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2202. Object.defineProperty( this, 'id', { value: textureId ++ } );
  2203. this.uuid = _Math.generateUUID();
  2204. this.name = '';
  2205. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  2206. this.mipmaps = [];
  2207. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  2208. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  2209. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  2210. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  2211. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  2212. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  2213. this.format = format !== undefined ? format : RGBAFormat;
  2214. this.type = type !== undefined ? type : UnsignedByteType;
  2215. this.offset = new Vector2( 0, 0 );
  2216. this.repeat = new Vector2( 1, 1 );
  2217. this.rotation = 0;
  2218. this.matrixAutoUpdate = true;
  2219. this.matrix = new Matrix3();
  2220. this.generateMipmaps = true;
  2221. this.premultiplyAlpha = false;
  2222. this.flipY = true;
  2223. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2224. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2225. //
  2226. // Also changing the encoding after already used by a Material will not automatically make the Material
  2227. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2228. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  2229. this.version = 0;
  2230. this.onUpdate = null;
  2231. }
  2232. Texture.DEFAULT_IMAGE = undefined;
  2233. Texture.DEFAULT_MAPPING = UVMapping;
  2234. Object.defineProperty( Texture.prototype, "needsUpdate", {
  2235. set: function ( value ) {
  2236. if ( value === true ) this.version ++;
  2237. }
  2238. } );
  2239. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  2240. constructor: Texture,
  2241. isTexture: true,
  2242. clone: function () {
  2243. return new this.constructor().copy( this );
  2244. },
  2245. copy: function ( source ) {
  2246. this.name = source.name;
  2247. this.image = source.image;
  2248. this.mipmaps = source.mipmaps.slice( 0 );
  2249. this.mapping = source.mapping;
  2250. this.wrapS = source.wrapS;
  2251. this.wrapT = source.wrapT;
  2252. this.magFilter = source.magFilter;
  2253. this.minFilter = source.minFilter;
  2254. this.anisotropy = source.anisotropy;
  2255. this.format = source.format;
  2256. this.type = source.type;
  2257. this.offset.copy( source.offset );
  2258. this.repeat.copy( source.repeat );
  2259. this.rotation = source.rotation;
  2260. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2261. this.matrix.copy( source.matrix );
  2262. this.generateMipmaps = source.generateMipmaps;
  2263. this.premultiplyAlpha = source.premultiplyAlpha;
  2264. this.flipY = source.flipY;
  2265. this.unpackAlignment = source.unpackAlignment;
  2266. this.encoding = source.encoding;
  2267. return this;
  2268. },
  2269. toJSON: function ( meta ) {
  2270. if ( meta.textures[ this.uuid ] !== undefined ) {
  2271. return meta.textures[ this.uuid ];
  2272. }
  2273. function getDataURL( image ) {
  2274. var canvas;
  2275. if ( image instanceof HTMLCanvasElement ) {
  2276. canvas = image;
  2277. } else {
  2278. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  2279. canvas.width = image.width;
  2280. canvas.height = image.height;
  2281. var context = canvas.getContext( '2d' );
  2282. if ( image instanceof ImageData ) {
  2283. context.putImageData( image, 0, 0 );
  2284. } else {
  2285. context.drawImage( image, 0, 0, image.width, image.height );
  2286. }
  2287. }
  2288. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  2289. return canvas.toDataURL( 'image/jpeg', 0.6 );
  2290. } else {
  2291. return canvas.toDataURL( 'image/png' );
  2292. }
  2293. }
  2294. var output = {
  2295. metadata: {
  2296. version: 4.5,
  2297. type: 'Texture',
  2298. generator: 'Texture.toJSON'
  2299. },
  2300. uuid: this.uuid,
  2301. name: this.name,
  2302. mapping: this.mapping,
  2303. repeat: [ this.repeat.x, this.repeat.y ],
  2304. offset: [ this.offset.x, this.offset.y ],
  2305. rotation: this.rotation,
  2306. wrap: [ this.wrapS, this.wrapT ],
  2307. minFilter: this.minFilter,
  2308. magFilter: this.magFilter,
  2309. anisotropy: this.anisotropy,
  2310. flipY: this.flipY
  2311. };
  2312. if ( this.image !== undefined ) {
  2313. // TODO: Move to THREE.Image
  2314. var image = this.image;
  2315. if ( image.uuid === undefined ) {
  2316. image.uuid = _Math.generateUUID(); // UGH
  2317. }
  2318. if ( meta.images[ image.uuid ] === undefined ) {
  2319. meta.images[ image.uuid ] = {
  2320. uuid: image.uuid,
  2321. url: getDataURL( image )
  2322. };
  2323. }
  2324. output.image = image.uuid;
  2325. }
  2326. meta.textures[ this.uuid ] = output;
  2327. return output;
  2328. },
  2329. dispose: function () {
  2330. this.dispatchEvent( { type: 'dispose' } );
  2331. },
  2332. transformUv: function ( uv ) {
  2333. if ( this.mapping !== UVMapping ) return;
  2334. uv.applyMatrix3( this.matrix );
  2335. if ( uv.x < 0 || uv.x > 1 ) {
  2336. switch ( this.wrapS ) {
  2337. case RepeatWrapping:
  2338. uv.x = uv.x - Math.floor( uv.x );
  2339. break;
  2340. case ClampToEdgeWrapping:
  2341. uv.x = uv.x < 0 ? 0 : 1;
  2342. break;
  2343. case MirroredRepeatWrapping:
  2344. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2345. uv.x = Math.ceil( uv.x ) - uv.x;
  2346. } else {
  2347. uv.x = uv.x - Math.floor( uv.x );
  2348. }
  2349. break;
  2350. }
  2351. }
  2352. if ( uv.y < 0 || uv.y > 1 ) {
  2353. switch ( this.wrapT ) {
  2354. case RepeatWrapping:
  2355. uv.y = uv.y - Math.floor( uv.y );
  2356. break;
  2357. case ClampToEdgeWrapping:
  2358. uv.y = uv.y < 0 ? 0 : 1;
  2359. break;
  2360. case MirroredRepeatWrapping:
  2361. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2362. uv.y = Math.ceil( uv.y ) - uv.y;
  2363. } else {
  2364. uv.y = uv.y - Math.floor( uv.y );
  2365. }
  2366. break;
  2367. }
  2368. }
  2369. if ( this.flipY ) {
  2370. uv.y = 1 - uv.y;
  2371. }
  2372. }
  2373. } );
  2374. /**
  2375. * @author supereggbert / http://www.paulbrunt.co.uk/
  2376. * @author philogb / http://blog.thejit.org/
  2377. * @author mikael emtinger / http://gomo.se/
  2378. * @author egraether / http://egraether.com/
  2379. * @author WestLangley / http://github.com/WestLangley
  2380. */
  2381. function Vector4( x, y, z, w ) {
  2382. this.x = x || 0;
  2383. this.y = y || 0;
  2384. this.z = z || 0;
  2385. this.w = ( w !== undefined ) ? w : 1;
  2386. }
  2387. Object.assign( Vector4.prototype, {
  2388. isVector4: true,
  2389. set: function ( x, y, z, w ) {
  2390. this.x = x;
  2391. this.y = y;
  2392. this.z = z;
  2393. this.w = w;
  2394. return this;
  2395. },
  2396. setScalar: function ( scalar ) {
  2397. this.x = scalar;
  2398. this.y = scalar;
  2399. this.z = scalar;
  2400. this.w = scalar;
  2401. return this;
  2402. },
  2403. setX: function ( x ) {
  2404. this.x = x;
  2405. return this;
  2406. },
  2407. setY: function ( y ) {
  2408. this.y = y;
  2409. return this;
  2410. },
  2411. setZ: function ( z ) {
  2412. this.z = z;
  2413. return this;
  2414. },
  2415. setW: function ( w ) {
  2416. this.w = w;
  2417. return this;
  2418. },
  2419. setComponent: function ( index, value ) {
  2420. switch ( index ) {
  2421. case 0: this.x = value; break;
  2422. case 1: this.y = value; break;
  2423. case 2: this.z = value; break;
  2424. case 3: this.w = value; break;
  2425. default: throw new Error( 'index is out of range: ' + index );
  2426. }
  2427. return this;
  2428. },
  2429. getComponent: function ( index ) {
  2430. switch ( index ) {
  2431. case 0: return this.x;
  2432. case 1: return this.y;
  2433. case 2: return this.z;
  2434. case 3: return this.w;
  2435. default: throw new Error( 'index is out of range: ' + index );
  2436. }
  2437. },
  2438. clone: function () {
  2439. return new this.constructor( this.x, this.y, this.z, this.w );
  2440. },
  2441. copy: function ( v ) {
  2442. this.x = v.x;
  2443. this.y = v.y;
  2444. this.z = v.z;
  2445. this.w = ( v.w !== undefined ) ? v.w : 1;
  2446. return this;
  2447. },
  2448. add: function ( v, w ) {
  2449. if ( w !== undefined ) {
  2450. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2451. return this.addVectors( v, w );
  2452. }
  2453. this.x += v.x;
  2454. this.y += v.y;
  2455. this.z += v.z;
  2456. this.w += v.w;
  2457. return this;
  2458. },
  2459. addScalar: function ( s ) {
  2460. this.x += s;
  2461. this.y += s;
  2462. this.z += s;
  2463. this.w += s;
  2464. return this;
  2465. },
  2466. addVectors: function ( a, b ) {
  2467. this.x = a.x + b.x;
  2468. this.y = a.y + b.y;
  2469. this.z = a.z + b.z;
  2470. this.w = a.w + b.w;
  2471. return this;
  2472. },
  2473. addScaledVector: function ( v, s ) {
  2474. this.x += v.x * s;
  2475. this.y += v.y * s;
  2476. this.z += v.z * s;
  2477. this.w += v.w * s;
  2478. return this;
  2479. },
  2480. sub: function ( v, w ) {
  2481. if ( w !== undefined ) {
  2482. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2483. return this.subVectors( v, w );
  2484. }
  2485. this.x -= v.x;
  2486. this.y -= v.y;
  2487. this.z -= v.z;
  2488. this.w -= v.w;
  2489. return this;
  2490. },
  2491. subScalar: function ( s ) {
  2492. this.x -= s;
  2493. this.y -= s;
  2494. this.z -= s;
  2495. this.w -= s;
  2496. return this;
  2497. },
  2498. subVectors: function ( a, b ) {
  2499. this.x = a.x - b.x;
  2500. this.y = a.y - b.y;
  2501. this.z = a.z - b.z;
  2502. this.w = a.w - b.w;
  2503. return this;
  2504. },
  2505. multiplyScalar: function ( scalar ) {
  2506. this.x *= scalar;
  2507. this.y *= scalar;
  2508. this.z *= scalar;
  2509. this.w *= scalar;
  2510. return this;
  2511. },
  2512. applyMatrix4: function ( m ) {
  2513. var x = this.x, y = this.y, z = this.z, w = this.w;
  2514. var e = m.elements;
  2515. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2516. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2517. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2518. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2519. return this;
  2520. },
  2521. divideScalar: function ( scalar ) {
  2522. return this.multiplyScalar( 1 / scalar );
  2523. },
  2524. setAxisAngleFromQuaternion: function ( q ) {
  2525. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2526. // q is assumed to be normalized
  2527. this.w = 2 * Math.acos( q.w );
  2528. var s = Math.sqrt( 1 - q.w * q.w );
  2529. if ( s < 0.0001 ) {
  2530. this.x = 1;
  2531. this.y = 0;
  2532. this.z = 0;
  2533. } else {
  2534. this.x = q.x / s;
  2535. this.y = q.y / s;
  2536. this.z = q.z / s;
  2537. }
  2538. return this;
  2539. },
  2540. setAxisAngleFromRotationMatrix: function ( m ) {
  2541. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2542. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2543. var angle, x, y, z, // variables for result
  2544. epsilon = 0.01, // margin to allow for rounding errors
  2545. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2546. te = m.elements,
  2547. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2548. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2549. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2550. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2551. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2552. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2553. // singularity found
  2554. // first check for identity matrix which must have +1 for all terms
  2555. // in leading diagonal and zero in other terms
  2556. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2557. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2558. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2559. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2560. // this singularity is identity matrix so angle = 0
  2561. this.set( 1, 0, 0, 0 );
  2562. return this; // zero angle, arbitrary axis
  2563. }
  2564. // otherwise this singularity is angle = 180
  2565. angle = Math.PI;
  2566. var xx = ( m11 + 1 ) / 2;
  2567. var yy = ( m22 + 1 ) / 2;
  2568. var zz = ( m33 + 1 ) / 2;
  2569. var xy = ( m12 + m21 ) / 4;
  2570. var xz = ( m13 + m31 ) / 4;
  2571. var yz = ( m23 + m32 ) / 4;
  2572. if ( ( xx > yy ) && ( xx > zz ) ) {
  2573. // m11 is the largest diagonal term
  2574. if ( xx < epsilon ) {
  2575. x = 0;
  2576. y = 0.707106781;
  2577. z = 0.707106781;
  2578. } else {
  2579. x = Math.sqrt( xx );
  2580. y = xy / x;
  2581. z = xz / x;
  2582. }
  2583. } else if ( yy > zz ) {
  2584. // m22 is the largest diagonal term
  2585. if ( yy < epsilon ) {
  2586. x = 0.707106781;
  2587. y = 0;
  2588. z = 0.707106781;
  2589. } else {
  2590. y = Math.sqrt( yy );
  2591. x = xy / y;
  2592. z = yz / y;
  2593. }
  2594. } else {
  2595. // m33 is the largest diagonal term so base result on this
  2596. if ( zz < epsilon ) {
  2597. x = 0.707106781;
  2598. y = 0.707106781;
  2599. z = 0;
  2600. } else {
  2601. z = Math.sqrt( zz );
  2602. x = xz / z;
  2603. y = yz / z;
  2604. }
  2605. }
  2606. this.set( x, y, z, angle );
  2607. return this; // return 180 deg rotation
  2608. }
  2609. // as we have reached here there are no singularities so we can handle normally
  2610. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2611. ( m13 - m31 ) * ( m13 - m31 ) +
  2612. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2613. if ( Math.abs( s ) < 0.001 ) s = 1;
  2614. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2615. // caught by singularity test above, but I've left it in just in case
  2616. this.x = ( m32 - m23 ) / s;
  2617. this.y = ( m13 - m31 ) / s;
  2618. this.z = ( m21 - m12 ) / s;
  2619. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2620. return this;
  2621. },
  2622. min: function ( v ) {
  2623. this.x = Math.min( this.x, v.x );
  2624. this.y = Math.min( this.y, v.y );
  2625. this.z = Math.min( this.z, v.z );
  2626. this.w = Math.min( this.w, v.w );
  2627. return this;
  2628. },
  2629. max: function ( v ) {
  2630. this.x = Math.max( this.x, v.x );
  2631. this.y = Math.max( this.y, v.y );
  2632. this.z = Math.max( this.z, v.z );
  2633. this.w = Math.max( this.w, v.w );
  2634. return this;
  2635. },
  2636. clamp: function ( min, max ) {
  2637. // assumes min < max, componentwise
  2638. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2639. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2640. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2641. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2642. return this;
  2643. },
  2644. clampScalar: function () {
  2645. var min, max;
  2646. return function clampScalar( minVal, maxVal ) {
  2647. if ( min === undefined ) {
  2648. min = new Vector4();
  2649. max = new Vector4();
  2650. }
  2651. min.set( minVal, minVal, minVal, minVal );
  2652. max.set( maxVal, maxVal, maxVal, maxVal );
  2653. return this.clamp( min, max );
  2654. };
  2655. }(),
  2656. clampLength: function ( min, max ) {
  2657. var length = this.length();
  2658. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2659. },
  2660. floor: function () {
  2661. this.x = Math.floor( this.x );
  2662. this.y = Math.floor( this.y );
  2663. this.z = Math.floor( this.z );
  2664. this.w = Math.floor( this.w );
  2665. return this;
  2666. },
  2667. ceil: function () {
  2668. this.x = Math.ceil( this.x );
  2669. this.y = Math.ceil( this.y );
  2670. this.z = Math.ceil( this.z );
  2671. this.w = Math.ceil( this.w );
  2672. return this;
  2673. },
  2674. round: function () {
  2675. this.x = Math.round( this.x );
  2676. this.y = Math.round( this.y );
  2677. this.z = Math.round( this.z );
  2678. this.w = Math.round( this.w );
  2679. return this;
  2680. },
  2681. roundToZero: function () {
  2682. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2683. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2684. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2685. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2686. return this;
  2687. },
  2688. negate: function () {
  2689. this.x = - this.x;
  2690. this.y = - this.y;
  2691. this.z = - this.z;
  2692. this.w = - this.w;
  2693. return this;
  2694. },
  2695. dot: function ( v ) {
  2696. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2697. },
  2698. lengthSq: function () {
  2699. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2700. },
  2701. length: function () {
  2702. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2703. },
  2704. lengthManhattan: function () {
  2705. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2706. },
  2707. normalize: function () {
  2708. return this.divideScalar( this.length() || 1 );
  2709. },
  2710. setLength: function ( length ) {
  2711. return this.normalize().multiplyScalar( length );
  2712. },
  2713. lerp: function ( v, alpha ) {
  2714. this.x += ( v.x - this.x ) * alpha;
  2715. this.y += ( v.y - this.y ) * alpha;
  2716. this.z += ( v.z - this.z ) * alpha;
  2717. this.w += ( v.w - this.w ) * alpha;
  2718. return this;
  2719. },
  2720. lerpVectors: function ( v1, v2, alpha ) {
  2721. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  2722. },
  2723. equals: function ( v ) {
  2724. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2725. },
  2726. fromArray: function ( array, offset ) {
  2727. if ( offset === undefined ) offset = 0;
  2728. this.x = array[ offset ];
  2729. this.y = array[ offset + 1 ];
  2730. this.z = array[ offset + 2 ];
  2731. this.w = array[ offset + 3 ];
  2732. return this;
  2733. },
  2734. toArray: function ( array, offset ) {
  2735. if ( array === undefined ) array = [];
  2736. if ( offset === undefined ) offset = 0;
  2737. array[ offset ] = this.x;
  2738. array[ offset + 1 ] = this.y;
  2739. array[ offset + 2 ] = this.z;
  2740. array[ offset + 3 ] = this.w;
  2741. return array;
  2742. },
  2743. fromBufferAttribute: function ( attribute, index, offset ) {
  2744. if ( offset !== undefined ) {
  2745. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2746. }
  2747. this.x = attribute.getX( index );
  2748. this.y = attribute.getY( index );
  2749. this.z = attribute.getZ( index );
  2750. this.w = attribute.getW( index );
  2751. return this;
  2752. }
  2753. } );
  2754. /**
  2755. * @author szimek / https://github.com/szimek/
  2756. * @author alteredq / http://alteredqualia.com/
  2757. * @author Marius Kintel / https://github.com/kintel
  2758. */
  2759. /*
  2760. In options, we can specify:
  2761. * Texture parameters for an auto-generated target texture
  2762. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2763. */
  2764. function WebGLRenderTarget( width, height, options ) {
  2765. this.uuid = _Math.generateUUID();
  2766. this.width = width;
  2767. this.height = height;
  2768. this.scissor = new Vector4( 0, 0, width, height );
  2769. this.scissorTest = false;
  2770. this.viewport = new Vector4( 0, 0, width, height );
  2771. options = options || {};
  2772. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  2773. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2774. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2775. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2776. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2777. }
  2778. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  2779. isWebGLRenderTarget: true,
  2780. setSize: function ( width, height ) {
  2781. if ( this.width !== width || this.height !== height ) {
  2782. this.width = width;
  2783. this.height = height;
  2784. this.dispose();
  2785. }
  2786. this.viewport.set( 0, 0, width, height );
  2787. this.scissor.set( 0, 0, width, height );
  2788. },
  2789. clone: function () {
  2790. return new this.constructor().copy( this );
  2791. },
  2792. copy: function ( source ) {
  2793. this.width = source.width;
  2794. this.height = source.height;
  2795. this.viewport.copy( source.viewport );
  2796. this.texture = source.texture.clone();
  2797. this.depthBuffer = source.depthBuffer;
  2798. this.stencilBuffer = source.stencilBuffer;
  2799. this.depthTexture = source.depthTexture;
  2800. return this;
  2801. },
  2802. dispose: function () {
  2803. this.dispatchEvent( { type: 'dispose' } );
  2804. }
  2805. } );
  2806. /**
  2807. * @author alteredq / http://alteredqualia.com
  2808. */
  2809. function WebGLRenderTargetCube( width, height, options ) {
  2810. WebGLRenderTarget.call( this, width, height, options );
  2811. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  2812. this.activeMipMapLevel = 0;
  2813. }
  2814. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  2815. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  2816. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  2817. /**
  2818. * @author alteredq / http://alteredqualia.com/
  2819. */
  2820. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2821. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2822. this.image = { data: data, width: width, height: height };
  2823. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2824. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2825. this.generateMipmaps = false;
  2826. this.flipY = false;
  2827. this.unpackAlignment = 1;
  2828. }
  2829. DataTexture.prototype = Object.create( Texture.prototype );
  2830. DataTexture.prototype.constructor = DataTexture;
  2831. DataTexture.prototype.isDataTexture = true;
  2832. /**
  2833. * @author mrdoob / http://mrdoob.com/
  2834. */
  2835. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2836. images = images !== undefined ? images : [];
  2837. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2838. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2839. this.flipY = false;
  2840. }
  2841. CubeTexture.prototype = Object.create( Texture.prototype );
  2842. CubeTexture.prototype.constructor = CubeTexture;
  2843. CubeTexture.prototype.isCubeTexture = true;
  2844. Object.defineProperty( CubeTexture.prototype, 'images', {
  2845. get: function () {
  2846. return this.image;
  2847. },
  2848. set: function ( value ) {
  2849. this.image = value;
  2850. }
  2851. } );
  2852. /**
  2853. * @author tschw
  2854. *
  2855. * Uniforms of a program.
  2856. * Those form a tree structure with a special top-level container for the root,
  2857. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2858. *
  2859. *
  2860. * Properties of inner nodes including the top-level container:
  2861. *
  2862. * .seq - array of nested uniforms
  2863. * .map - nested uniforms by name
  2864. *
  2865. *
  2866. * Methods of all nodes except the top-level container:
  2867. *
  2868. * .setValue( gl, value, [renderer] )
  2869. *
  2870. * uploads a uniform value(s)
  2871. * the 'renderer' parameter is needed for sampler uniforms
  2872. *
  2873. *
  2874. * Static methods of the top-level container (renderer factorizations):
  2875. *
  2876. * .upload( gl, seq, values, renderer )
  2877. *
  2878. * sets uniforms in 'seq' to 'values[id].value'
  2879. *
  2880. * .seqWithValue( seq, values ) : filteredSeq
  2881. *
  2882. * filters 'seq' entries with corresponding entry in values
  2883. *
  2884. *
  2885. * Methods of the top-level container (renderer factorizations):
  2886. *
  2887. * .setValue( gl, name, value )
  2888. *
  2889. * sets uniform with name 'name' to 'value'
  2890. *
  2891. * .set( gl, obj, prop )
  2892. *
  2893. * sets uniform from object and property with same name than uniform
  2894. *
  2895. * .setOptional( gl, obj, prop )
  2896. *
  2897. * like .set for an optional property of the object
  2898. *
  2899. */
  2900. var emptyTexture = new Texture();
  2901. var emptyCubeTexture = new CubeTexture();
  2902. // --- Base for inner nodes (including the root) ---
  2903. function UniformContainer() {
  2904. this.seq = [];
  2905. this.map = {};
  2906. }
  2907. // --- Utilities ---
  2908. // Array Caches (provide typed arrays for temporary by size)
  2909. var arrayCacheF32 = [];
  2910. var arrayCacheI32 = [];
  2911. // Float32Array caches used for uploading Matrix uniforms
  2912. var mat4array = new Float32Array( 16 );
  2913. var mat3array = new Float32Array( 9 );
  2914. // Flattening for arrays of vectors and matrices
  2915. function flatten( array, nBlocks, blockSize ) {
  2916. var firstElem = array[ 0 ];
  2917. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2918. // unoptimized: ! isNaN( firstElem )
  2919. // see http://jacksondunstan.com/articles/983
  2920. var n = nBlocks * blockSize,
  2921. r = arrayCacheF32[ n ];
  2922. if ( r === undefined ) {
  2923. r = new Float32Array( n );
  2924. arrayCacheF32[ n ] = r;
  2925. }
  2926. if ( nBlocks !== 0 ) {
  2927. firstElem.toArray( r, 0 );
  2928. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2929. offset += blockSize;
  2930. array[ i ].toArray( r, offset );
  2931. }
  2932. }
  2933. return r;
  2934. }
  2935. // Texture unit allocation
  2936. function allocTexUnits( renderer, n ) {
  2937. var r = arrayCacheI32[ n ];
  2938. if ( r === undefined ) {
  2939. r = new Int32Array( n );
  2940. arrayCacheI32[ n ] = r;
  2941. }
  2942. for ( var i = 0; i !== n; ++ i )
  2943. r[ i ] = renderer.allocTextureUnit();
  2944. return r;
  2945. }
  2946. // --- Setters ---
  2947. // Note: Defining these methods externally, because they come in a bunch
  2948. // and this way their names minify.
  2949. // Single scalar
  2950. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2951. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2952. // Single float vector (from flat array or THREE.VectorN)
  2953. function setValue2fv( gl, v ) {
  2954. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2955. else gl.uniform2f( this.addr, v.x, v.y );
  2956. }
  2957. function setValue3fv( gl, v ) {
  2958. if ( v.x !== undefined )
  2959. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2960. else if ( v.r !== undefined )
  2961. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2962. else
  2963. gl.uniform3fv( this.addr, v );
  2964. }
  2965. function setValue4fv( gl, v ) {
  2966. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2967. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2968. }
  2969. // Single matrix (from flat array or MatrixN)
  2970. function setValue2fm( gl, v ) {
  2971. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2972. }
  2973. function setValue3fm( gl, v ) {
  2974. if ( v.elements === undefined ) {
  2975. gl.uniformMatrix3fv( this.addr, false, v );
  2976. } else {
  2977. mat3array.set( v.elements );
  2978. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2979. }
  2980. }
  2981. function setValue4fm( gl, v ) {
  2982. if ( v.elements === undefined ) {
  2983. gl.uniformMatrix4fv( this.addr, false, v );
  2984. } else {
  2985. mat4array.set( v.elements );
  2986. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2987. }
  2988. }
  2989. // Single texture (2D / Cube)
  2990. function setValueT1( gl, v, renderer ) {
  2991. var unit = renderer.allocTextureUnit();
  2992. gl.uniform1i( this.addr, unit );
  2993. renderer.setTexture2D( v || emptyTexture, unit );
  2994. }
  2995. function setValueT6( gl, v, renderer ) {
  2996. var unit = renderer.allocTextureUnit();
  2997. gl.uniform1i( this.addr, unit );
  2998. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2999. }
  3000. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  3001. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  3002. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  3003. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  3004. // Helper to pick the right setter for the singular case
  3005. function getSingularSetter( type ) {
  3006. switch ( type ) {
  3007. case 0x1406: return setValue1f; // FLOAT
  3008. case 0x8b50: return setValue2fv; // _VEC2
  3009. case 0x8b51: return setValue3fv; // _VEC3
  3010. case 0x8b52: return setValue4fv; // _VEC4
  3011. case 0x8b5a: return setValue2fm; // _MAT2
  3012. case 0x8b5b: return setValue3fm; // _MAT3
  3013. case 0x8b5c: return setValue4fm; // _MAT4
  3014. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  3015. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  3016. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  3017. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  3018. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  3019. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  3020. }
  3021. }
  3022. // Array of scalars
  3023. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  3024. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  3025. // Array of vectors (flat or from THREE classes)
  3026. function setValueV2a( gl, v ) {
  3027. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  3028. }
  3029. function setValueV3a( gl, v ) {
  3030. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  3031. }
  3032. function setValueV4a( gl, v ) {
  3033. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  3034. }
  3035. // Array of matrices (flat or from THREE clases)
  3036. function setValueM2a( gl, v ) {
  3037. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  3038. }
  3039. function setValueM3a( gl, v ) {
  3040. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  3041. }
  3042. function setValueM4a( gl, v ) {
  3043. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  3044. }
  3045. // Array of textures (2D / Cube)
  3046. function setValueT1a( gl, v, renderer ) {
  3047. var n = v.length,
  3048. units = allocTexUnits( renderer, n );
  3049. gl.uniform1iv( this.addr, units );
  3050. for ( var i = 0; i !== n; ++ i ) {
  3051. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  3052. }
  3053. }
  3054. function setValueT6a( gl, v, renderer ) {
  3055. var n = v.length,
  3056. units = allocTexUnits( renderer, n );
  3057. gl.uniform1iv( this.addr, units );
  3058. for ( var i = 0; i !== n; ++ i ) {
  3059. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  3060. }
  3061. }
  3062. // Helper to pick the right setter for a pure (bottom-level) array
  3063. function getPureArraySetter( type ) {
  3064. switch ( type ) {
  3065. case 0x1406: return setValue1fv; // FLOAT
  3066. case 0x8b50: return setValueV2a; // _VEC2
  3067. case 0x8b51: return setValueV3a; // _VEC3
  3068. case 0x8b52: return setValueV4a; // _VEC4
  3069. case 0x8b5a: return setValueM2a; // _MAT2
  3070. case 0x8b5b: return setValueM3a; // _MAT3
  3071. case 0x8b5c: return setValueM4a; // _MAT4
  3072. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  3073. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  3074. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  3075. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  3076. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  3077. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  3078. }
  3079. }
  3080. // --- Uniform Classes ---
  3081. function SingleUniform( id, activeInfo, addr ) {
  3082. this.id = id;
  3083. this.addr = addr;
  3084. this.setValue = getSingularSetter( activeInfo.type );
  3085. // this.path = activeInfo.name; // DEBUG
  3086. }
  3087. function PureArrayUniform( id, activeInfo, addr ) {
  3088. this.id = id;
  3089. this.addr = addr;
  3090. this.size = activeInfo.size;
  3091. this.setValue = getPureArraySetter( activeInfo.type );
  3092. // this.path = activeInfo.name; // DEBUG
  3093. }
  3094. function StructuredUniform( id ) {
  3095. this.id = id;
  3096. UniformContainer.call( this ); // mix-in
  3097. }
  3098. StructuredUniform.prototype.setValue = function ( gl, value ) {
  3099. // Note: Don't need an extra 'renderer' parameter, since samplers
  3100. // are not allowed in structured uniforms.
  3101. var seq = this.seq;
  3102. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3103. var u = seq[ i ];
  3104. u.setValue( gl, value[ u.id ] );
  3105. }
  3106. };
  3107. // --- Top-level ---
  3108. // Parser - builds up the property tree from the path strings
  3109. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  3110. // extracts
  3111. // - the identifier (member name or array index)
  3112. // - followed by an optional right bracket (found when array index)
  3113. // - followed by an optional left bracket or dot (type of subscript)
  3114. //
  3115. // Note: These portions can be read in a non-overlapping fashion and
  3116. // allow straightforward parsing of the hierarchy that WebGL encodes
  3117. // in the uniform names.
  3118. function addUniform( container, uniformObject ) {
  3119. container.seq.push( uniformObject );
  3120. container.map[ uniformObject.id ] = uniformObject;
  3121. }
  3122. function parseUniform( activeInfo, addr, container ) {
  3123. var path = activeInfo.name,
  3124. pathLength = path.length;
  3125. // reset RegExp object, because of the early exit of a previous run
  3126. RePathPart.lastIndex = 0;
  3127. for ( ; ; ) {
  3128. var match = RePathPart.exec( path ),
  3129. matchEnd = RePathPart.lastIndex,
  3130. id = match[ 1 ],
  3131. idIsIndex = match[ 2 ] === ']',
  3132. subscript = match[ 3 ];
  3133. if ( idIsIndex ) id = id | 0; // convert to integer
  3134. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  3135. // bare name or "pure" bottom-level array "[0]" suffix
  3136. addUniform( container, subscript === undefined ?
  3137. new SingleUniform( id, activeInfo, addr ) :
  3138. new PureArrayUniform( id, activeInfo, addr ) );
  3139. break;
  3140. } else {
  3141. // step into inner node / create it in case it doesn't exist
  3142. var map = container.map, next = map[ id ];
  3143. if ( next === undefined ) {
  3144. next = new StructuredUniform( id );
  3145. addUniform( container, next );
  3146. }
  3147. container = next;
  3148. }
  3149. }
  3150. }
  3151. // Root Container
  3152. function WebGLUniforms( gl, program, renderer ) {
  3153. UniformContainer.call( this );
  3154. this.renderer = renderer;
  3155. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  3156. for ( var i = 0; i < n; ++ i ) {
  3157. var info = gl.getActiveUniform( program, i ),
  3158. path = info.name,
  3159. addr = gl.getUniformLocation( program, path );
  3160. parseUniform( info, addr, this );
  3161. }
  3162. }
  3163. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  3164. var u = this.map[ name ];
  3165. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  3166. };
  3167. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  3168. var v = object[ name ];
  3169. if ( v !== undefined ) this.setValue( gl, name, v );
  3170. };
  3171. // Static interface
  3172. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  3173. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3174. var u = seq[ i ],
  3175. v = values[ u.id ];
  3176. if ( v.needsUpdate !== false ) {
  3177. // note: always updating when .needsUpdate is undefined
  3178. u.setValue( gl, v.value, renderer );
  3179. }
  3180. }
  3181. };
  3182. WebGLUniforms.seqWithValue = function ( seq, values ) {
  3183. var r = [];
  3184. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3185. var u = seq[ i ];
  3186. if ( u.id in values ) r.push( u );
  3187. }
  3188. return r;
  3189. };
  3190. /**
  3191. * @author mrdoob / http://mrdoob.com/
  3192. */
  3193. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3194. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3195. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3196. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3197. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3198. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3199. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3200. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3201. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3202. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3203. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3204. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3205. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3206. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3207. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3208. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3209. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3210. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3211. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3212. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3213. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3214. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3215. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3216. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3217. function Color( r, g, b ) {
  3218. if ( g === undefined && b === undefined ) {
  3219. // r is THREE.Color, hex or string
  3220. return this.set( r );
  3221. }
  3222. return this.setRGB( r, g, b );
  3223. }
  3224. Object.assign( Color.prototype, {
  3225. isColor: true,
  3226. r: 1, g: 1, b: 1,
  3227. set: function ( value ) {
  3228. if ( value && value.isColor ) {
  3229. this.copy( value );
  3230. } else if ( typeof value === 'number' ) {
  3231. this.setHex( value );
  3232. } else if ( typeof value === 'string' ) {
  3233. this.setStyle( value );
  3234. }
  3235. return this;
  3236. },
  3237. setScalar: function ( scalar ) {
  3238. this.r = scalar;
  3239. this.g = scalar;
  3240. this.b = scalar;
  3241. return this;
  3242. },
  3243. setHex: function ( hex ) {
  3244. hex = Math.floor( hex );
  3245. this.r = ( hex >> 16 & 255 ) / 255;
  3246. this.g = ( hex >> 8 & 255 ) / 255;
  3247. this.b = ( hex & 255 ) / 255;
  3248. return this;
  3249. },
  3250. setRGB: function ( r, g, b ) {
  3251. this.r = r;
  3252. this.g = g;
  3253. this.b = b;
  3254. return this;
  3255. },
  3256. setHSL: function () {
  3257. function hue2rgb( p, q, t ) {
  3258. if ( t < 0 ) t += 1;
  3259. if ( t > 1 ) t -= 1;
  3260. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3261. if ( t < 1 / 2 ) return q;
  3262. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3263. return p;
  3264. }
  3265. return function setHSL( h, s, l ) {
  3266. // h,s,l ranges are in 0.0 - 1.0
  3267. h = _Math.euclideanModulo( h, 1 );
  3268. s = _Math.clamp( s, 0, 1 );
  3269. l = _Math.clamp( l, 0, 1 );
  3270. if ( s === 0 ) {
  3271. this.r = this.g = this.b = l;
  3272. } else {
  3273. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3274. var q = ( 2 * l ) - p;
  3275. this.r = hue2rgb( q, p, h + 1 / 3 );
  3276. this.g = hue2rgb( q, p, h );
  3277. this.b = hue2rgb( q, p, h - 1 / 3 );
  3278. }
  3279. return this;
  3280. };
  3281. }(),
  3282. setStyle: function ( style ) {
  3283. function handleAlpha( string ) {
  3284. if ( string === undefined ) return;
  3285. if ( parseFloat( string ) < 1 ) {
  3286. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3287. }
  3288. }
  3289. var m;
  3290. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3291. // rgb / hsl
  3292. var color;
  3293. var name = m[ 1 ];
  3294. var components = m[ 2 ];
  3295. switch ( name ) {
  3296. case 'rgb':
  3297. case 'rgba':
  3298. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3299. // rgb(255,0,0) rgba(255,0,0,0.5)
  3300. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3301. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3302. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3303. handleAlpha( color[ 5 ] );
  3304. return this;
  3305. }
  3306. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3307. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3308. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3309. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3310. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3311. handleAlpha( color[ 5 ] );
  3312. return this;
  3313. }
  3314. break;
  3315. case 'hsl':
  3316. case 'hsla':
  3317. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3318. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3319. var h = parseFloat( color[ 1 ] ) / 360;
  3320. var s = parseInt( color[ 2 ], 10 ) / 100;
  3321. var l = parseInt( color[ 3 ], 10 ) / 100;
  3322. handleAlpha( color[ 5 ] );
  3323. return this.setHSL( h, s, l );
  3324. }
  3325. break;
  3326. }
  3327. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3328. // hex color
  3329. var hex = m[ 1 ];
  3330. var size = hex.length;
  3331. if ( size === 3 ) {
  3332. // #ff0
  3333. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3334. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3335. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3336. return this;
  3337. } else if ( size === 6 ) {
  3338. // #ff0000
  3339. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3340. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3341. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3342. return this;
  3343. }
  3344. }
  3345. if ( style && style.length > 0 ) {
  3346. // color keywords
  3347. var hex = ColorKeywords[ style ];
  3348. if ( hex !== undefined ) {
  3349. // red
  3350. this.setHex( hex );
  3351. } else {
  3352. // unknown color
  3353. console.warn( 'THREE.Color: Unknown color ' + style );
  3354. }
  3355. }
  3356. return this;
  3357. },
  3358. clone: function () {
  3359. return new this.constructor( this.r, this.g, this.b );
  3360. },
  3361. copy: function ( color ) {
  3362. this.r = color.r;
  3363. this.g = color.g;
  3364. this.b = color.b;
  3365. return this;
  3366. },
  3367. copyGammaToLinear: function ( color, gammaFactor ) {
  3368. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3369. this.r = Math.pow( color.r, gammaFactor );
  3370. this.g = Math.pow( color.g, gammaFactor );
  3371. this.b = Math.pow( color.b, gammaFactor );
  3372. return this;
  3373. },
  3374. copyLinearToGamma: function ( color, gammaFactor ) {
  3375. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3376. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3377. this.r = Math.pow( color.r, safeInverse );
  3378. this.g = Math.pow( color.g, safeInverse );
  3379. this.b = Math.pow( color.b, safeInverse );
  3380. return this;
  3381. },
  3382. convertGammaToLinear: function () {
  3383. var r = this.r, g = this.g, b = this.b;
  3384. this.r = r * r;
  3385. this.g = g * g;
  3386. this.b = b * b;
  3387. return this;
  3388. },
  3389. convertLinearToGamma: function () {
  3390. this.r = Math.sqrt( this.r );
  3391. this.g = Math.sqrt( this.g );
  3392. this.b = Math.sqrt( this.b );
  3393. return this;
  3394. },
  3395. getHex: function () {
  3396. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3397. },
  3398. getHexString: function () {
  3399. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3400. },
  3401. getHSL: function ( optionalTarget ) {
  3402. // h,s,l ranges are in 0.0 - 1.0
  3403. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3404. var r = this.r, g = this.g, b = this.b;
  3405. var max = Math.max( r, g, b );
  3406. var min = Math.min( r, g, b );
  3407. var hue, saturation;
  3408. var lightness = ( min + max ) / 2.0;
  3409. if ( min === max ) {
  3410. hue = 0;
  3411. saturation = 0;
  3412. } else {
  3413. var delta = max - min;
  3414. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3415. switch ( max ) {
  3416. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3417. case g: hue = ( b - r ) / delta + 2; break;
  3418. case b: hue = ( r - g ) / delta + 4; break;
  3419. }
  3420. hue /= 6;
  3421. }
  3422. hsl.h = hue;
  3423. hsl.s = saturation;
  3424. hsl.l = lightness;
  3425. return hsl;
  3426. },
  3427. getStyle: function () {
  3428. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3429. },
  3430. offsetHSL: function ( h, s, l ) {
  3431. var hsl = this.getHSL();
  3432. hsl.h += h; hsl.s += s; hsl.l += l;
  3433. this.setHSL( hsl.h, hsl.s, hsl.l );
  3434. return this;
  3435. },
  3436. add: function ( color ) {
  3437. this.r += color.r;
  3438. this.g += color.g;
  3439. this.b += color.b;
  3440. return this;
  3441. },
  3442. addColors: function ( color1, color2 ) {
  3443. this.r = color1.r + color2.r;
  3444. this.g = color1.g + color2.g;
  3445. this.b = color1.b + color2.b;
  3446. return this;
  3447. },
  3448. addScalar: function ( s ) {
  3449. this.r += s;
  3450. this.g += s;
  3451. this.b += s;
  3452. return this;
  3453. },
  3454. sub: function( color ) {
  3455. this.r = Math.max( 0, this.r - color.r );
  3456. this.g = Math.max( 0, this.g - color.g );
  3457. this.b = Math.max( 0, this.b - color.b );
  3458. return this;
  3459. },
  3460. multiply: function ( color ) {
  3461. this.r *= color.r;
  3462. this.g *= color.g;
  3463. this.b *= color.b;
  3464. return this;
  3465. },
  3466. multiplyScalar: function ( s ) {
  3467. this.r *= s;
  3468. this.g *= s;
  3469. this.b *= s;
  3470. return this;
  3471. },
  3472. lerp: function ( color, alpha ) {
  3473. this.r += ( color.r - this.r ) * alpha;
  3474. this.g += ( color.g - this.g ) * alpha;
  3475. this.b += ( color.b - this.b ) * alpha;
  3476. return this;
  3477. },
  3478. equals: function ( c ) {
  3479. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3480. },
  3481. fromArray: function ( array, offset ) {
  3482. if ( offset === undefined ) offset = 0;
  3483. this.r = array[ offset ];
  3484. this.g = array[ offset + 1 ];
  3485. this.b = array[ offset + 2 ];
  3486. return this;
  3487. },
  3488. toArray: function ( array, offset ) {
  3489. if ( array === undefined ) array = [];
  3490. if ( offset === undefined ) offset = 0;
  3491. array[ offset ] = this.r;
  3492. array[ offset + 1 ] = this.g;
  3493. array[ offset + 2 ] = this.b;
  3494. return array;
  3495. },
  3496. toJSON: function () {
  3497. return this.getHex();
  3498. }
  3499. } );
  3500. /**
  3501. * Uniforms library for shared webgl shaders
  3502. */
  3503. var UniformsLib = {
  3504. common: {
  3505. diffuse: { value: new Color( 0xeeeeee ) },
  3506. opacity: { value: 1.0 },
  3507. map: { value: null },
  3508. uvTransform: { value: new Matrix3() },
  3509. alphaMap: { value: null },
  3510. },
  3511. specularmap: {
  3512. specularMap: { value: null },
  3513. },
  3514. envmap: {
  3515. envMap: { value: null },
  3516. flipEnvMap: { value: - 1 },
  3517. reflectivity: { value: 1.0 },
  3518. refractionRatio: { value: 0.98 }
  3519. },
  3520. aomap: {
  3521. aoMap: { value: null },
  3522. aoMapIntensity: { value: 1 }
  3523. },
  3524. lightmap: {
  3525. lightMap: { value: null },
  3526. lightMapIntensity: { value: 1 }
  3527. },
  3528. emissivemap: {
  3529. emissiveMap: { value: null }
  3530. },
  3531. bumpmap: {
  3532. bumpMap: { value: null },
  3533. bumpScale: { value: 1 }
  3534. },
  3535. normalmap: {
  3536. normalMap: { value: null },
  3537. normalScale: { value: new Vector2( 1, 1 ) }
  3538. },
  3539. displacementmap: {
  3540. displacementMap: { value: null },
  3541. displacementScale: { value: 1 },
  3542. displacementBias: { value: 0 }
  3543. },
  3544. roughnessmap: {
  3545. roughnessMap: { value: null }
  3546. },
  3547. metalnessmap: {
  3548. metalnessMap: { value: null }
  3549. },
  3550. gradientmap: {
  3551. gradientMap: { value: null }
  3552. },
  3553. fog: {
  3554. fogDensity: { value: 0.00025 },
  3555. fogNear: { value: 1 },
  3556. fogFar: { value: 2000 },
  3557. fogColor: { value: new Color( 0xffffff ) }
  3558. },
  3559. lights: {
  3560. ambientLightColor: { value: [] },
  3561. directionalLights: { value: [], properties: {
  3562. direction: {},
  3563. color: {},
  3564. shadow: {},
  3565. shadowBias: {},
  3566. shadowRadius: {},
  3567. shadowMapSize: {}
  3568. } },
  3569. directionalShadowMap: { value: [] },
  3570. directionalShadowMatrix: { value: [] },
  3571. spotLights: { value: [], properties: {
  3572. color: {},
  3573. position: {},
  3574. direction: {},
  3575. distance: {},
  3576. coneCos: {},
  3577. penumbraCos: {},
  3578. decay: {},
  3579. shadow: {},
  3580. shadowBias: {},
  3581. shadowRadius: {},
  3582. shadowMapSize: {}
  3583. } },
  3584. spotShadowMap: { value: [] },
  3585. spotShadowMatrix: { value: [] },
  3586. pointLights: { value: [], properties: {
  3587. color: {},
  3588. position: {},
  3589. decay: {},
  3590. distance: {},
  3591. shadow: {},
  3592. shadowBias: {},
  3593. shadowRadius: {},
  3594. shadowMapSize: {},
  3595. shadowCameraNear: {},
  3596. shadowCameraFar: {}
  3597. } },
  3598. pointShadowMap: { value: [] },
  3599. pointShadowMatrix: { value: [] },
  3600. hemisphereLights: { value: [], properties: {
  3601. direction: {},
  3602. skyColor: {},
  3603. groundColor: {}
  3604. } },
  3605. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3606. rectAreaLights: { value: [], properties: {
  3607. color: {},
  3608. position: {},
  3609. width: {},
  3610. height: {}
  3611. } }
  3612. },
  3613. points: {
  3614. diffuse: { value: new Color( 0xeeeeee ) },
  3615. opacity: { value: 1.0 },
  3616. size: { value: 1.0 },
  3617. scale: { value: 1.0 },
  3618. map: { value: null },
  3619. uvTransform: { value: new Matrix3() }
  3620. }
  3621. };
  3622. /**
  3623. * Uniform Utilities
  3624. */
  3625. var UniformsUtils = {
  3626. merge: function ( uniforms ) {
  3627. var merged = {};
  3628. for ( var u = 0; u < uniforms.length; u ++ ) {
  3629. var tmp = this.clone( uniforms[ u ] );
  3630. for ( var p in tmp ) {
  3631. merged[ p ] = tmp[ p ];
  3632. }
  3633. }
  3634. return merged;
  3635. },
  3636. clone: function ( uniforms_src ) {
  3637. var uniforms_dst = {};
  3638. for ( var u in uniforms_src ) {
  3639. uniforms_dst[ u ] = {};
  3640. for ( var p in uniforms_src[ u ] ) {
  3641. var parameter_src = uniforms_src[ u ][ p ];
  3642. if ( parameter_src && ( parameter_src.isColor ||
  3643. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3644. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3645. parameter_src.isTexture ) ) {
  3646. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3647. } else if ( Array.isArray( parameter_src ) ) {
  3648. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3649. } else {
  3650. uniforms_dst[ u ][ p ] = parameter_src;
  3651. }
  3652. }
  3653. }
  3654. return uniforms_dst;
  3655. }
  3656. };
  3657. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3658. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3659. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3660. 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";
  3661. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3662. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3663. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3664. 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";
  3665. 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 = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\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";
  3666. 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";
  3667. 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";
  3668. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3669. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3670. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3671. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3672. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3673. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3674. 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";
  3675. 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";
  3676. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  3677. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3678. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3679. 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";
  3680. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3681. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3682. 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";
  3683. 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, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = 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";
  3684. 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";
  3685. 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";
  3686. 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";
  3687. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3688. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3689. 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";
  3690. 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";
  3691. 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";
  3692. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3693. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3694. 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";
  3695. 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\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\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 = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 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";
  3696. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3697. 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";
  3698. 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";
  3699. 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";
  3700. 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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 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";
  3701. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  3702. 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";
  3703. 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";
  3704. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n";
  3705. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3706. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3707. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  3708. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n";
  3709. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3710. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3711. 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";
  3712. 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";
  3713. 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";
  3714. 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 );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\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";
  3715. 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 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\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";
  3716. 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";
  3717. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3718. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  3719. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3720. 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";
  3721. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3722. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3723. 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\tfloat shadow = 1.0;\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\tshadow = (\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\tshadow = (\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\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\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, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\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";
  3724. 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";
  3725. 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";
  3726. 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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3727. 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";
  3728. 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";
  3729. 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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";
  3730. 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";
  3731. 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";
  3732. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3733. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3734. 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";
  3735. 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";
  3736. 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 mat3 uvTransform;\n#endif\n";
  3737. 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 = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  3738. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3739. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3740. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3741. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  3742. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3743. 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";
  3744. 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";
  3745. 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#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3746. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n";
  3747. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n";
  3748. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3749. 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";
  3750. 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";
  3751. 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";
  3752. 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 <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";
  3753. 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";
  3754. 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 <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";
  3755. 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";
  3756. 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_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";
  3757. 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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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";
  3758. 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_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";
  3759. 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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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";
  3760. 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_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3761. 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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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";
  3762. 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";
  3763. 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";
  3764. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n";
  3765. var shadow_vert = "#include <fog_pars_vertex>\n#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\t#include <fog_vertex>\n}\n";
  3766. var ShaderChunk = {
  3767. alphamap_fragment: alphamap_fragment,
  3768. alphamap_pars_fragment: alphamap_pars_fragment,
  3769. alphatest_fragment: alphatest_fragment,
  3770. aomap_fragment: aomap_fragment,
  3771. aomap_pars_fragment: aomap_pars_fragment,
  3772. begin_vertex: begin_vertex,
  3773. beginnormal_vertex: beginnormal_vertex,
  3774. bsdfs: bsdfs,
  3775. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3776. clipping_planes_fragment: clipping_planes_fragment,
  3777. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3778. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3779. clipping_planes_vertex: clipping_planes_vertex,
  3780. color_fragment: color_fragment,
  3781. color_pars_fragment: color_pars_fragment,
  3782. color_pars_vertex: color_pars_vertex,
  3783. color_vertex: color_vertex,
  3784. common: common,
  3785. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3786. defaultnormal_vertex: defaultnormal_vertex,
  3787. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3788. displacementmap_vertex: displacementmap_vertex,
  3789. emissivemap_fragment: emissivemap_fragment,
  3790. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3791. encodings_fragment: encodings_fragment,
  3792. encodings_pars_fragment: encodings_pars_fragment,
  3793. envmap_fragment: envmap_fragment,
  3794. envmap_pars_fragment: envmap_pars_fragment,
  3795. envmap_pars_vertex: envmap_pars_vertex,
  3796. envmap_vertex: envmap_vertex,
  3797. fog_vertex: fog_vertex,
  3798. fog_pars_vertex: fog_pars_vertex,
  3799. fog_fragment: fog_fragment,
  3800. fog_pars_fragment: fog_pars_fragment,
  3801. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3802. lightmap_fragment: lightmap_fragment,
  3803. lightmap_pars_fragment: lightmap_pars_fragment,
  3804. lights_lambert_vertex: lights_lambert_vertex,
  3805. lights_pars: lights_pars,
  3806. lights_phong_fragment: lights_phong_fragment,
  3807. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3808. lights_physical_fragment: lights_physical_fragment,
  3809. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3810. lights_template: lights_template,
  3811. logdepthbuf_fragment: logdepthbuf_fragment,
  3812. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3813. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3814. logdepthbuf_vertex: logdepthbuf_vertex,
  3815. map_fragment: map_fragment,
  3816. map_pars_fragment: map_pars_fragment,
  3817. map_particle_fragment: map_particle_fragment,
  3818. map_particle_pars_fragment: map_particle_pars_fragment,
  3819. metalnessmap_fragment: metalnessmap_fragment,
  3820. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3821. morphnormal_vertex: morphnormal_vertex,
  3822. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3823. morphtarget_vertex: morphtarget_vertex,
  3824. normal_fragment: normal_fragment,
  3825. normalmap_pars_fragment: normalmap_pars_fragment,
  3826. packing: packing,
  3827. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3828. project_vertex: project_vertex,
  3829. dithering_fragment: dithering_fragment,
  3830. dithering_pars_fragment: dithering_pars_fragment,
  3831. roughnessmap_fragment: roughnessmap_fragment,
  3832. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3833. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3834. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3835. shadowmap_vertex: shadowmap_vertex,
  3836. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3837. skinbase_vertex: skinbase_vertex,
  3838. skinning_pars_vertex: skinning_pars_vertex,
  3839. skinning_vertex: skinning_vertex,
  3840. skinnormal_vertex: skinnormal_vertex,
  3841. specularmap_fragment: specularmap_fragment,
  3842. specularmap_pars_fragment: specularmap_pars_fragment,
  3843. tonemapping_fragment: tonemapping_fragment,
  3844. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3845. uv_pars_fragment: uv_pars_fragment,
  3846. uv_pars_vertex: uv_pars_vertex,
  3847. uv_vertex: uv_vertex,
  3848. uv2_pars_fragment: uv2_pars_fragment,
  3849. uv2_pars_vertex: uv2_pars_vertex,
  3850. uv2_vertex: uv2_vertex,
  3851. worldpos_vertex: worldpos_vertex,
  3852. cube_frag: cube_frag,
  3853. cube_vert: cube_vert,
  3854. depth_frag: depth_frag,
  3855. depth_vert: depth_vert,
  3856. distanceRGBA_frag: distanceRGBA_frag,
  3857. distanceRGBA_vert: distanceRGBA_vert,
  3858. equirect_frag: equirect_frag,
  3859. equirect_vert: equirect_vert,
  3860. linedashed_frag: linedashed_frag,
  3861. linedashed_vert: linedashed_vert,
  3862. meshbasic_frag: meshbasic_frag,
  3863. meshbasic_vert: meshbasic_vert,
  3864. meshlambert_frag: meshlambert_frag,
  3865. meshlambert_vert: meshlambert_vert,
  3866. meshphong_frag: meshphong_frag,
  3867. meshphong_vert: meshphong_vert,
  3868. meshphysical_frag: meshphysical_frag,
  3869. meshphysical_vert: meshphysical_vert,
  3870. normal_frag: normal_frag,
  3871. normal_vert: normal_vert,
  3872. points_frag: points_frag,
  3873. points_vert: points_vert,
  3874. shadow_frag: shadow_frag,
  3875. shadow_vert: shadow_vert
  3876. };
  3877. /**
  3878. * @author alteredq / http://alteredqualia.com/
  3879. * @author mrdoob / http://mrdoob.com/
  3880. * @author mikael emtinger / http://gomo.se/
  3881. */
  3882. var ShaderLib = {
  3883. basic: {
  3884. uniforms: UniformsUtils.merge( [
  3885. UniformsLib.common,
  3886. UniformsLib.specularmap,
  3887. UniformsLib.envmap,
  3888. UniformsLib.aomap,
  3889. UniformsLib.lightmap,
  3890. UniformsLib.fog
  3891. ] ),
  3892. vertexShader: ShaderChunk.meshbasic_vert,
  3893. fragmentShader: ShaderChunk.meshbasic_frag
  3894. },
  3895. lambert: {
  3896. uniforms: UniformsUtils.merge( [
  3897. UniformsLib.common,
  3898. UniformsLib.specularmap,
  3899. UniformsLib.envmap,
  3900. UniformsLib.aomap,
  3901. UniformsLib.lightmap,
  3902. UniformsLib.emissivemap,
  3903. UniformsLib.fog,
  3904. UniformsLib.lights,
  3905. {
  3906. emissive: { value: new Color( 0x000000 ) }
  3907. }
  3908. ] ),
  3909. vertexShader: ShaderChunk.meshlambert_vert,
  3910. fragmentShader: ShaderChunk.meshlambert_frag
  3911. },
  3912. phong: {
  3913. uniforms: UniformsUtils.merge( [
  3914. UniformsLib.common,
  3915. UniformsLib.specularmap,
  3916. UniformsLib.envmap,
  3917. UniformsLib.aomap,
  3918. UniformsLib.lightmap,
  3919. UniformsLib.emissivemap,
  3920. UniformsLib.bumpmap,
  3921. UniformsLib.normalmap,
  3922. UniformsLib.displacementmap,
  3923. UniformsLib.gradientmap,
  3924. UniformsLib.fog,
  3925. UniformsLib.lights,
  3926. {
  3927. emissive: { value: new Color( 0x000000 ) },
  3928. specular: { value: new Color( 0x111111 ) },
  3929. shininess: { value: 30 }
  3930. }
  3931. ] ),
  3932. vertexShader: ShaderChunk.meshphong_vert,
  3933. fragmentShader: ShaderChunk.meshphong_frag
  3934. },
  3935. standard: {
  3936. uniforms: UniformsUtils.merge( [
  3937. UniformsLib.common,
  3938. UniformsLib.envmap,
  3939. UniformsLib.aomap,
  3940. UniformsLib.lightmap,
  3941. UniformsLib.emissivemap,
  3942. UniformsLib.bumpmap,
  3943. UniformsLib.normalmap,
  3944. UniformsLib.displacementmap,
  3945. UniformsLib.roughnessmap,
  3946. UniformsLib.metalnessmap,
  3947. UniformsLib.fog,
  3948. UniformsLib.lights,
  3949. {
  3950. emissive: { value: new Color( 0x000000 ) },
  3951. roughness: { value: 0.5 },
  3952. metalness: { value: 0.5 },
  3953. envMapIntensity: { value: 1 } // temporary
  3954. }
  3955. ] ),
  3956. vertexShader: ShaderChunk.meshphysical_vert,
  3957. fragmentShader: ShaderChunk.meshphysical_frag
  3958. },
  3959. points: {
  3960. uniforms: UniformsUtils.merge( [
  3961. UniformsLib.points,
  3962. UniformsLib.fog
  3963. ] ),
  3964. vertexShader: ShaderChunk.points_vert,
  3965. fragmentShader: ShaderChunk.points_frag
  3966. },
  3967. dashed: {
  3968. uniforms: UniformsUtils.merge( [
  3969. UniformsLib.common,
  3970. UniformsLib.fog,
  3971. {
  3972. scale: { value: 1 },
  3973. dashSize: { value: 1 },
  3974. totalSize: { value: 2 }
  3975. }
  3976. ] ),
  3977. vertexShader: ShaderChunk.linedashed_vert,
  3978. fragmentShader: ShaderChunk.linedashed_frag
  3979. },
  3980. depth: {
  3981. uniforms: UniformsUtils.merge( [
  3982. UniformsLib.common,
  3983. UniformsLib.displacementmap
  3984. ] ),
  3985. vertexShader: ShaderChunk.depth_vert,
  3986. fragmentShader: ShaderChunk.depth_frag
  3987. },
  3988. normal: {
  3989. uniforms: UniformsUtils.merge( [
  3990. UniformsLib.common,
  3991. UniformsLib.bumpmap,
  3992. UniformsLib.normalmap,
  3993. UniformsLib.displacementmap,
  3994. {
  3995. opacity: { value: 1.0 }
  3996. }
  3997. ] ),
  3998. vertexShader: ShaderChunk.normal_vert,
  3999. fragmentShader: ShaderChunk.normal_frag
  4000. },
  4001. /* -------------------------------------------------------------------------
  4002. // Cube map shader
  4003. ------------------------------------------------------------------------- */
  4004. cube: {
  4005. uniforms: {
  4006. tCube: { value: null },
  4007. tFlip: { value: - 1 },
  4008. opacity: { value: 1.0 }
  4009. },
  4010. vertexShader: ShaderChunk.cube_vert,
  4011. fragmentShader: ShaderChunk.cube_frag
  4012. },
  4013. equirect: {
  4014. uniforms: {
  4015. tEquirect: { value: null },
  4016. },
  4017. vertexShader: ShaderChunk.equirect_vert,
  4018. fragmentShader: ShaderChunk.equirect_frag
  4019. },
  4020. distanceRGBA: {
  4021. uniforms: UniformsUtils.merge( [
  4022. UniformsLib.common,
  4023. UniformsLib.displacementmap,
  4024. {
  4025. referencePosition: { value: new Vector3() },
  4026. nearDistance: { value: 1 },
  4027. farDistance: { value: 1000 }
  4028. }
  4029. ] ),
  4030. vertexShader: ShaderChunk.distanceRGBA_vert,
  4031. fragmentShader: ShaderChunk.distanceRGBA_frag
  4032. },
  4033. shadow: {
  4034. uniforms: UniformsUtils.merge( [
  4035. UniformsLib.lights,
  4036. UniformsLib.fog,
  4037. {
  4038. color: { value: new Color( 0x00000 ) },
  4039. opacity: { value: 1.0 }
  4040. },
  4041. ] ),
  4042. vertexShader: ShaderChunk.shadow_vert,
  4043. fragmentShader: ShaderChunk.shadow_frag
  4044. }
  4045. };
  4046. ShaderLib.physical = {
  4047. uniforms: UniformsUtils.merge( [
  4048. ShaderLib.standard.uniforms,
  4049. {
  4050. clearCoat: { value: 0 },
  4051. clearCoatRoughness: { value: 0 }
  4052. }
  4053. ] ),
  4054. vertexShader: ShaderChunk.meshphysical_vert,
  4055. fragmentShader: ShaderChunk.meshphysical_frag
  4056. };
  4057. /**
  4058. * @author bhouston / http://clara.io
  4059. */
  4060. function Box2( min, max ) {
  4061. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  4062. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  4063. }
  4064. Object.assign( Box2.prototype, {
  4065. set: function ( min, max ) {
  4066. this.min.copy( min );
  4067. this.max.copy( max );
  4068. return this;
  4069. },
  4070. setFromPoints: function ( points ) {
  4071. this.makeEmpty();
  4072. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4073. this.expandByPoint( points[ i ] );
  4074. }
  4075. return this;
  4076. },
  4077. setFromCenterAndSize: function () {
  4078. var v1 = new Vector2();
  4079. return function setFromCenterAndSize( center, size ) {
  4080. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4081. this.min.copy( center ).sub( halfSize );
  4082. this.max.copy( center ).add( halfSize );
  4083. return this;
  4084. };
  4085. }(),
  4086. clone: function () {
  4087. return new this.constructor().copy( this );
  4088. },
  4089. copy: function ( box ) {
  4090. this.min.copy( box.min );
  4091. this.max.copy( box.max );
  4092. return this;
  4093. },
  4094. makeEmpty: function () {
  4095. this.min.x = this.min.y = + Infinity;
  4096. this.max.x = this.max.y = - Infinity;
  4097. return this;
  4098. },
  4099. isEmpty: function () {
  4100. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4101. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  4102. },
  4103. getCenter: function ( optionalTarget ) {
  4104. var result = optionalTarget || new Vector2();
  4105. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4106. },
  4107. getSize: function ( optionalTarget ) {
  4108. var result = optionalTarget || new Vector2();
  4109. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  4110. },
  4111. expandByPoint: function ( point ) {
  4112. this.min.min( point );
  4113. this.max.max( point );
  4114. return this;
  4115. },
  4116. expandByVector: function ( vector ) {
  4117. this.min.sub( vector );
  4118. this.max.add( vector );
  4119. return this;
  4120. },
  4121. expandByScalar: function ( scalar ) {
  4122. this.min.addScalar( - scalar );
  4123. this.max.addScalar( scalar );
  4124. return this;
  4125. },
  4126. containsPoint: function ( point ) {
  4127. return point.x < this.min.x || point.x > this.max.x ||
  4128. point.y < this.min.y || point.y > this.max.y ? false : true;
  4129. },
  4130. containsBox: function ( box ) {
  4131. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4132. this.min.y <= box.min.y && box.max.y <= this.max.y;
  4133. },
  4134. getParameter: function ( point, optionalTarget ) {
  4135. // This can potentially have a divide by zero if the box
  4136. // has a size dimension of 0.
  4137. var result = optionalTarget || new Vector2();
  4138. return result.set(
  4139. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4140. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  4141. );
  4142. },
  4143. intersectsBox: function ( box ) {
  4144. // using 4 splitting planes to rule out intersections
  4145. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4146. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  4147. },
  4148. clampPoint: function ( point, optionalTarget ) {
  4149. var result = optionalTarget || new Vector2();
  4150. return result.copy( point ).clamp( this.min, this.max );
  4151. },
  4152. distanceToPoint: function () {
  4153. var v1 = new Vector2();
  4154. return function distanceToPoint( point ) {
  4155. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4156. return clampedPoint.sub( point ).length();
  4157. };
  4158. }(),
  4159. intersect: function ( box ) {
  4160. this.min.max( box.min );
  4161. this.max.min( box.max );
  4162. return this;
  4163. },
  4164. union: function ( box ) {
  4165. this.min.min( box.min );
  4166. this.max.max( box.max );
  4167. return this;
  4168. },
  4169. translate: function ( offset ) {
  4170. this.min.add( offset );
  4171. this.max.add( offset );
  4172. return this;
  4173. },
  4174. equals: function ( box ) {
  4175. return box.min.equals( this.min ) && box.max.equals( this.max );
  4176. }
  4177. } );
  4178. /**
  4179. * @author mikael emtinger / http://gomo.se/
  4180. * @author alteredq / http://alteredqualia.com/
  4181. */
  4182. function WebGLFlareRenderer( renderer, gl, state, textures, capabilities ) {
  4183. var vertexBuffer, elementBuffer;
  4184. var shader, program, attributes, uniforms;
  4185. var tempTexture, occlusionTexture;
  4186. function init() {
  4187. var vertices = new Float32Array( [
  4188. - 1, - 1, 0, 0,
  4189. 1, - 1, 1, 0,
  4190. 1, 1, 1, 1,
  4191. - 1, 1, 0, 1
  4192. ] );
  4193. var faces = new Uint16Array( [
  4194. 0, 1, 2,
  4195. 0, 2, 3
  4196. ] );
  4197. // buffers
  4198. vertexBuffer = gl.createBuffer();
  4199. elementBuffer = gl.createBuffer();
  4200. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4201. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4202. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4203. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4204. // textures
  4205. tempTexture = gl.createTexture();
  4206. occlusionTexture = gl.createTexture();
  4207. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4208. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  4209. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  4210. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  4211. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  4212. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  4213. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4214. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  4215. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  4216. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  4217. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  4218. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  4219. shader = {
  4220. vertexShader: [
  4221. "uniform lowp int renderType;",
  4222. "uniform vec3 screenPosition;",
  4223. "uniform vec2 scale;",
  4224. "uniform float rotation;",
  4225. "uniform sampler2D occlusionMap;",
  4226. "attribute vec2 position;",
  4227. "attribute vec2 uv;",
  4228. "varying vec2 vUV;",
  4229. "varying float vVisibility;",
  4230. "void main() {",
  4231. "vUV = uv;",
  4232. "vec2 pos = position;",
  4233. "if ( renderType == 2 ) {",
  4234. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  4235. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  4236. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  4237. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  4238. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  4239. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  4240. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  4241. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  4242. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  4243. "vVisibility = visibility.r / 9.0;",
  4244. "vVisibility *= 1.0 - visibility.g / 9.0;",
  4245. "vVisibility *= visibility.b / 9.0;",
  4246. "vVisibility *= 1.0 - visibility.a / 9.0;",
  4247. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  4248. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  4249. "}",
  4250. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4251. "}"
  4252. ].join( "\n" ),
  4253. fragmentShader: [
  4254. "uniform lowp int renderType;",
  4255. "uniform sampler2D map;",
  4256. "uniform float opacity;",
  4257. "uniform vec3 color;",
  4258. "varying vec2 vUV;",
  4259. "varying float vVisibility;",
  4260. "void main() {",
  4261. // pink square
  4262. "if ( renderType == 0 ) {",
  4263. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4264. // restore
  4265. "} else if ( renderType == 1 ) {",
  4266. "gl_FragColor = texture2D( map, vUV );",
  4267. // flare
  4268. "} else {",
  4269. "vec4 texture = texture2D( map, vUV );",
  4270. "texture.a *= opacity * vVisibility;",
  4271. "gl_FragColor = texture;",
  4272. "gl_FragColor.rgb *= color;",
  4273. "}",
  4274. "}"
  4275. ].join( "\n" )
  4276. };
  4277. program = createProgram( shader );
  4278. attributes = {
  4279. vertex: gl.getAttribLocation ( program, "position" ),
  4280. uv: gl.getAttribLocation ( program, "uv" )
  4281. };
  4282. uniforms = {
  4283. renderType: gl.getUniformLocation( program, "renderType" ),
  4284. map: gl.getUniformLocation( program, "map" ),
  4285. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4286. opacity: gl.getUniformLocation( program, "opacity" ),
  4287. color: gl.getUniformLocation( program, "color" ),
  4288. scale: gl.getUniformLocation( program, "scale" ),
  4289. rotation: gl.getUniformLocation( program, "rotation" ),
  4290. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4291. };
  4292. }
  4293. /*
  4294. * Render lens flares
  4295. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4296. * reads these back and calculates occlusion.
  4297. */
  4298. this.render = function ( flares, scene, camera, viewport ) {
  4299. if ( flares.length === 0 ) return;
  4300. var tempPosition = new Vector3();
  4301. var invAspect = viewport.w / viewport.z,
  4302. halfViewportWidth = viewport.z * 0.5,
  4303. halfViewportHeight = viewport.w * 0.5;
  4304. var size = 16 / viewport.w,
  4305. scale = new Vector2( size * invAspect, size );
  4306. var screenPosition = new Vector3( 1, 1, 0 ),
  4307. screenPositionPixels = new Vector2( 1, 1 );
  4308. var validArea = new Box2();
  4309. validArea.min.set( viewport.x, viewport.y );
  4310. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4311. if ( program === undefined ) {
  4312. init();
  4313. }
  4314. state.useProgram( program );
  4315. state.initAttributes();
  4316. state.enableAttribute( attributes.vertex );
  4317. state.enableAttribute( attributes.uv );
  4318. state.disableUnusedAttributes();
  4319. // loop through all lens flares to update their occlusion and positions
  4320. // setup gl and common used attribs/uniforms
  4321. gl.uniform1i( uniforms.occlusionMap, 0 );
  4322. gl.uniform1i( uniforms.map, 1 );
  4323. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4324. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4325. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4326. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4327. state.disable( gl.CULL_FACE );
  4328. state.buffers.depth.setMask( false );
  4329. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4330. size = 16 / viewport.w;
  4331. scale.set( size * invAspect, size );
  4332. // calc object screen position
  4333. var flare = flares[ i ];
  4334. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4335. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4336. tempPosition.applyMatrix4( camera.projectionMatrix );
  4337. // setup arrays for gl programs
  4338. screenPosition.copy( tempPosition );
  4339. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4340. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4341. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4342. // screen cull
  4343. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4344. // save current RGB to temp texture
  4345. state.activeTexture( gl.TEXTURE0 );
  4346. state.bindTexture( gl.TEXTURE_2D, null );
  4347. state.activeTexture( gl.TEXTURE1 );
  4348. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4349. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4350. // render pink quad
  4351. gl.uniform1i( uniforms.renderType, 0 );
  4352. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4353. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4354. state.disable( gl.BLEND );
  4355. state.enable( gl.DEPTH_TEST );
  4356. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4357. // copy result to occlusionMap
  4358. state.activeTexture( gl.TEXTURE0 );
  4359. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4360. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4361. // restore graphics
  4362. gl.uniform1i( uniforms.renderType, 1 );
  4363. state.disable( gl.DEPTH_TEST );
  4364. state.activeTexture( gl.TEXTURE1 );
  4365. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4366. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4367. // update object positions
  4368. flare.positionScreen.copy( screenPosition );
  4369. if ( flare.customUpdateCallback ) {
  4370. flare.customUpdateCallback( flare );
  4371. } else {
  4372. flare.updateLensFlares();
  4373. }
  4374. // render flares
  4375. gl.uniform1i( uniforms.renderType, 2 );
  4376. state.enable( gl.BLEND );
  4377. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4378. var sprite = flare.lensFlares[ j ];
  4379. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4380. screenPosition.x = sprite.x;
  4381. screenPosition.y = sprite.y;
  4382. screenPosition.z = sprite.z;
  4383. size = sprite.size * sprite.scale / viewport.w;
  4384. scale.x = size * invAspect;
  4385. scale.y = size;
  4386. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4387. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4388. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4389. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4390. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4391. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4392. textures.setTexture2D( sprite.texture, 1 );
  4393. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4394. }
  4395. }
  4396. }
  4397. }
  4398. // restore gl
  4399. state.enable( gl.CULL_FACE );
  4400. state.enable( gl.DEPTH_TEST );
  4401. state.buffers.depth.setMask( true );
  4402. state.reset();
  4403. };
  4404. function createProgram( shader ) {
  4405. var program = gl.createProgram();
  4406. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4407. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4408. var prefix = "precision " + capabilities.precision + " float;\n";
  4409. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4410. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4411. gl.compileShader( fragmentShader );
  4412. gl.compileShader( vertexShader );
  4413. gl.attachShader( program, fragmentShader );
  4414. gl.attachShader( program, vertexShader );
  4415. gl.linkProgram( program );
  4416. return program;
  4417. }
  4418. }
  4419. /**
  4420. * @author mrdoob / http://mrdoob.com/
  4421. */
  4422. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  4423. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  4424. this.needsUpdate = true;
  4425. }
  4426. CanvasTexture.prototype = Object.create( Texture.prototype );
  4427. CanvasTexture.prototype.constructor = CanvasTexture;
  4428. /**
  4429. * @author mikael emtinger / http://gomo.se/
  4430. * @author alteredq / http://alteredqualia.com/
  4431. */
  4432. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  4433. var vertexBuffer, elementBuffer;
  4434. var program, attributes, uniforms;
  4435. var texture;
  4436. // decompose matrixWorld
  4437. var spritePosition = new Vector3();
  4438. var spriteRotation = new Quaternion();
  4439. var spriteScale = new Vector3();
  4440. function init() {
  4441. var vertices = new Float32Array( [
  4442. - 0.5, - 0.5, 0, 0,
  4443. 0.5, - 0.5, 1, 0,
  4444. 0.5, 0.5, 1, 1,
  4445. - 0.5, 0.5, 0, 1
  4446. ] );
  4447. var faces = new Uint16Array( [
  4448. 0, 1, 2,
  4449. 0, 2, 3
  4450. ] );
  4451. vertexBuffer = gl.createBuffer();
  4452. elementBuffer = gl.createBuffer();
  4453. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4454. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4455. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4456. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4457. program = createProgram();
  4458. attributes = {
  4459. position: gl.getAttribLocation ( program, 'position' ),
  4460. uv: gl.getAttribLocation ( program, 'uv' )
  4461. };
  4462. uniforms = {
  4463. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4464. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4465. rotation: gl.getUniformLocation( program, 'rotation' ),
  4466. scale: gl.getUniformLocation( program, 'scale' ),
  4467. color: gl.getUniformLocation( program, 'color' ),
  4468. map: gl.getUniformLocation( program, 'map' ),
  4469. opacity: gl.getUniformLocation( program, 'opacity' ),
  4470. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4471. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4472. fogType: gl.getUniformLocation( program, 'fogType' ),
  4473. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4474. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4475. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4476. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4477. fogDepth: gl.getUniformLocation( program, 'fogDepth' ),
  4478. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4479. };
  4480. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4481. canvas.width = 8;
  4482. canvas.height = 8;
  4483. var context = canvas.getContext( '2d' );
  4484. context.fillStyle = 'white';
  4485. context.fillRect( 0, 0, 8, 8 );
  4486. texture = new CanvasTexture( canvas );
  4487. }
  4488. this.render = function ( sprites, scene, camera ) {
  4489. if ( sprites.length === 0 ) return;
  4490. // setup gl
  4491. if ( program === undefined ) {
  4492. init();
  4493. }
  4494. state.useProgram( program );
  4495. state.initAttributes();
  4496. state.enableAttribute( attributes.position );
  4497. state.enableAttribute( attributes.uv );
  4498. state.disableUnusedAttributes();
  4499. state.disable( gl.CULL_FACE );
  4500. state.enable( gl.BLEND );
  4501. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4502. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4503. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4504. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4505. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4506. state.activeTexture( gl.TEXTURE0 );
  4507. gl.uniform1i( uniforms.map, 0 );
  4508. var oldFogType = 0;
  4509. var sceneFogType = 0;
  4510. var fog = scene.fog;
  4511. if ( fog ) {
  4512. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4513. if ( fog.isFog ) {
  4514. gl.uniform1f( uniforms.fogNear, fog.near );
  4515. gl.uniform1f( uniforms.fogFar, fog.far );
  4516. gl.uniform1i( uniforms.fogType, 1 );
  4517. oldFogType = 1;
  4518. sceneFogType = 1;
  4519. } else if ( fog.isFogExp2 ) {
  4520. gl.uniform1f( uniforms.fogDensity, fog.density );
  4521. gl.uniform1i( uniforms.fogType, 2 );
  4522. oldFogType = 2;
  4523. sceneFogType = 2;
  4524. }
  4525. } else {
  4526. gl.uniform1i( uniforms.fogType, 0 );
  4527. oldFogType = 0;
  4528. sceneFogType = 0;
  4529. }
  4530. // update positions and sort
  4531. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4532. var sprite = sprites[ i ];
  4533. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4534. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4535. }
  4536. sprites.sort( painterSortStable );
  4537. // render all sprites
  4538. var scale = [];
  4539. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4540. var sprite = sprites[ i ];
  4541. var material = sprite.material;
  4542. if ( material.visible === false ) continue;
  4543. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  4544. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4545. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4546. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4547. scale[ 0 ] = spriteScale.x;
  4548. scale[ 1 ] = spriteScale.y;
  4549. var fogType = 0;
  4550. if ( scene.fog && material.fog ) {
  4551. fogType = sceneFogType;
  4552. }
  4553. if ( oldFogType !== fogType ) {
  4554. gl.uniform1i( uniforms.fogType, fogType );
  4555. oldFogType = fogType;
  4556. }
  4557. if ( material.map !== null ) {
  4558. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4559. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4560. } else {
  4561. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4562. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4563. }
  4564. gl.uniform1f( uniforms.opacity, material.opacity );
  4565. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4566. gl.uniform1f( uniforms.rotation, material.rotation );
  4567. gl.uniform2fv( uniforms.scale, scale );
  4568. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4569. state.buffers.depth.setTest( material.depthTest );
  4570. state.buffers.depth.setMask( material.depthWrite );
  4571. textures.setTexture2D( material.map || texture, 0 );
  4572. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4573. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  4574. }
  4575. // restore gl
  4576. state.enable( gl.CULL_FACE );
  4577. state.reset();
  4578. };
  4579. function createProgram() {
  4580. var program = gl.createProgram();
  4581. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4582. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4583. gl.shaderSource( vertexShader, [
  4584. 'precision ' + capabilities.precision + ' float;',
  4585. '#define SHADER_NAME ' + 'SpriteMaterial',
  4586. 'uniform mat4 modelViewMatrix;',
  4587. 'uniform mat4 projectionMatrix;',
  4588. 'uniform float rotation;',
  4589. 'uniform vec2 scale;',
  4590. 'uniform vec2 uvOffset;',
  4591. 'uniform vec2 uvScale;',
  4592. 'attribute vec2 position;',
  4593. 'attribute vec2 uv;',
  4594. 'varying vec2 vUV;',
  4595. 'varying float fogDepth;',
  4596. 'void main() {',
  4597. 'vUV = uvOffset + uv * uvScale;',
  4598. 'vec2 alignedPosition = position * scale;',
  4599. 'vec2 rotatedPosition;',
  4600. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4601. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4602. 'vec4 mvPosition;',
  4603. 'mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4604. 'mvPosition.xy += rotatedPosition;',
  4605. 'gl_Position = projectionMatrix * mvPosition;',
  4606. 'fogDepth = - mvPosition.z;',
  4607. '}'
  4608. ].join( '\n' ) );
  4609. gl.shaderSource( fragmentShader, [
  4610. 'precision ' + capabilities.precision + ' float;',
  4611. '#define SHADER_NAME ' + 'SpriteMaterial',
  4612. 'uniform vec3 color;',
  4613. 'uniform sampler2D map;',
  4614. 'uniform float opacity;',
  4615. 'uniform int fogType;',
  4616. 'uniform vec3 fogColor;',
  4617. 'uniform float fogDensity;',
  4618. 'uniform float fogNear;',
  4619. 'uniform float fogFar;',
  4620. 'uniform float alphaTest;',
  4621. 'varying vec2 vUV;',
  4622. 'varying float fogDepth;',
  4623. 'void main() {',
  4624. 'vec4 texture = texture2D( map, vUV );',
  4625. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4626. 'if ( gl_FragColor.a < alphaTest ) discard;',
  4627. 'if ( fogType > 0 ) {',
  4628. 'float fogFactor = 0.0;',
  4629. 'if ( fogType == 1 ) {',
  4630. 'fogFactor = smoothstep( fogNear, fogFar, fogDepth );',
  4631. '} else {',
  4632. 'const float LOG2 = 1.442695;',
  4633. 'fogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );',
  4634. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4635. '}',
  4636. 'gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );',
  4637. '}',
  4638. '}'
  4639. ].join( '\n' ) );
  4640. gl.compileShader( vertexShader );
  4641. gl.compileShader( fragmentShader );
  4642. gl.attachShader( program, vertexShader );
  4643. gl.attachShader( program, fragmentShader );
  4644. gl.linkProgram( program );
  4645. return program;
  4646. }
  4647. function painterSortStable( a, b ) {
  4648. if ( a.renderOrder !== b.renderOrder ) {
  4649. return a.renderOrder - b.renderOrder;
  4650. } else if ( a.z !== b.z ) {
  4651. return b.z - a.z;
  4652. } else {
  4653. return b.id - a.id;
  4654. }
  4655. }
  4656. }
  4657. /**
  4658. * @author mrdoob / http://mrdoob.com/
  4659. * @author alteredq / http://alteredqualia.com/
  4660. */
  4661. var materialId = 0;
  4662. function Material() {
  4663. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4664. this.uuid = _Math.generateUUID();
  4665. this.name = '';
  4666. this.type = 'Material';
  4667. this.fog = true;
  4668. this.lights = true;
  4669. this.blending = NormalBlending;
  4670. this.side = FrontSide;
  4671. this.flatShading = false;
  4672. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4673. this.opacity = 1;
  4674. this.transparent = false;
  4675. this.blendSrc = SrcAlphaFactor;
  4676. this.blendDst = OneMinusSrcAlphaFactor;
  4677. this.blendEquation = AddEquation;
  4678. this.blendSrcAlpha = null;
  4679. this.blendDstAlpha = null;
  4680. this.blendEquationAlpha = null;
  4681. this.depthFunc = LessEqualDepth;
  4682. this.depthTest = true;
  4683. this.depthWrite = true;
  4684. this.clippingPlanes = null;
  4685. this.clipIntersection = false;
  4686. this.clipShadows = false;
  4687. this.colorWrite = true;
  4688. this.precision = null; // override the renderer's default precision for this material
  4689. this.polygonOffset = false;
  4690. this.polygonOffsetFactor = 0;
  4691. this.polygonOffsetUnits = 0;
  4692. this.dithering = false;
  4693. this.alphaTest = 0;
  4694. this.premultipliedAlpha = false;
  4695. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4696. this.visible = true;
  4697. this.userData = {};
  4698. this.needsUpdate = true;
  4699. }
  4700. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4701. isMaterial: true,
  4702. onBeforeCompile: function () {},
  4703. setValues: function ( values ) {
  4704. if ( values === undefined ) return;
  4705. for ( var key in values ) {
  4706. var newValue = values[ key ];
  4707. if ( newValue === undefined ) {
  4708. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4709. continue;
  4710. }
  4711. // for backward compatability if shading is set in the constructor
  4712. if ( key === 'shading' ) {
  4713. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4714. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4715. continue;
  4716. }
  4717. var currentValue = this[ key ];
  4718. if ( currentValue === undefined ) {
  4719. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4720. continue;
  4721. }
  4722. if ( currentValue && currentValue.isColor ) {
  4723. currentValue.set( newValue );
  4724. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4725. currentValue.copy( newValue );
  4726. } else if ( key === 'overdraw' ) {
  4727. // ensure overdraw is backwards-compatible with legacy boolean type
  4728. this[ key ] = Number( newValue );
  4729. } else {
  4730. this[ key ] = newValue;
  4731. }
  4732. }
  4733. },
  4734. toJSON: function ( meta ) {
  4735. var isRoot = meta === undefined;
  4736. if ( isRoot ) {
  4737. meta = {
  4738. textures: {},
  4739. images: {}
  4740. };
  4741. }
  4742. var data = {
  4743. metadata: {
  4744. version: 4.5,
  4745. type: 'Material',
  4746. generator: 'Material.toJSON'
  4747. }
  4748. };
  4749. // standard Material serialization
  4750. data.uuid = this.uuid;
  4751. data.type = this.type;
  4752. if ( this.name !== '' ) data.name = this.name;
  4753. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4754. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4755. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4756. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4757. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4758. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4759. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4760. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4761. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4762. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4763. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4764. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4765. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4766. data.bumpScale = this.bumpScale;
  4767. }
  4768. if ( this.normalMap && this.normalMap.isTexture ) {
  4769. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4770. data.normalScale = this.normalScale.toArray();
  4771. }
  4772. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4773. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4774. data.displacementScale = this.displacementScale;
  4775. data.displacementBias = this.displacementBias;
  4776. }
  4777. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4778. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4779. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4780. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4781. if ( this.envMap && this.envMap.isTexture ) {
  4782. data.envMap = this.envMap.toJSON( meta ).uuid;
  4783. data.reflectivity = this.reflectivity; // Scale behind envMap
  4784. }
  4785. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4786. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4787. }
  4788. if ( this.size !== undefined ) data.size = this.size;
  4789. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4790. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4791. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4792. if ( this.side !== FrontSide ) data.side = this.side;
  4793. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4794. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4795. if ( this.transparent === true ) data.transparent = this.transparent;
  4796. data.depthFunc = this.depthFunc;
  4797. data.depthTest = this.depthTest;
  4798. data.depthWrite = this.depthWrite;
  4799. if ( this.dithering === true ) data.dithering = true;
  4800. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4801. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4802. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4803. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4804. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4805. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4806. if ( this.morphTargets === true ) data.morphTargets = true;
  4807. if ( this.skinning === true ) data.skinning = true;
  4808. if ( this.visible === false ) data.visible = false;
  4809. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4810. // TODO: Copied from Object3D.toJSON
  4811. function extractFromCache( cache ) {
  4812. var values = [];
  4813. for ( var key in cache ) {
  4814. var data = cache[ key ];
  4815. delete data.metadata;
  4816. values.push( data );
  4817. }
  4818. return values;
  4819. }
  4820. if ( isRoot ) {
  4821. var textures = extractFromCache( meta.textures );
  4822. var images = extractFromCache( meta.images );
  4823. if ( textures.length > 0 ) data.textures = textures;
  4824. if ( images.length > 0 ) data.images = images;
  4825. }
  4826. return data;
  4827. },
  4828. clone: function () {
  4829. return new this.constructor().copy( this );
  4830. },
  4831. copy: function ( source ) {
  4832. this.name = source.name;
  4833. this.fog = source.fog;
  4834. this.lights = source.lights;
  4835. this.blending = source.blending;
  4836. this.side = source.side;
  4837. this.flatShading = source.flatShading;
  4838. this.vertexColors = source.vertexColors;
  4839. this.opacity = source.opacity;
  4840. this.transparent = source.transparent;
  4841. this.blendSrc = source.blendSrc;
  4842. this.blendDst = source.blendDst;
  4843. this.blendEquation = source.blendEquation;
  4844. this.blendSrcAlpha = source.blendSrcAlpha;
  4845. this.blendDstAlpha = source.blendDstAlpha;
  4846. this.blendEquationAlpha = source.blendEquationAlpha;
  4847. this.depthFunc = source.depthFunc;
  4848. this.depthTest = source.depthTest;
  4849. this.depthWrite = source.depthWrite;
  4850. this.colorWrite = source.colorWrite;
  4851. this.precision = source.precision;
  4852. this.polygonOffset = source.polygonOffset;
  4853. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4854. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4855. this.dithering = source.dithering;
  4856. this.alphaTest = source.alphaTest;
  4857. this.premultipliedAlpha = source.premultipliedAlpha;
  4858. this.overdraw = source.overdraw;
  4859. this.visible = source.visible;
  4860. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4861. this.clipShadows = source.clipShadows;
  4862. this.clipIntersection = source.clipIntersection;
  4863. var srcPlanes = source.clippingPlanes,
  4864. dstPlanes = null;
  4865. if ( srcPlanes !== null ) {
  4866. var n = srcPlanes.length;
  4867. dstPlanes = new Array( n );
  4868. for ( var i = 0; i !== n; ++ i )
  4869. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4870. }
  4871. this.clippingPlanes = dstPlanes;
  4872. return this;
  4873. },
  4874. dispose: function () {
  4875. this.dispatchEvent( { type: 'dispose' } );
  4876. }
  4877. } );
  4878. /**
  4879. * @author alteredq / http://alteredqualia.com/
  4880. *
  4881. * parameters = {
  4882. * defines: { "label" : "value" },
  4883. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4884. *
  4885. * fragmentShader: <string>,
  4886. * vertexShader: <string>,
  4887. *
  4888. * wireframe: <boolean>,
  4889. * wireframeLinewidth: <float>,
  4890. *
  4891. * lights: <bool>,
  4892. *
  4893. * skinning: <bool>,
  4894. * morphTargets: <bool>,
  4895. * morphNormals: <bool>
  4896. * }
  4897. */
  4898. function ShaderMaterial( parameters ) {
  4899. Material.call( this );
  4900. this.type = 'ShaderMaterial';
  4901. this.defines = {};
  4902. this.uniforms = {};
  4903. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4904. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4905. this.linewidth = 1;
  4906. this.wireframe = false;
  4907. this.wireframeLinewidth = 1;
  4908. this.fog = false; // set to use scene fog
  4909. this.lights = false; // set to use scene lights
  4910. this.clipping = false; // set to use user-defined clipping planes
  4911. this.skinning = false; // set to use skinning attribute streams
  4912. this.morphTargets = false; // set to use morph targets
  4913. this.morphNormals = false; // set to use morph normals
  4914. this.extensions = {
  4915. derivatives: false, // set to use derivatives
  4916. fragDepth: false, // set to use fragment depth values
  4917. drawBuffers: false, // set to use draw buffers
  4918. shaderTextureLOD: false // set to use shader texture LOD
  4919. };
  4920. // When rendered geometry doesn't include these attributes but the material does,
  4921. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4922. this.defaultAttributeValues = {
  4923. 'color': [ 1, 1, 1 ],
  4924. 'uv': [ 0, 0 ],
  4925. 'uv2': [ 0, 0 ]
  4926. };
  4927. this.index0AttributeName = undefined;
  4928. if ( parameters !== undefined ) {
  4929. if ( parameters.attributes !== undefined ) {
  4930. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4931. }
  4932. this.setValues( parameters );
  4933. }
  4934. }
  4935. ShaderMaterial.prototype = Object.create( Material.prototype );
  4936. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4937. ShaderMaterial.prototype.isShaderMaterial = true;
  4938. ShaderMaterial.prototype.copy = function ( source ) {
  4939. Material.prototype.copy.call( this, source );
  4940. this.fragmentShader = source.fragmentShader;
  4941. this.vertexShader = source.vertexShader;
  4942. this.uniforms = UniformsUtils.clone( source.uniforms );
  4943. this.defines = source.defines;
  4944. this.wireframe = source.wireframe;
  4945. this.wireframeLinewidth = source.wireframeLinewidth;
  4946. this.lights = source.lights;
  4947. this.clipping = source.clipping;
  4948. this.skinning = source.skinning;
  4949. this.morphTargets = source.morphTargets;
  4950. this.morphNormals = source.morphNormals;
  4951. this.extensions = source.extensions;
  4952. return this;
  4953. };
  4954. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4955. var data = Material.prototype.toJSON.call( this, meta );
  4956. data.uniforms = this.uniforms;
  4957. data.vertexShader = this.vertexShader;
  4958. data.fragmentShader = this.fragmentShader;
  4959. return data;
  4960. };
  4961. /**
  4962. * @author mrdoob / http://mrdoob.com/
  4963. * @author alteredq / http://alteredqualia.com/
  4964. * @author bhouston / https://clara.io
  4965. * @author WestLangley / http://github.com/WestLangley
  4966. *
  4967. * parameters = {
  4968. *
  4969. * opacity: <float>,
  4970. *
  4971. * map: new THREE.Texture( <Image> ),
  4972. *
  4973. * alphaMap: new THREE.Texture( <Image> ),
  4974. *
  4975. * displacementMap: new THREE.Texture( <Image> ),
  4976. * displacementScale: <float>,
  4977. * displacementBias: <float>,
  4978. *
  4979. * wireframe: <boolean>,
  4980. * wireframeLinewidth: <float>
  4981. * }
  4982. */
  4983. function MeshDepthMaterial( parameters ) {
  4984. Material.call( this );
  4985. this.type = 'MeshDepthMaterial';
  4986. this.depthPacking = BasicDepthPacking;
  4987. this.skinning = false;
  4988. this.morphTargets = false;
  4989. this.map = null;
  4990. this.alphaMap = null;
  4991. this.displacementMap = null;
  4992. this.displacementScale = 1;
  4993. this.displacementBias = 0;
  4994. this.wireframe = false;
  4995. this.wireframeLinewidth = 1;
  4996. this.fog = false;
  4997. this.lights = false;
  4998. this.setValues( parameters );
  4999. }
  5000. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  5001. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  5002. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  5003. MeshDepthMaterial.prototype.copy = function ( source ) {
  5004. Material.prototype.copy.call( this, source );
  5005. this.depthPacking = source.depthPacking;
  5006. this.skinning = source.skinning;
  5007. this.morphTargets = source.morphTargets;
  5008. this.map = source.map;
  5009. this.alphaMap = source.alphaMap;
  5010. this.displacementMap = source.displacementMap;
  5011. this.displacementScale = source.displacementScale;
  5012. this.displacementBias = source.displacementBias;
  5013. this.wireframe = source.wireframe;
  5014. this.wireframeLinewidth = source.wireframeLinewidth;
  5015. return this;
  5016. };
  5017. /**
  5018. * @author WestLangley / http://github.com/WestLangley
  5019. *
  5020. * parameters = {
  5021. *
  5022. * referencePosition: <float>,
  5023. * nearDistance: <float>,
  5024. * farDistance: <float>,
  5025. *
  5026. * skinning: <bool>,
  5027. * morphTargets: <bool>,
  5028. *
  5029. * map: new THREE.Texture( <Image> ),
  5030. *
  5031. * alphaMap: new THREE.Texture( <Image> ),
  5032. *
  5033. * displacementMap: new THREE.Texture( <Image> ),
  5034. * displacementScale: <float>,
  5035. * displacementBias: <float>
  5036. *
  5037. * }
  5038. */
  5039. function MeshDistanceMaterial( parameters ) {
  5040. Material.call( this );
  5041. this.type = 'MeshDistanceMaterial';
  5042. this.referencePosition = new Vector3();
  5043. this.nearDistance = 1;
  5044. this.farDistance = 1000;
  5045. this.skinning = false;
  5046. this.morphTargets = false;
  5047. this.map = null;
  5048. this.alphaMap = null;
  5049. this.displacementMap = null;
  5050. this.displacementScale = 1;
  5051. this.displacementBias = 0;
  5052. this.fog = false;
  5053. this.lights = false;
  5054. this.setValues( parameters );
  5055. }
  5056. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  5057. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  5058. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  5059. MeshDistanceMaterial.prototype.copy = function ( source ) {
  5060. Material.prototype.copy.call( this, source );
  5061. this.referencePosition.copy( source.referencePosition );
  5062. this.nearDistance = source.nearDistance;
  5063. this.farDistance = source.farDistance;
  5064. this.skinning = source.skinning;
  5065. this.morphTargets = source.morphTargets;
  5066. this.map = source.map;
  5067. this.alphaMap = source.alphaMap;
  5068. this.displacementMap = source.displacementMap;
  5069. this.displacementScale = source.displacementScale;
  5070. this.displacementBias = source.displacementBias;
  5071. return this;
  5072. };
  5073. /**
  5074. * @author bhouston / http://clara.io
  5075. * @author WestLangley / http://github.com/WestLangley
  5076. */
  5077. function Box3( min, max ) {
  5078. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  5079. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  5080. }
  5081. Object.assign( Box3.prototype, {
  5082. isBox3: true,
  5083. set: function ( min, max ) {
  5084. this.min.copy( min );
  5085. this.max.copy( max );
  5086. return this;
  5087. },
  5088. setFromArray: function ( array ) {
  5089. var minX = + Infinity;
  5090. var minY = + Infinity;
  5091. var minZ = + Infinity;
  5092. var maxX = - Infinity;
  5093. var maxY = - Infinity;
  5094. var maxZ = - Infinity;
  5095. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  5096. var x = array[ i ];
  5097. var y = array[ i + 1 ];
  5098. var z = array[ i + 2 ];
  5099. if ( x < minX ) minX = x;
  5100. if ( y < minY ) minY = y;
  5101. if ( z < minZ ) minZ = z;
  5102. if ( x > maxX ) maxX = x;
  5103. if ( y > maxY ) maxY = y;
  5104. if ( z > maxZ ) maxZ = z;
  5105. }
  5106. this.min.set( minX, minY, minZ );
  5107. this.max.set( maxX, maxY, maxZ );
  5108. return this;
  5109. },
  5110. setFromBufferAttribute: function ( attribute ) {
  5111. var minX = + Infinity;
  5112. var minY = + Infinity;
  5113. var minZ = + Infinity;
  5114. var maxX = - Infinity;
  5115. var maxY = - Infinity;
  5116. var maxZ = - Infinity;
  5117. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5118. var x = attribute.getX( i );
  5119. var y = attribute.getY( i );
  5120. var z = attribute.getZ( i );
  5121. if ( x < minX ) minX = x;
  5122. if ( y < minY ) minY = y;
  5123. if ( z < minZ ) minZ = z;
  5124. if ( x > maxX ) maxX = x;
  5125. if ( y > maxY ) maxY = y;
  5126. if ( z > maxZ ) maxZ = z;
  5127. }
  5128. this.min.set( minX, minY, minZ );
  5129. this.max.set( maxX, maxY, maxZ );
  5130. return this;
  5131. },
  5132. setFromPoints: function ( points ) {
  5133. this.makeEmpty();
  5134. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5135. this.expandByPoint( points[ i ] );
  5136. }
  5137. return this;
  5138. },
  5139. setFromCenterAndSize: function () {
  5140. var v1 = new Vector3();
  5141. return function setFromCenterAndSize( center, size ) {
  5142. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  5143. this.min.copy( center ).sub( halfSize );
  5144. this.max.copy( center ).add( halfSize );
  5145. return this;
  5146. };
  5147. }(),
  5148. setFromObject: function ( object ) {
  5149. this.makeEmpty();
  5150. return this.expandByObject( object );
  5151. },
  5152. clone: function () {
  5153. return new this.constructor().copy( this );
  5154. },
  5155. copy: function ( box ) {
  5156. this.min.copy( box.min );
  5157. this.max.copy( box.max );
  5158. return this;
  5159. },
  5160. makeEmpty: function () {
  5161. this.min.x = this.min.y = this.min.z = + Infinity;
  5162. this.max.x = this.max.y = this.max.z = - Infinity;
  5163. return this;
  5164. },
  5165. isEmpty: function () {
  5166. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5167. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5168. },
  5169. getCenter: function ( optionalTarget ) {
  5170. var result = optionalTarget || new Vector3();
  5171. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5172. },
  5173. getSize: function ( optionalTarget ) {
  5174. var result = optionalTarget || new Vector3();
  5175. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  5176. },
  5177. expandByPoint: function ( point ) {
  5178. this.min.min( point );
  5179. this.max.max( point );
  5180. return this;
  5181. },
  5182. expandByVector: function ( vector ) {
  5183. this.min.sub( vector );
  5184. this.max.add( vector );
  5185. return this;
  5186. },
  5187. expandByScalar: function ( scalar ) {
  5188. this.min.addScalar( - scalar );
  5189. this.max.addScalar( scalar );
  5190. return this;
  5191. },
  5192. expandByObject: function () {
  5193. // Computes the world-axis-aligned bounding box of an object (including its children),
  5194. // accounting for both the object's, and children's, world transforms
  5195. var v1 = new Vector3();
  5196. return function expandByObject( object ) {
  5197. var scope = this;
  5198. object.updateMatrixWorld( true );
  5199. object.traverse( function ( node ) {
  5200. var i, l;
  5201. var geometry = node.geometry;
  5202. if ( geometry !== undefined ) {
  5203. if ( geometry.isGeometry ) {
  5204. var vertices = geometry.vertices;
  5205. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  5206. v1.copy( vertices[ i ] );
  5207. v1.applyMatrix4( node.matrixWorld );
  5208. scope.expandByPoint( v1 );
  5209. }
  5210. } else if ( geometry.isBufferGeometry ) {
  5211. var attribute = geometry.attributes.position;
  5212. if ( attribute !== undefined ) {
  5213. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  5214. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  5215. scope.expandByPoint( v1 );
  5216. }
  5217. }
  5218. }
  5219. }
  5220. } );
  5221. return this;
  5222. };
  5223. }(),
  5224. containsPoint: function ( point ) {
  5225. return point.x < this.min.x || point.x > this.max.x ||
  5226. point.y < this.min.y || point.y > this.max.y ||
  5227. point.z < this.min.z || point.z > this.max.z ? false : true;
  5228. },
  5229. containsBox: function ( box ) {
  5230. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  5231. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  5232. this.min.z <= box.min.z && box.max.z <= this.max.z;
  5233. },
  5234. getParameter: function ( point, optionalTarget ) {
  5235. // This can potentially have a divide by zero if the box
  5236. // has a size dimension of 0.
  5237. var result = optionalTarget || new Vector3();
  5238. return result.set(
  5239. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5240. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5241. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5242. );
  5243. },
  5244. intersectsBox: function ( box ) {
  5245. // using 6 splitting planes to rule out intersections.
  5246. return box.max.x < this.min.x || box.min.x > this.max.x ||
  5247. box.max.y < this.min.y || box.min.y > this.max.y ||
  5248. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  5249. },
  5250. intersectsSphere: ( function () {
  5251. var closestPoint = new Vector3();
  5252. return function intersectsSphere( sphere ) {
  5253. // Find the point on the AABB closest to the sphere center.
  5254. this.clampPoint( sphere.center, closestPoint );
  5255. // If that point is inside the sphere, the AABB and sphere intersect.
  5256. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5257. };
  5258. } )(),
  5259. intersectsPlane: function ( plane ) {
  5260. // We compute the minimum and maximum dot product values. If those values
  5261. // are on the same side (back or front) of the plane, then there is no intersection.
  5262. var min, max;
  5263. if ( plane.normal.x > 0 ) {
  5264. min = plane.normal.x * this.min.x;
  5265. max = plane.normal.x * this.max.x;
  5266. } else {
  5267. min = plane.normal.x * this.max.x;
  5268. max = plane.normal.x * this.min.x;
  5269. }
  5270. if ( plane.normal.y > 0 ) {
  5271. min += plane.normal.y * this.min.y;
  5272. max += plane.normal.y * this.max.y;
  5273. } else {
  5274. min += plane.normal.y * this.max.y;
  5275. max += plane.normal.y * this.min.y;
  5276. }
  5277. if ( plane.normal.z > 0 ) {
  5278. min += plane.normal.z * this.min.z;
  5279. max += plane.normal.z * this.max.z;
  5280. } else {
  5281. min += plane.normal.z * this.max.z;
  5282. max += plane.normal.z * this.min.z;
  5283. }
  5284. return ( min <= plane.constant && max >= plane.constant );
  5285. },
  5286. clampPoint: function ( point, optionalTarget ) {
  5287. var result = optionalTarget || new Vector3();
  5288. return result.copy( point ).clamp( this.min, this.max );
  5289. },
  5290. distanceToPoint: function () {
  5291. var v1 = new Vector3();
  5292. return function distanceToPoint( point ) {
  5293. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5294. return clampedPoint.sub( point ).length();
  5295. };
  5296. }(),
  5297. getBoundingSphere: function () {
  5298. var v1 = new Vector3();
  5299. return function getBoundingSphere( optionalTarget ) {
  5300. var result = optionalTarget || new Sphere();
  5301. this.getCenter( result.center );
  5302. result.radius = this.getSize( v1 ).length() * 0.5;
  5303. return result;
  5304. };
  5305. }(),
  5306. intersect: function ( box ) {
  5307. this.min.max( box.min );
  5308. this.max.min( box.max );
  5309. // 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.
  5310. if( this.isEmpty() ) this.makeEmpty();
  5311. return this;
  5312. },
  5313. union: function ( box ) {
  5314. this.min.min( box.min );
  5315. this.max.max( box.max );
  5316. return this;
  5317. },
  5318. applyMatrix4: function () {
  5319. var points = [
  5320. new Vector3(),
  5321. new Vector3(),
  5322. new Vector3(),
  5323. new Vector3(),
  5324. new Vector3(),
  5325. new Vector3(),
  5326. new Vector3(),
  5327. new Vector3()
  5328. ];
  5329. return function applyMatrix4( matrix ) {
  5330. // transform of empty box is an empty box.
  5331. if( this.isEmpty() ) return this;
  5332. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5333. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5334. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5335. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5336. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5337. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5338. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5339. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5340. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5341. this.setFromPoints( points );
  5342. return this;
  5343. };
  5344. }(),
  5345. translate: function ( offset ) {
  5346. this.min.add( offset );
  5347. this.max.add( offset );
  5348. return this;
  5349. },
  5350. equals: function ( box ) {
  5351. return box.min.equals( this.min ) && box.max.equals( this.max );
  5352. }
  5353. } );
  5354. /**
  5355. * @author bhouston / http://clara.io
  5356. * @author mrdoob / http://mrdoob.com/
  5357. */
  5358. function Sphere( center, radius ) {
  5359. this.center = ( center !== undefined ) ? center : new Vector3();
  5360. this.radius = ( radius !== undefined ) ? radius : 0;
  5361. }
  5362. Object.assign( Sphere.prototype, {
  5363. set: function ( center, radius ) {
  5364. this.center.copy( center );
  5365. this.radius = radius;
  5366. return this;
  5367. },
  5368. setFromPoints: function () {
  5369. var box = new Box3();
  5370. return function setFromPoints( points, optionalCenter ) {
  5371. var center = this.center;
  5372. if ( optionalCenter !== undefined ) {
  5373. center.copy( optionalCenter );
  5374. } else {
  5375. box.setFromPoints( points ).getCenter( center );
  5376. }
  5377. var maxRadiusSq = 0;
  5378. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5379. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5380. }
  5381. this.radius = Math.sqrt( maxRadiusSq );
  5382. return this;
  5383. };
  5384. }(),
  5385. clone: function () {
  5386. return new this.constructor().copy( this );
  5387. },
  5388. copy: function ( sphere ) {
  5389. this.center.copy( sphere.center );
  5390. this.radius = sphere.radius;
  5391. return this;
  5392. },
  5393. empty: function () {
  5394. return ( this.radius <= 0 );
  5395. },
  5396. containsPoint: function ( point ) {
  5397. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5398. },
  5399. distanceToPoint: function ( point ) {
  5400. return ( point.distanceTo( this.center ) - this.radius );
  5401. },
  5402. intersectsSphere: function ( sphere ) {
  5403. var radiusSum = this.radius + sphere.radius;
  5404. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5405. },
  5406. intersectsBox: function ( box ) {
  5407. return box.intersectsSphere( this );
  5408. },
  5409. intersectsPlane: function ( plane ) {
  5410. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5411. },
  5412. clampPoint: function ( point, optionalTarget ) {
  5413. var deltaLengthSq = this.center.distanceToSquared( point );
  5414. var result = optionalTarget || new Vector3();
  5415. result.copy( point );
  5416. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5417. result.sub( this.center ).normalize();
  5418. result.multiplyScalar( this.radius ).add( this.center );
  5419. }
  5420. return result;
  5421. },
  5422. getBoundingBox: function ( optionalTarget ) {
  5423. var box = optionalTarget || new Box3();
  5424. box.set( this.center, this.center );
  5425. box.expandByScalar( this.radius );
  5426. return box;
  5427. },
  5428. applyMatrix4: function ( matrix ) {
  5429. this.center.applyMatrix4( matrix );
  5430. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5431. return this;
  5432. },
  5433. translate: function ( offset ) {
  5434. this.center.add( offset );
  5435. return this;
  5436. },
  5437. equals: function ( sphere ) {
  5438. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5439. }
  5440. } );
  5441. /**
  5442. * @author bhouston / http://clara.io
  5443. */
  5444. function Plane( normal, constant ) {
  5445. // normal is assumed to be normalized
  5446. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5447. this.constant = ( constant !== undefined ) ? constant : 0;
  5448. }
  5449. Object.assign( Plane.prototype, {
  5450. set: function ( normal, constant ) {
  5451. this.normal.copy( normal );
  5452. this.constant = constant;
  5453. return this;
  5454. },
  5455. setComponents: function ( x, y, z, w ) {
  5456. this.normal.set( x, y, z );
  5457. this.constant = w;
  5458. return this;
  5459. },
  5460. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5461. this.normal.copy( normal );
  5462. this.constant = - point.dot( this.normal );
  5463. return this;
  5464. },
  5465. setFromCoplanarPoints: function () {
  5466. var v1 = new Vector3();
  5467. var v2 = new Vector3();
  5468. return function setFromCoplanarPoints( a, b, c ) {
  5469. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5470. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5471. this.setFromNormalAndCoplanarPoint( normal, a );
  5472. return this;
  5473. };
  5474. }(),
  5475. clone: function () {
  5476. return new this.constructor().copy( this );
  5477. },
  5478. copy: function ( plane ) {
  5479. this.normal.copy( plane.normal );
  5480. this.constant = plane.constant;
  5481. return this;
  5482. },
  5483. normalize: function () {
  5484. // Note: will lead to a divide by zero if the plane is invalid.
  5485. var inverseNormalLength = 1.0 / this.normal.length();
  5486. this.normal.multiplyScalar( inverseNormalLength );
  5487. this.constant *= inverseNormalLength;
  5488. return this;
  5489. },
  5490. negate: function () {
  5491. this.constant *= - 1;
  5492. this.normal.negate();
  5493. return this;
  5494. },
  5495. distanceToPoint: function ( point ) {
  5496. return this.normal.dot( point ) + this.constant;
  5497. },
  5498. distanceToSphere: function ( sphere ) {
  5499. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5500. },
  5501. projectPoint: function ( point, optionalTarget ) {
  5502. var result = optionalTarget || new Vector3();
  5503. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5504. },
  5505. intersectLine: function () {
  5506. var v1 = new Vector3();
  5507. return function intersectLine( line, optionalTarget ) {
  5508. var result = optionalTarget || new Vector3();
  5509. var direction = line.delta( v1 );
  5510. var denominator = this.normal.dot( direction );
  5511. if ( denominator === 0 ) {
  5512. // line is coplanar, return origin
  5513. if ( this.distanceToPoint( line.start ) === 0 ) {
  5514. return result.copy( line.start );
  5515. }
  5516. // Unsure if this is the correct method to handle this case.
  5517. return undefined;
  5518. }
  5519. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5520. if ( t < 0 || t > 1 ) {
  5521. return undefined;
  5522. }
  5523. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5524. };
  5525. }(),
  5526. intersectsLine: function ( line ) {
  5527. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5528. var startSign = this.distanceToPoint( line.start );
  5529. var endSign = this.distanceToPoint( line.end );
  5530. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5531. },
  5532. intersectsBox: function ( box ) {
  5533. return box.intersectsPlane( this );
  5534. },
  5535. intersectsSphere: function ( sphere ) {
  5536. return sphere.intersectsPlane( this );
  5537. },
  5538. coplanarPoint: function ( optionalTarget ) {
  5539. var result = optionalTarget || new Vector3();
  5540. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5541. },
  5542. applyMatrix4: function () {
  5543. var v1 = new Vector3();
  5544. var m1 = new Matrix3();
  5545. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5546. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5547. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5548. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5549. this.constant = - referencePoint.dot( normal );
  5550. return this;
  5551. };
  5552. }(),
  5553. translate: function ( offset ) {
  5554. this.constant -= offset.dot( this.normal );
  5555. return this;
  5556. },
  5557. equals: function ( plane ) {
  5558. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5559. }
  5560. } );
  5561. /**
  5562. * @author mrdoob / http://mrdoob.com/
  5563. * @author alteredq / http://alteredqualia.com/
  5564. * @author bhouston / http://clara.io
  5565. */
  5566. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5567. this.planes = [
  5568. ( p0 !== undefined ) ? p0 : new Plane(),
  5569. ( p1 !== undefined ) ? p1 : new Plane(),
  5570. ( p2 !== undefined ) ? p2 : new Plane(),
  5571. ( p3 !== undefined ) ? p3 : new Plane(),
  5572. ( p4 !== undefined ) ? p4 : new Plane(),
  5573. ( p5 !== undefined ) ? p5 : new Plane()
  5574. ];
  5575. }
  5576. Object.assign( Frustum.prototype, {
  5577. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5578. var planes = this.planes;
  5579. planes[ 0 ].copy( p0 );
  5580. planes[ 1 ].copy( p1 );
  5581. planes[ 2 ].copy( p2 );
  5582. planes[ 3 ].copy( p3 );
  5583. planes[ 4 ].copy( p4 );
  5584. planes[ 5 ].copy( p5 );
  5585. return this;
  5586. },
  5587. clone: function () {
  5588. return new this.constructor().copy( this );
  5589. },
  5590. copy: function ( frustum ) {
  5591. var planes = this.planes;
  5592. for ( var i = 0; i < 6; i ++ ) {
  5593. planes[ i ].copy( frustum.planes[ i ] );
  5594. }
  5595. return this;
  5596. },
  5597. setFromMatrix: function ( m ) {
  5598. var planes = this.planes;
  5599. var me = m.elements;
  5600. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5601. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5602. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5603. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5604. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5605. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5606. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5607. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5608. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5609. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5610. return this;
  5611. },
  5612. intersectsObject: function () {
  5613. var sphere = new Sphere();
  5614. return function intersectsObject( object ) {
  5615. var geometry = object.geometry;
  5616. if ( geometry.boundingSphere === null )
  5617. geometry.computeBoundingSphere();
  5618. sphere.copy( geometry.boundingSphere )
  5619. .applyMatrix4( object.matrixWorld );
  5620. return this.intersectsSphere( sphere );
  5621. };
  5622. }(),
  5623. intersectsSprite: function () {
  5624. var sphere = new Sphere();
  5625. return function intersectsSprite( sprite ) {
  5626. sphere.center.set( 0, 0, 0 );
  5627. sphere.radius = 0.7071067811865476;
  5628. sphere.applyMatrix4( sprite.matrixWorld );
  5629. return this.intersectsSphere( sphere );
  5630. };
  5631. }(),
  5632. intersectsSphere: function ( sphere ) {
  5633. var planes = this.planes;
  5634. var center = sphere.center;
  5635. var negRadius = - sphere.radius;
  5636. for ( var i = 0; i < 6; i ++ ) {
  5637. var distance = planes[ i ].distanceToPoint( center );
  5638. if ( distance < negRadius ) {
  5639. return false;
  5640. }
  5641. }
  5642. return true;
  5643. },
  5644. intersectsBox: function () {
  5645. var p1 = new Vector3(),
  5646. p2 = new Vector3();
  5647. return function intersectsBox( box ) {
  5648. var planes = this.planes;
  5649. for ( var i = 0; i < 6; i ++ ) {
  5650. var plane = planes[ i ];
  5651. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5652. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5653. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5654. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5655. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5656. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5657. var d1 = plane.distanceToPoint( p1 );
  5658. var d2 = plane.distanceToPoint( p2 );
  5659. // if both outside plane, no intersection
  5660. if ( d1 < 0 && d2 < 0 ) {
  5661. return false;
  5662. }
  5663. }
  5664. return true;
  5665. };
  5666. }(),
  5667. containsPoint: function ( point ) {
  5668. var planes = this.planes;
  5669. for ( var i = 0; i < 6; i ++ ) {
  5670. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5671. return false;
  5672. }
  5673. }
  5674. return true;
  5675. }
  5676. } );
  5677. /**
  5678. * @author alteredq / http://alteredqualia.com/
  5679. * @author mrdoob / http://mrdoob.com/
  5680. */
  5681. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  5682. var _frustum = new Frustum(),
  5683. _projScreenMatrix = new Matrix4(),
  5684. _shadowMapSize = new Vector2(),
  5685. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  5686. _lookTarget = new Vector3(),
  5687. _lightPositionWorld = new Vector3(),
  5688. _MorphingFlag = 1,
  5689. _SkinningFlag = 2,
  5690. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5691. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5692. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5693. _materialCache = {};
  5694. var cubeDirections = [
  5695. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5696. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5697. ];
  5698. var cubeUps = [
  5699. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5700. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5701. ];
  5702. var cube2DViewPorts = [
  5703. new Vector4(), new Vector4(), new Vector4(),
  5704. new Vector4(), new Vector4(), new Vector4()
  5705. ];
  5706. // init
  5707. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5708. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5709. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5710. var depthMaterial = new MeshDepthMaterial( {
  5711. depthPacking: RGBADepthPacking,
  5712. morphTargets: useMorphing,
  5713. skinning: useSkinning
  5714. } );
  5715. _depthMaterials[ i ] = depthMaterial;
  5716. //
  5717. var distanceMaterial = new MeshDistanceMaterial( {
  5718. morphTargets: useMorphing,
  5719. skinning: useSkinning
  5720. } );
  5721. _distanceMaterials[ i ] = distanceMaterial;
  5722. }
  5723. //
  5724. var scope = this;
  5725. this.enabled = false;
  5726. this.autoUpdate = true;
  5727. this.needsUpdate = false;
  5728. this.type = PCFShadowMap;
  5729. this.renderReverseSided = true;
  5730. this.renderSingleSided = true;
  5731. this.render = function ( lights, scene, camera ) {
  5732. if ( scope.enabled === false ) return;
  5733. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5734. if ( lights.length === 0 ) return;
  5735. // TODO Clean up (needed in case of contextlost)
  5736. var _gl = _renderer.context;
  5737. var _state = _renderer.state;
  5738. // Set GL state for depth map.
  5739. _state.disable( _gl.BLEND );
  5740. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5741. _state.buffers.depth.setTest( true );
  5742. _state.setScissorTest( false );
  5743. // render depth map
  5744. var faceCount;
  5745. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  5746. var light = lights[ i ];
  5747. var shadow = light.shadow;
  5748. var isPointLight = light && light.isPointLight;
  5749. if ( shadow === undefined ) {
  5750. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5751. continue;
  5752. }
  5753. var shadowCamera = shadow.camera;
  5754. _shadowMapSize.copy( shadow.mapSize );
  5755. _shadowMapSize.min( _maxShadowMapSize );
  5756. if ( isPointLight ) {
  5757. var vpWidth = _shadowMapSize.x;
  5758. var vpHeight = _shadowMapSize.y;
  5759. // These viewports map a cube-map onto a 2D texture with the
  5760. // following orientation:
  5761. //
  5762. // xzXZ
  5763. // y Y
  5764. //
  5765. // X - Positive x direction
  5766. // x - Negative x direction
  5767. // Y - Positive y direction
  5768. // y - Negative y direction
  5769. // Z - Positive z direction
  5770. // z - Negative z direction
  5771. // positive X
  5772. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5773. // negative X
  5774. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5775. // positive Z
  5776. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5777. // negative Z
  5778. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5779. // positive Y
  5780. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5781. // negative Y
  5782. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5783. _shadowMapSize.x *= 4.0;
  5784. _shadowMapSize.y *= 2.0;
  5785. }
  5786. if ( shadow.map === null ) {
  5787. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5788. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5789. shadow.map.texture.name = light.name + ".shadowMap";
  5790. shadowCamera.updateProjectionMatrix();
  5791. }
  5792. if ( shadow.isSpotLightShadow ) {
  5793. shadow.update( light );
  5794. }
  5795. var shadowMap = shadow.map;
  5796. var shadowMatrix = shadow.matrix;
  5797. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5798. shadowCamera.position.copy( _lightPositionWorld );
  5799. if ( isPointLight ) {
  5800. faceCount = 6;
  5801. // for point lights we set the shadow matrix to be a translation-only matrix
  5802. // equal to inverse of the light's position
  5803. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5804. } else {
  5805. faceCount = 1;
  5806. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5807. shadowCamera.lookAt( _lookTarget );
  5808. shadowCamera.updateMatrixWorld();
  5809. // compute shadow matrix
  5810. shadowMatrix.set(
  5811. 0.5, 0.0, 0.0, 0.5,
  5812. 0.0, 0.5, 0.0, 0.5,
  5813. 0.0, 0.0, 0.5, 0.5,
  5814. 0.0, 0.0, 0.0, 1.0
  5815. );
  5816. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5817. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5818. }
  5819. _renderer.setRenderTarget( shadowMap );
  5820. _renderer.clear();
  5821. // render shadow map for each cube face (if omni-directional) or
  5822. // run a single pass if not
  5823. for ( var face = 0; face < faceCount; face ++ ) {
  5824. if ( isPointLight ) {
  5825. _lookTarget.copy( shadowCamera.position );
  5826. _lookTarget.add( cubeDirections[ face ] );
  5827. shadowCamera.up.copy( cubeUps[ face ] );
  5828. shadowCamera.lookAt( _lookTarget );
  5829. shadowCamera.updateMatrixWorld();
  5830. var vpDimensions = cube2DViewPorts[ face ];
  5831. _state.viewport( vpDimensions );
  5832. }
  5833. // update camera matrices and frustum
  5834. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5835. _frustum.setFromMatrix( _projScreenMatrix );
  5836. // set object matrices & frustum culling
  5837. renderObject( scene, camera, shadowCamera, isPointLight );
  5838. }
  5839. }
  5840. scope.needsUpdate = false;
  5841. };
  5842. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  5843. var geometry = object.geometry;
  5844. var result = null;
  5845. var materialVariants = _depthMaterials;
  5846. var customMaterial = object.customDepthMaterial;
  5847. if ( isPointLight ) {
  5848. materialVariants = _distanceMaterials;
  5849. customMaterial = object.customDistanceMaterial;
  5850. }
  5851. if ( ! customMaterial ) {
  5852. var useMorphing = false;
  5853. if ( material.morphTargets ) {
  5854. if ( geometry && geometry.isBufferGeometry ) {
  5855. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5856. } else if ( geometry && geometry.isGeometry ) {
  5857. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5858. }
  5859. }
  5860. if ( object.isSkinnedMesh && material.skinning === false ) {
  5861. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5862. }
  5863. var useSkinning = object.isSkinnedMesh && material.skinning;
  5864. var variantIndex = 0;
  5865. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5866. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5867. result = materialVariants[ variantIndex ];
  5868. } else {
  5869. result = customMaterial;
  5870. }
  5871. if ( _renderer.localClippingEnabled &&
  5872. material.clipShadows === true &&
  5873. material.clippingPlanes.length !== 0 ) {
  5874. // in this case we need a unique material instance reflecting the
  5875. // appropriate state
  5876. var keyA = result.uuid, keyB = material.uuid;
  5877. var materialsForVariant = _materialCache[ keyA ];
  5878. if ( materialsForVariant === undefined ) {
  5879. materialsForVariant = {};
  5880. _materialCache[ keyA ] = materialsForVariant;
  5881. }
  5882. var cachedMaterial = materialsForVariant[ keyB ];
  5883. if ( cachedMaterial === undefined ) {
  5884. cachedMaterial = result.clone();
  5885. materialsForVariant[ keyB ] = cachedMaterial;
  5886. }
  5887. result = cachedMaterial;
  5888. }
  5889. result.visible = material.visible;
  5890. result.wireframe = material.wireframe;
  5891. var side = material.side;
  5892. if ( scope.renderSingleSided && side == DoubleSide ) {
  5893. side = FrontSide;
  5894. }
  5895. if ( scope.renderReverseSided ) {
  5896. if ( side === FrontSide ) side = BackSide;
  5897. else if ( side === BackSide ) side = FrontSide;
  5898. }
  5899. result.side = side;
  5900. result.clipShadows = material.clipShadows;
  5901. result.clippingPlanes = material.clippingPlanes;
  5902. result.clipIntersection = material.clipIntersection;
  5903. result.wireframeLinewidth = material.wireframeLinewidth;
  5904. result.linewidth = material.linewidth;
  5905. if ( isPointLight && result.isMeshDistanceMaterial ) {
  5906. result.referencePosition.copy( lightPositionWorld );
  5907. result.nearDistance = shadowCameraNear;
  5908. result.farDistance = shadowCameraFar;
  5909. }
  5910. return result;
  5911. }
  5912. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5913. if ( object.visible === false ) return;
  5914. var visible = object.layers.test( camera.layers );
  5915. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5916. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5917. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5918. var geometry = _objects.update( object );
  5919. var material = object.material;
  5920. if ( Array.isArray( material ) ) {
  5921. var groups = geometry.groups;
  5922. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5923. var group = groups[ k ];
  5924. var groupMaterial = material[ group.materialIndex ];
  5925. if ( groupMaterial && groupMaterial.visible ) {
  5926. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5927. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5928. }
  5929. }
  5930. } else if ( material.visible ) {
  5931. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5932. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5933. }
  5934. }
  5935. }
  5936. var children = object.children;
  5937. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5938. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5939. }
  5940. }
  5941. }
  5942. /**
  5943. * @author mrdoob / http://mrdoob.com/
  5944. */
  5945. function WebGLAttributes( gl ) {
  5946. var buffers = {};
  5947. function createBuffer( attribute, bufferType ) {
  5948. var array = attribute.array;
  5949. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  5950. var buffer = gl.createBuffer();
  5951. gl.bindBuffer( bufferType, buffer );
  5952. gl.bufferData( bufferType, array, usage );
  5953. attribute.onUploadCallback();
  5954. var type = gl.FLOAT;
  5955. if ( array instanceof Float32Array ) {
  5956. type = gl.FLOAT;
  5957. } else if ( array instanceof Float64Array ) {
  5958. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  5959. } else if ( array instanceof Uint16Array ) {
  5960. type = gl.UNSIGNED_SHORT;
  5961. } else if ( array instanceof Int16Array ) {
  5962. type = gl.SHORT;
  5963. } else if ( array instanceof Uint32Array ) {
  5964. type = gl.UNSIGNED_INT;
  5965. } else if ( array instanceof Int32Array ) {
  5966. type = gl.INT;
  5967. } else if ( array instanceof Int8Array ) {
  5968. type = gl.BYTE;
  5969. } else if ( array instanceof Uint8Array ) {
  5970. type = gl.UNSIGNED_BYTE;
  5971. }
  5972. return {
  5973. buffer: buffer,
  5974. type: type,
  5975. bytesPerElement: array.BYTES_PER_ELEMENT,
  5976. version: attribute.version
  5977. };
  5978. }
  5979. function updateBuffer( buffer, attribute, bufferType ) {
  5980. var array = attribute.array;
  5981. var updateRange = attribute.updateRange;
  5982. gl.bindBuffer( bufferType, buffer );
  5983. if ( attribute.dynamic === false ) {
  5984. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  5985. } else if ( updateRange.count === - 1 ) {
  5986. // Not using update ranges
  5987. gl.bufferSubData( bufferType, 0, array );
  5988. } else if ( updateRange.count === 0 ) {
  5989. 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.' );
  5990. } else {
  5991. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  5992. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  5993. updateRange.count = -1; // reset range
  5994. }
  5995. }
  5996. //
  5997. function get( attribute ) {
  5998. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5999. return buffers[ attribute.uuid ];
  6000. }
  6001. function remove( attribute ) {
  6002. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  6003. var data = buffers[ attribute.uuid ];
  6004. if ( data ) {
  6005. gl.deleteBuffer( data.buffer );
  6006. delete buffers[ attribute.uuid ];
  6007. }
  6008. }
  6009. function update( attribute, bufferType ) {
  6010. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  6011. var data = buffers[ attribute.uuid ];
  6012. if ( data === undefined ) {
  6013. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  6014. } else if ( data.version < attribute.version ) {
  6015. updateBuffer( data.buffer, attribute, bufferType );
  6016. data.version = attribute.version;
  6017. }
  6018. }
  6019. return {
  6020. get: get,
  6021. remove: remove,
  6022. update: update
  6023. };
  6024. }
  6025. /**
  6026. * @author mrdoob / http://mrdoob.com/
  6027. * @author WestLangley / http://github.com/WestLangley
  6028. * @author bhouston / http://clara.io
  6029. */
  6030. function Euler( x, y, z, order ) {
  6031. this._x = x || 0;
  6032. this._y = y || 0;
  6033. this._z = z || 0;
  6034. this._order = order || Euler.DefaultOrder;
  6035. }
  6036. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6037. Euler.DefaultOrder = 'XYZ';
  6038. Object.defineProperties( Euler.prototype, {
  6039. x: {
  6040. get: function () {
  6041. return this._x;
  6042. },
  6043. set: function ( value ) {
  6044. this._x = value;
  6045. this.onChangeCallback();
  6046. }
  6047. },
  6048. y: {
  6049. get: function () {
  6050. return this._y;
  6051. },
  6052. set: function ( value ) {
  6053. this._y = value;
  6054. this.onChangeCallback();
  6055. }
  6056. },
  6057. z: {
  6058. get: function () {
  6059. return this._z;
  6060. },
  6061. set: function ( value ) {
  6062. this._z = value;
  6063. this.onChangeCallback();
  6064. }
  6065. },
  6066. order: {
  6067. get: function () {
  6068. return this._order;
  6069. },
  6070. set: function ( value ) {
  6071. this._order = value;
  6072. this.onChangeCallback();
  6073. }
  6074. }
  6075. } );
  6076. Object.assign( Euler.prototype, {
  6077. isEuler: true,
  6078. set: function ( x, y, z, order ) {
  6079. this._x = x;
  6080. this._y = y;
  6081. this._z = z;
  6082. this._order = order || this._order;
  6083. this.onChangeCallback();
  6084. return this;
  6085. },
  6086. clone: function () {
  6087. return new this.constructor( this._x, this._y, this._z, this._order );
  6088. },
  6089. copy: function ( euler ) {
  6090. this._x = euler._x;
  6091. this._y = euler._y;
  6092. this._z = euler._z;
  6093. this._order = euler._order;
  6094. this.onChangeCallback();
  6095. return this;
  6096. },
  6097. setFromRotationMatrix: function ( m, order, update ) {
  6098. var clamp = _Math.clamp;
  6099. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6100. var te = m.elements;
  6101. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6102. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6103. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6104. order = order || this._order;
  6105. if ( order === 'XYZ' ) {
  6106. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6107. if ( Math.abs( m13 ) < 0.99999 ) {
  6108. this._x = Math.atan2( - m23, m33 );
  6109. this._z = Math.atan2( - m12, m11 );
  6110. } else {
  6111. this._x = Math.atan2( m32, m22 );
  6112. this._z = 0;
  6113. }
  6114. } else if ( order === 'YXZ' ) {
  6115. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6116. if ( Math.abs( m23 ) < 0.99999 ) {
  6117. this._y = Math.atan2( m13, m33 );
  6118. this._z = Math.atan2( m21, m22 );
  6119. } else {
  6120. this._y = Math.atan2( - m31, m11 );
  6121. this._z = 0;
  6122. }
  6123. } else if ( order === 'ZXY' ) {
  6124. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6125. if ( Math.abs( m32 ) < 0.99999 ) {
  6126. this._y = Math.atan2( - m31, m33 );
  6127. this._z = Math.atan2( - m12, m22 );
  6128. } else {
  6129. this._y = 0;
  6130. this._z = Math.atan2( m21, m11 );
  6131. }
  6132. } else if ( order === 'ZYX' ) {
  6133. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6134. if ( Math.abs( m31 ) < 0.99999 ) {
  6135. this._x = Math.atan2( m32, m33 );
  6136. this._z = Math.atan2( m21, m11 );
  6137. } else {
  6138. this._x = 0;
  6139. this._z = Math.atan2( - m12, m22 );
  6140. }
  6141. } else if ( order === 'YZX' ) {
  6142. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6143. if ( Math.abs( m21 ) < 0.99999 ) {
  6144. this._x = Math.atan2( - m23, m22 );
  6145. this._y = Math.atan2( - m31, m11 );
  6146. } else {
  6147. this._x = 0;
  6148. this._y = Math.atan2( m13, m33 );
  6149. }
  6150. } else if ( order === 'XZY' ) {
  6151. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6152. if ( Math.abs( m12 ) < 0.99999 ) {
  6153. this._x = Math.atan2( m32, m22 );
  6154. this._y = Math.atan2( m13, m11 );
  6155. } else {
  6156. this._x = Math.atan2( - m23, m33 );
  6157. this._y = 0;
  6158. }
  6159. } else {
  6160. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6161. }
  6162. this._order = order;
  6163. if ( update !== false ) this.onChangeCallback();
  6164. return this;
  6165. },
  6166. setFromQuaternion: function () {
  6167. var matrix = new Matrix4();
  6168. return function setFromQuaternion( q, order, update ) {
  6169. matrix.makeRotationFromQuaternion( q );
  6170. return this.setFromRotationMatrix( matrix, order, update );
  6171. };
  6172. }(),
  6173. setFromVector3: function ( v, order ) {
  6174. return this.set( v.x, v.y, v.z, order || this._order );
  6175. },
  6176. reorder: function () {
  6177. // WARNING: this discards revolution information -bhouston
  6178. var q = new Quaternion();
  6179. return function reorder( newOrder ) {
  6180. q.setFromEuler( this );
  6181. return this.setFromQuaternion( q, newOrder );
  6182. };
  6183. }(),
  6184. equals: function ( euler ) {
  6185. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6186. },
  6187. fromArray: function ( array ) {
  6188. this._x = array[ 0 ];
  6189. this._y = array[ 1 ];
  6190. this._z = array[ 2 ];
  6191. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6192. this.onChangeCallback();
  6193. return this;
  6194. },
  6195. toArray: function ( array, offset ) {
  6196. if ( array === undefined ) array = [];
  6197. if ( offset === undefined ) offset = 0;
  6198. array[ offset ] = this._x;
  6199. array[ offset + 1 ] = this._y;
  6200. array[ offset + 2 ] = this._z;
  6201. array[ offset + 3 ] = this._order;
  6202. return array;
  6203. },
  6204. toVector3: function ( optionalResult ) {
  6205. if ( optionalResult ) {
  6206. return optionalResult.set( this._x, this._y, this._z );
  6207. } else {
  6208. return new Vector3( this._x, this._y, this._z );
  6209. }
  6210. },
  6211. onChange: function ( callback ) {
  6212. this.onChangeCallback = callback;
  6213. return this;
  6214. },
  6215. onChangeCallback: function () {}
  6216. } );
  6217. /**
  6218. * @author mrdoob / http://mrdoob.com/
  6219. */
  6220. function Layers() {
  6221. this.mask = 1 | 0;
  6222. }
  6223. Object.assign( Layers.prototype, {
  6224. set: function ( channel ) {
  6225. this.mask = 1 << channel | 0;
  6226. },
  6227. enable: function ( channel ) {
  6228. this.mask |= 1 << channel | 0;
  6229. },
  6230. toggle: function ( channel ) {
  6231. this.mask ^= 1 << channel | 0;
  6232. },
  6233. disable: function ( channel ) {
  6234. this.mask &= ~ ( 1 << channel | 0 );
  6235. },
  6236. test: function ( layers ) {
  6237. return ( this.mask & layers.mask ) !== 0;
  6238. }
  6239. } );
  6240. /**
  6241. * @author mrdoob / http://mrdoob.com/
  6242. * @author mikael emtinger / http://gomo.se/
  6243. * @author alteredq / http://alteredqualia.com/
  6244. * @author WestLangley / http://github.com/WestLangley
  6245. * @author elephantatwork / www.elephantatwork.ch
  6246. */
  6247. var object3DId = 0;
  6248. function Object3D() {
  6249. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6250. this.uuid = _Math.generateUUID();
  6251. this.name = '';
  6252. this.type = 'Object3D';
  6253. this.parent = null;
  6254. this.children = [];
  6255. this.up = Object3D.DefaultUp.clone();
  6256. var position = new Vector3();
  6257. var rotation = new Euler();
  6258. var quaternion = new Quaternion();
  6259. var scale = new Vector3( 1, 1, 1 );
  6260. function onRotationChange() {
  6261. quaternion.setFromEuler( rotation, false );
  6262. }
  6263. function onQuaternionChange() {
  6264. rotation.setFromQuaternion( quaternion, undefined, false );
  6265. }
  6266. rotation.onChange( onRotationChange );
  6267. quaternion.onChange( onQuaternionChange );
  6268. Object.defineProperties( this, {
  6269. position: {
  6270. enumerable: true,
  6271. value: position
  6272. },
  6273. rotation: {
  6274. enumerable: true,
  6275. value: rotation
  6276. },
  6277. quaternion: {
  6278. enumerable: true,
  6279. value: quaternion
  6280. },
  6281. scale: {
  6282. enumerable: true,
  6283. value: scale
  6284. },
  6285. modelViewMatrix: {
  6286. value: new Matrix4()
  6287. },
  6288. normalMatrix: {
  6289. value: new Matrix3()
  6290. }
  6291. } );
  6292. this.matrix = new Matrix4();
  6293. this.matrixWorld = new Matrix4();
  6294. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6295. this.matrixWorldNeedsUpdate = false;
  6296. this.layers = new Layers();
  6297. this.visible = true;
  6298. this.castShadow = false;
  6299. this.receiveShadow = false;
  6300. this.frustumCulled = true;
  6301. this.renderOrder = 0;
  6302. this.userData = {};
  6303. }
  6304. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6305. Object3D.DefaultMatrixAutoUpdate = true;
  6306. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6307. isObject3D: true,
  6308. onBeforeRender: function () {},
  6309. onAfterRender: function () {},
  6310. applyMatrix: function ( matrix ) {
  6311. this.matrix.multiplyMatrices( matrix, this.matrix );
  6312. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6313. },
  6314. applyQuaternion: function ( q ) {
  6315. this.quaternion.premultiply( q );
  6316. return this;
  6317. },
  6318. setRotationFromAxisAngle: function ( axis, angle ) {
  6319. // assumes axis is normalized
  6320. this.quaternion.setFromAxisAngle( axis, angle );
  6321. },
  6322. setRotationFromEuler: function ( euler ) {
  6323. this.quaternion.setFromEuler( euler, true );
  6324. },
  6325. setRotationFromMatrix: function ( m ) {
  6326. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6327. this.quaternion.setFromRotationMatrix( m );
  6328. },
  6329. setRotationFromQuaternion: function ( q ) {
  6330. // assumes q is normalized
  6331. this.quaternion.copy( q );
  6332. },
  6333. rotateOnAxis: function () {
  6334. // rotate object on axis in object space
  6335. // axis is assumed to be normalized
  6336. var q1 = new Quaternion();
  6337. return function rotateOnAxis( axis, angle ) {
  6338. q1.setFromAxisAngle( axis, angle );
  6339. this.quaternion.multiply( q1 );
  6340. return this;
  6341. };
  6342. }(),
  6343. rotateX: function () {
  6344. var v1 = new Vector3( 1, 0, 0 );
  6345. return function rotateX( angle ) {
  6346. return this.rotateOnAxis( v1, angle );
  6347. };
  6348. }(),
  6349. rotateY: function () {
  6350. var v1 = new Vector3( 0, 1, 0 );
  6351. return function rotateY( angle ) {
  6352. return this.rotateOnAxis( v1, angle );
  6353. };
  6354. }(),
  6355. rotateZ: function () {
  6356. var v1 = new Vector3( 0, 0, 1 );
  6357. return function rotateZ( angle ) {
  6358. return this.rotateOnAxis( v1, angle );
  6359. };
  6360. }(),
  6361. translateOnAxis: function () {
  6362. // translate object by distance along axis in object space
  6363. // axis is assumed to be normalized
  6364. var v1 = new Vector3();
  6365. return function translateOnAxis( axis, distance ) {
  6366. v1.copy( axis ).applyQuaternion( this.quaternion );
  6367. this.position.add( v1.multiplyScalar( distance ) );
  6368. return this;
  6369. };
  6370. }(),
  6371. translateX: function () {
  6372. var v1 = new Vector3( 1, 0, 0 );
  6373. return function translateX( distance ) {
  6374. return this.translateOnAxis( v1, distance );
  6375. };
  6376. }(),
  6377. translateY: function () {
  6378. var v1 = new Vector3( 0, 1, 0 );
  6379. return function translateY( distance ) {
  6380. return this.translateOnAxis( v1, distance );
  6381. };
  6382. }(),
  6383. translateZ: function () {
  6384. var v1 = new Vector3( 0, 0, 1 );
  6385. return function translateZ( distance ) {
  6386. return this.translateOnAxis( v1, distance );
  6387. };
  6388. }(),
  6389. localToWorld: function ( vector ) {
  6390. return vector.applyMatrix4( this.matrixWorld );
  6391. },
  6392. worldToLocal: function () {
  6393. var m1 = new Matrix4();
  6394. return function worldToLocal( vector ) {
  6395. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6396. };
  6397. }(),
  6398. lookAt: function () {
  6399. // This method does not support objects with rotated and/or translated parent(s)
  6400. var m1 = new Matrix4();
  6401. return function lookAt( vector ) {
  6402. if ( this.isCamera ) {
  6403. m1.lookAt( this.position, vector, this.up );
  6404. } else {
  6405. m1.lookAt( vector, this.position, this.up );
  6406. }
  6407. this.quaternion.setFromRotationMatrix( m1 );
  6408. };
  6409. }(),
  6410. add: function ( object ) {
  6411. if ( arguments.length > 1 ) {
  6412. for ( var i = 0; i < arguments.length; i ++ ) {
  6413. this.add( arguments[ i ] );
  6414. }
  6415. return this;
  6416. }
  6417. if ( object === this ) {
  6418. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6419. return this;
  6420. }
  6421. if ( ( object && object.isObject3D ) ) {
  6422. if ( object.parent !== null ) {
  6423. object.parent.remove( object );
  6424. }
  6425. object.parent = this;
  6426. object.dispatchEvent( { type: 'added' } );
  6427. this.children.push( object );
  6428. } else {
  6429. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6430. }
  6431. return this;
  6432. },
  6433. remove: function ( object ) {
  6434. if ( arguments.length > 1 ) {
  6435. for ( var i = 0; i < arguments.length; i ++ ) {
  6436. this.remove( arguments[ i ] );
  6437. }
  6438. return this;
  6439. }
  6440. var index = this.children.indexOf( object );
  6441. if ( index !== - 1 ) {
  6442. object.parent = null;
  6443. object.dispatchEvent( { type: 'removed' } );
  6444. this.children.splice( index, 1 );
  6445. }
  6446. return this;
  6447. },
  6448. getObjectById: function ( id ) {
  6449. return this.getObjectByProperty( 'id', id );
  6450. },
  6451. getObjectByName: function ( name ) {
  6452. return this.getObjectByProperty( 'name', name );
  6453. },
  6454. getObjectByProperty: function ( name, value ) {
  6455. if ( this[ name ] === value ) return this;
  6456. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6457. var child = this.children[ i ];
  6458. var object = child.getObjectByProperty( name, value );
  6459. if ( object !== undefined ) {
  6460. return object;
  6461. }
  6462. }
  6463. return undefined;
  6464. },
  6465. getWorldPosition: function ( optionalTarget ) {
  6466. var result = optionalTarget || new Vector3();
  6467. this.updateMatrixWorld( true );
  6468. return result.setFromMatrixPosition( this.matrixWorld );
  6469. },
  6470. getWorldQuaternion: function () {
  6471. var position = new Vector3();
  6472. var scale = new Vector3();
  6473. return function getWorldQuaternion( optionalTarget ) {
  6474. var result = optionalTarget || new Quaternion();
  6475. this.updateMatrixWorld( true );
  6476. this.matrixWorld.decompose( position, result, scale );
  6477. return result;
  6478. };
  6479. }(),
  6480. getWorldRotation: function () {
  6481. var quaternion = new Quaternion();
  6482. return function getWorldRotation( optionalTarget ) {
  6483. var result = optionalTarget || new Euler();
  6484. this.getWorldQuaternion( quaternion );
  6485. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6486. };
  6487. }(),
  6488. getWorldScale: function () {
  6489. var position = new Vector3();
  6490. var quaternion = new Quaternion();
  6491. return function getWorldScale( optionalTarget ) {
  6492. var result = optionalTarget || new Vector3();
  6493. this.updateMatrixWorld( true );
  6494. this.matrixWorld.decompose( position, quaternion, result );
  6495. return result;
  6496. };
  6497. }(),
  6498. getWorldDirection: function () {
  6499. var quaternion = new Quaternion();
  6500. return function getWorldDirection( optionalTarget ) {
  6501. var result = optionalTarget || new Vector3();
  6502. this.getWorldQuaternion( quaternion );
  6503. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6504. };
  6505. }(),
  6506. raycast: function () {},
  6507. traverse: function ( callback ) {
  6508. callback( this );
  6509. var children = this.children;
  6510. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6511. children[ i ].traverse( callback );
  6512. }
  6513. },
  6514. traverseVisible: function ( callback ) {
  6515. if ( this.visible === false ) return;
  6516. callback( this );
  6517. var children = this.children;
  6518. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6519. children[ i ].traverseVisible( callback );
  6520. }
  6521. },
  6522. traverseAncestors: function ( callback ) {
  6523. var parent = this.parent;
  6524. if ( parent !== null ) {
  6525. callback( parent );
  6526. parent.traverseAncestors( callback );
  6527. }
  6528. },
  6529. updateMatrix: function () {
  6530. this.matrix.compose( this.position, this.quaternion, this.scale );
  6531. this.matrixWorldNeedsUpdate = true;
  6532. },
  6533. updateMatrixWorld: function ( force ) {
  6534. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6535. if ( this.matrixWorldNeedsUpdate || force ) {
  6536. if ( this.parent === null ) {
  6537. this.matrixWorld.copy( this.matrix );
  6538. } else {
  6539. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6540. }
  6541. this.matrixWorldNeedsUpdate = false;
  6542. force = true;
  6543. }
  6544. // update children
  6545. var children = this.children;
  6546. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6547. children[ i ].updateMatrixWorld( force );
  6548. }
  6549. },
  6550. toJSON: function ( meta ) {
  6551. // meta is '' when called from JSON.stringify
  6552. var isRootObject = ( meta === undefined || meta === '' );
  6553. var output = {};
  6554. // meta is a hash used to collect geometries, materials.
  6555. // not providing it implies that this is the root object
  6556. // being serialized.
  6557. if ( isRootObject ) {
  6558. // initialize meta obj
  6559. meta = {
  6560. geometries: {},
  6561. materials: {},
  6562. textures: {},
  6563. images: {}
  6564. };
  6565. output.metadata = {
  6566. version: 4.5,
  6567. type: 'Object',
  6568. generator: 'Object3D.toJSON'
  6569. };
  6570. }
  6571. // standard Object3D serialization
  6572. var object = {};
  6573. object.uuid = this.uuid;
  6574. object.type = this.type;
  6575. if ( this.name !== '' ) object.name = this.name;
  6576. if ( this.castShadow === true ) object.castShadow = true;
  6577. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6578. if ( this.visible === false ) object.visible = false;
  6579. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6580. object.matrix = this.matrix.toArray();
  6581. //
  6582. function serialize( library, element ) {
  6583. if ( library[ element.uuid ] === undefined ) {
  6584. library[ element.uuid ] = element.toJSON( meta );
  6585. }
  6586. return element.uuid;
  6587. }
  6588. if ( this.geometry !== undefined ) {
  6589. object.geometry = serialize( meta.geometries, this.geometry );
  6590. }
  6591. if ( this.material !== undefined ) {
  6592. if ( Array.isArray( this.material ) ) {
  6593. var uuids = [];
  6594. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6595. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6596. }
  6597. object.material = uuids;
  6598. } else {
  6599. object.material = serialize( meta.materials, this.material );
  6600. }
  6601. }
  6602. //
  6603. if ( this.children.length > 0 ) {
  6604. object.children = [];
  6605. for ( var i = 0; i < this.children.length; i ++ ) {
  6606. object.children.push( this.children[ i ].toJSON( meta ).object );
  6607. }
  6608. }
  6609. if ( isRootObject ) {
  6610. var geometries = extractFromCache( meta.geometries );
  6611. var materials = extractFromCache( meta.materials );
  6612. var textures = extractFromCache( meta.textures );
  6613. var images = extractFromCache( meta.images );
  6614. if ( geometries.length > 0 ) output.geometries = geometries;
  6615. if ( materials.length > 0 ) output.materials = materials;
  6616. if ( textures.length > 0 ) output.textures = textures;
  6617. if ( images.length > 0 ) output.images = images;
  6618. }
  6619. output.object = object;
  6620. return output;
  6621. // extract data from the cache hash
  6622. // remove metadata on each item
  6623. // and return as array
  6624. function extractFromCache( cache ) {
  6625. var values = [];
  6626. for ( var key in cache ) {
  6627. var data = cache[ key ];
  6628. delete data.metadata;
  6629. values.push( data );
  6630. }
  6631. return values;
  6632. }
  6633. },
  6634. clone: function ( recursive ) {
  6635. return new this.constructor().copy( this, recursive );
  6636. },
  6637. copy: function ( source, recursive ) {
  6638. if ( recursive === undefined ) recursive = true;
  6639. this.name = source.name;
  6640. this.up.copy( source.up );
  6641. this.position.copy( source.position );
  6642. this.quaternion.copy( source.quaternion );
  6643. this.scale.copy( source.scale );
  6644. this.matrix.copy( source.matrix );
  6645. this.matrixWorld.copy( source.matrixWorld );
  6646. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6647. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6648. this.layers.mask = source.layers.mask;
  6649. this.visible = source.visible;
  6650. this.castShadow = source.castShadow;
  6651. this.receiveShadow = source.receiveShadow;
  6652. this.frustumCulled = source.frustumCulled;
  6653. this.renderOrder = source.renderOrder;
  6654. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6655. if ( recursive === true ) {
  6656. for ( var i = 0; i < source.children.length; i ++ ) {
  6657. var child = source.children[ i ];
  6658. this.add( child.clone() );
  6659. }
  6660. }
  6661. return this;
  6662. }
  6663. } );
  6664. /**
  6665. * @author mrdoob / http://mrdoob.com/
  6666. * @author mikael emtinger / http://gomo.se/
  6667. * @author WestLangley / http://github.com/WestLangley
  6668. */
  6669. function Camera() {
  6670. Object3D.call( this );
  6671. this.type = 'Camera';
  6672. this.matrixWorldInverse = new Matrix4();
  6673. this.projectionMatrix = new Matrix4();
  6674. }
  6675. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6676. constructor: Camera,
  6677. isCamera: true,
  6678. copy: function ( source, recursive ) {
  6679. Object3D.prototype.copy.call( this, source, recursive );
  6680. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6681. this.projectionMatrix.copy( source.projectionMatrix );
  6682. return this;
  6683. },
  6684. getWorldDirection: function () {
  6685. var quaternion = new Quaternion();
  6686. return function getWorldDirection( optionalTarget ) {
  6687. var result = optionalTarget || new Vector3();
  6688. this.getWorldQuaternion( quaternion );
  6689. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6690. };
  6691. }(),
  6692. updateMatrixWorld: function ( force ) {
  6693. Object3D.prototype.updateMatrixWorld.call( this, force );
  6694. this.matrixWorldInverse.getInverse( this.matrixWorld );
  6695. },
  6696. clone: function () {
  6697. return new this.constructor().copy( this );
  6698. }
  6699. } );
  6700. /**
  6701. * @author alteredq / http://alteredqualia.com/
  6702. * @author arose / http://github.com/arose
  6703. */
  6704. function OrthographicCamera( left, right, top, bottom, near, far ) {
  6705. Camera.call( this );
  6706. this.type = 'OrthographicCamera';
  6707. this.zoom = 1;
  6708. this.view = null;
  6709. this.left = left;
  6710. this.right = right;
  6711. this.top = top;
  6712. this.bottom = bottom;
  6713. this.near = ( near !== undefined ) ? near : 0.1;
  6714. this.far = ( far !== undefined ) ? far : 2000;
  6715. this.updateProjectionMatrix();
  6716. }
  6717. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6718. constructor: OrthographicCamera,
  6719. isOrthographicCamera: true,
  6720. copy: function ( source, recursive ) {
  6721. Camera.prototype.copy.call( this, source, recursive );
  6722. this.left = source.left;
  6723. this.right = source.right;
  6724. this.top = source.top;
  6725. this.bottom = source.bottom;
  6726. this.near = source.near;
  6727. this.far = source.far;
  6728. this.zoom = source.zoom;
  6729. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6730. return this;
  6731. },
  6732. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  6733. this.view = {
  6734. fullWidth: fullWidth,
  6735. fullHeight: fullHeight,
  6736. offsetX: x,
  6737. offsetY: y,
  6738. width: width,
  6739. height: height
  6740. };
  6741. this.updateProjectionMatrix();
  6742. },
  6743. clearViewOffset: function() {
  6744. this.view = null;
  6745. this.updateProjectionMatrix();
  6746. },
  6747. updateProjectionMatrix: function () {
  6748. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6749. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6750. var cx = ( this.right + this.left ) / 2;
  6751. var cy = ( this.top + this.bottom ) / 2;
  6752. var left = cx - dx;
  6753. var right = cx + dx;
  6754. var top = cy + dy;
  6755. var bottom = cy - dy;
  6756. if ( this.view !== null ) {
  6757. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  6758. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  6759. var scaleW = ( this.right - this.left ) / this.view.width;
  6760. var scaleH = ( this.top - this.bottom ) / this.view.height;
  6761. left += scaleW * ( this.view.offsetX / zoomW );
  6762. right = left + scaleW * ( this.view.width / zoomW );
  6763. top -= scaleH * ( this.view.offsetY / zoomH );
  6764. bottom = top - scaleH * ( this.view.height / zoomH );
  6765. }
  6766. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  6767. },
  6768. toJSON: function ( meta ) {
  6769. var data = Object3D.prototype.toJSON.call( this, meta );
  6770. data.object.zoom = this.zoom;
  6771. data.object.left = this.left;
  6772. data.object.right = this.right;
  6773. data.object.top = this.top;
  6774. data.object.bottom = this.bottom;
  6775. data.object.near = this.near;
  6776. data.object.far = this.far;
  6777. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6778. return data;
  6779. }
  6780. } );
  6781. /**
  6782. * @author mrdoob / http://mrdoob.com/
  6783. * @author greggman / http://games.greggman.com/
  6784. * @author zz85 / http://www.lab4games.net/zz85/blog
  6785. * @author tschw
  6786. */
  6787. function PerspectiveCamera( fov, aspect, near, far ) {
  6788. Camera.call( this );
  6789. this.type = 'PerspectiveCamera';
  6790. this.fov = fov !== undefined ? fov : 50;
  6791. this.zoom = 1;
  6792. this.near = near !== undefined ? near : 0.1;
  6793. this.far = far !== undefined ? far : 2000;
  6794. this.focus = 10;
  6795. this.aspect = aspect !== undefined ? aspect : 1;
  6796. this.view = null;
  6797. this.filmGauge = 35; // width of the film (default in millimeters)
  6798. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6799. this.updateProjectionMatrix();
  6800. }
  6801. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6802. constructor: PerspectiveCamera,
  6803. isPerspectiveCamera: true,
  6804. copy: function ( source, recursive ) {
  6805. Camera.prototype.copy.call( this, source, recursive );
  6806. this.fov = source.fov;
  6807. this.zoom = source.zoom;
  6808. this.near = source.near;
  6809. this.far = source.far;
  6810. this.focus = source.focus;
  6811. this.aspect = source.aspect;
  6812. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6813. this.filmGauge = source.filmGauge;
  6814. this.filmOffset = source.filmOffset;
  6815. return this;
  6816. },
  6817. /**
  6818. * Sets the FOV by focal length in respect to the current .filmGauge.
  6819. *
  6820. * The default film gauge is 35, so that the focal length can be specified for
  6821. * a 35mm (full frame) camera.
  6822. *
  6823. * Values for focal length and film gauge must have the same unit.
  6824. */
  6825. setFocalLength: function ( focalLength ) {
  6826. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  6827. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6828. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6829. this.updateProjectionMatrix();
  6830. },
  6831. /**
  6832. * Calculates the focal length from the current .fov and .filmGauge.
  6833. */
  6834. getFocalLength: function () {
  6835. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  6836. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6837. },
  6838. getEffectiveFOV: function () {
  6839. return _Math.RAD2DEG * 2 * Math.atan(
  6840. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6841. },
  6842. getFilmWidth: function () {
  6843. // film not completely covered in portrait format (aspect < 1)
  6844. return this.filmGauge * Math.min( this.aspect, 1 );
  6845. },
  6846. getFilmHeight: function () {
  6847. // film not completely covered in landscape format (aspect > 1)
  6848. return this.filmGauge / Math.max( this.aspect, 1 );
  6849. },
  6850. /**
  6851. * Sets an offset in a larger frustum. This is useful for multi-window or
  6852. * multi-monitor/multi-machine setups.
  6853. *
  6854. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6855. * the monitors are in grid like this
  6856. *
  6857. * +---+---+---+
  6858. * | A | B | C |
  6859. * +---+---+---+
  6860. * | D | E | F |
  6861. * +---+---+---+
  6862. *
  6863. * then for each monitor you would call it like this
  6864. *
  6865. * var w = 1920;
  6866. * var h = 1080;
  6867. * var fullWidth = w * 3;
  6868. * var fullHeight = h * 2;
  6869. *
  6870. * --A--
  6871. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6872. * --B--
  6873. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6874. * --C--
  6875. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6876. * --D--
  6877. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6878. * --E--
  6879. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6880. * --F--
  6881. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6882. *
  6883. * Note there is no reason monitors have to be the same size or in a grid.
  6884. */
  6885. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  6886. this.aspect = fullWidth / fullHeight;
  6887. this.view = {
  6888. fullWidth: fullWidth,
  6889. fullHeight: fullHeight,
  6890. offsetX: x,
  6891. offsetY: y,
  6892. width: width,
  6893. height: height
  6894. };
  6895. this.updateProjectionMatrix();
  6896. },
  6897. clearViewOffset: function () {
  6898. this.view = null;
  6899. this.updateProjectionMatrix();
  6900. },
  6901. updateProjectionMatrix: function () {
  6902. var near = this.near,
  6903. top = near * Math.tan(
  6904. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  6905. height = 2 * top,
  6906. width = this.aspect * height,
  6907. left = - 0.5 * width,
  6908. view = this.view;
  6909. if ( view !== null ) {
  6910. var fullWidth = view.fullWidth,
  6911. fullHeight = view.fullHeight;
  6912. left += view.offsetX * width / fullWidth;
  6913. top -= view.offsetY * height / fullHeight;
  6914. width *= view.width / fullWidth;
  6915. height *= view.height / fullHeight;
  6916. }
  6917. var skew = this.filmOffset;
  6918. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6919. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6920. },
  6921. toJSON: function ( meta ) {
  6922. var data = Object3D.prototype.toJSON.call( this, meta );
  6923. data.object.fov = this.fov;
  6924. data.object.zoom = this.zoom;
  6925. data.object.near = this.near;
  6926. data.object.far = this.far;
  6927. data.object.focus = this.focus;
  6928. data.object.aspect = this.aspect;
  6929. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6930. data.object.filmGauge = this.filmGauge;
  6931. data.object.filmOffset = this.filmOffset;
  6932. return data;
  6933. }
  6934. } );
  6935. /**
  6936. * @author mrdoob / http://mrdoob.com/
  6937. * @author alteredq / http://alteredqualia.com/
  6938. */
  6939. function Face3( a, b, c, normal, color, materialIndex ) {
  6940. this.a = a;
  6941. this.b = b;
  6942. this.c = c;
  6943. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6944. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6945. this.color = ( color && color.isColor ) ? color : new Color();
  6946. this.vertexColors = Array.isArray( color ) ? color : [];
  6947. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6948. }
  6949. Object.assign( Face3.prototype, {
  6950. clone: function () {
  6951. return new this.constructor().copy( this );
  6952. },
  6953. copy: function ( source ) {
  6954. this.a = source.a;
  6955. this.b = source.b;
  6956. this.c = source.c;
  6957. this.normal.copy( source.normal );
  6958. this.color.copy( source.color );
  6959. this.materialIndex = source.materialIndex;
  6960. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6961. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6962. }
  6963. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6964. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6965. }
  6966. return this;
  6967. }
  6968. } );
  6969. /**
  6970. * @author mrdoob / http://mrdoob.com/
  6971. * @author kile / http://kile.stravaganza.org/
  6972. * @author alteredq / http://alteredqualia.com/
  6973. * @author mikael emtinger / http://gomo.se/
  6974. * @author zz85 / http://www.lab4games.net/zz85/blog
  6975. * @author bhouston / http://clara.io
  6976. */
  6977. var count = 0;
  6978. function GeometryIdCount() { return count++; }
  6979. function Geometry() {
  6980. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6981. this.uuid = _Math.generateUUID();
  6982. this.name = '';
  6983. this.type = 'Geometry';
  6984. this.vertices = [];
  6985. this.colors = [];
  6986. this.faces = [];
  6987. this.faceVertexUvs = [[]];
  6988. this.morphTargets = [];
  6989. this.morphNormals = [];
  6990. this.skinWeights = [];
  6991. this.skinIndices = [];
  6992. this.lineDistances = [];
  6993. this.boundingBox = null;
  6994. this.boundingSphere = null;
  6995. // update flags
  6996. this.elementsNeedUpdate = false;
  6997. this.verticesNeedUpdate = false;
  6998. this.uvsNeedUpdate = false;
  6999. this.normalsNeedUpdate = false;
  7000. this.colorsNeedUpdate = false;
  7001. this.lineDistancesNeedUpdate = false;
  7002. this.groupsNeedUpdate = false;
  7003. }
  7004. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7005. isGeometry: true,
  7006. applyMatrix: function ( matrix ) {
  7007. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7008. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7009. var vertex = this.vertices[ i ];
  7010. vertex.applyMatrix4( matrix );
  7011. }
  7012. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7013. var face = this.faces[ i ];
  7014. face.normal.applyMatrix3( normalMatrix ).normalize();
  7015. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7016. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7017. }
  7018. }
  7019. if ( this.boundingBox !== null ) {
  7020. this.computeBoundingBox();
  7021. }
  7022. if ( this.boundingSphere !== null ) {
  7023. this.computeBoundingSphere();
  7024. }
  7025. this.verticesNeedUpdate = true;
  7026. this.normalsNeedUpdate = true;
  7027. return this;
  7028. },
  7029. rotateX: function () {
  7030. // rotate geometry around world x-axis
  7031. var m1 = new Matrix4();
  7032. return function rotateX( angle ) {
  7033. m1.makeRotationX( angle );
  7034. this.applyMatrix( m1 );
  7035. return this;
  7036. };
  7037. }(),
  7038. rotateY: function () {
  7039. // rotate geometry around world y-axis
  7040. var m1 = new Matrix4();
  7041. return function rotateY( angle ) {
  7042. m1.makeRotationY( angle );
  7043. this.applyMatrix( m1 );
  7044. return this;
  7045. };
  7046. }(),
  7047. rotateZ: function () {
  7048. // rotate geometry around world z-axis
  7049. var m1 = new Matrix4();
  7050. return function rotateZ( angle ) {
  7051. m1.makeRotationZ( angle );
  7052. this.applyMatrix( m1 );
  7053. return this;
  7054. };
  7055. }(),
  7056. translate: function () {
  7057. // translate geometry
  7058. var m1 = new Matrix4();
  7059. return function translate( x, y, z ) {
  7060. m1.makeTranslation( x, y, z );
  7061. this.applyMatrix( m1 );
  7062. return this;
  7063. };
  7064. }(),
  7065. scale: function () {
  7066. // scale geometry
  7067. var m1 = new Matrix4();
  7068. return function scale( x, y, z ) {
  7069. m1.makeScale( x, y, z );
  7070. this.applyMatrix( m1 );
  7071. return this;
  7072. };
  7073. }(),
  7074. lookAt: function () {
  7075. var obj = new Object3D();
  7076. return function lookAt( vector ) {
  7077. obj.lookAt( vector );
  7078. obj.updateMatrix();
  7079. this.applyMatrix( obj.matrix );
  7080. };
  7081. }(),
  7082. fromBufferGeometry: function ( geometry ) {
  7083. var scope = this;
  7084. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7085. var attributes = geometry.attributes;
  7086. var positions = attributes.position.array;
  7087. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7088. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7089. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7090. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7091. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7092. var tempNormals = [];
  7093. var tempUVs = [];
  7094. var tempUVs2 = [];
  7095. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7096. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7097. if ( normals !== undefined ) {
  7098. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7099. }
  7100. if ( colors !== undefined ) {
  7101. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7102. }
  7103. if ( uvs !== undefined ) {
  7104. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7105. }
  7106. if ( uvs2 !== undefined ) {
  7107. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7108. }
  7109. }
  7110. function addFace( a, b, c, materialIndex ) {
  7111. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7112. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7113. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7114. scope.faces.push( face );
  7115. if ( uvs !== undefined ) {
  7116. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7117. }
  7118. if ( uvs2 !== undefined ) {
  7119. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7120. }
  7121. }
  7122. var groups = geometry.groups;
  7123. if ( groups.length > 0 ) {
  7124. for ( var i = 0; i < groups.length; i ++ ) {
  7125. var group = groups[ i ];
  7126. var start = group.start;
  7127. var count = group.count;
  7128. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7129. if ( indices !== undefined ) {
  7130. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7131. } else {
  7132. addFace( j, j + 1, j + 2, group.materialIndex );
  7133. }
  7134. }
  7135. }
  7136. } else {
  7137. if ( indices !== undefined ) {
  7138. for ( var i = 0; i < indices.length; i += 3 ) {
  7139. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7140. }
  7141. } else {
  7142. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7143. addFace( i, i + 1, i + 2 );
  7144. }
  7145. }
  7146. }
  7147. this.computeFaceNormals();
  7148. if ( geometry.boundingBox !== null ) {
  7149. this.boundingBox = geometry.boundingBox.clone();
  7150. }
  7151. if ( geometry.boundingSphere !== null ) {
  7152. this.boundingSphere = geometry.boundingSphere.clone();
  7153. }
  7154. return this;
  7155. },
  7156. center: function () {
  7157. this.computeBoundingBox();
  7158. var offset = this.boundingBox.getCenter().negate();
  7159. this.translate( offset.x, offset.y, offset.z );
  7160. return offset;
  7161. },
  7162. normalize: function () {
  7163. this.computeBoundingSphere();
  7164. var center = this.boundingSphere.center;
  7165. var radius = this.boundingSphere.radius;
  7166. var s = radius === 0 ? 1 : 1.0 / radius;
  7167. var matrix = new Matrix4();
  7168. matrix.set(
  7169. s, 0, 0, - s * center.x,
  7170. 0, s, 0, - s * center.y,
  7171. 0, 0, s, - s * center.z,
  7172. 0, 0, 0, 1
  7173. );
  7174. this.applyMatrix( matrix );
  7175. return this;
  7176. },
  7177. computeFaceNormals: function () {
  7178. var cb = new Vector3(), ab = new Vector3();
  7179. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7180. var face = this.faces[ f ];
  7181. var vA = this.vertices[ face.a ];
  7182. var vB = this.vertices[ face.b ];
  7183. var vC = this.vertices[ face.c ];
  7184. cb.subVectors( vC, vB );
  7185. ab.subVectors( vA, vB );
  7186. cb.cross( ab );
  7187. cb.normalize();
  7188. face.normal.copy( cb );
  7189. }
  7190. },
  7191. computeVertexNormals: function ( areaWeighted ) {
  7192. if ( areaWeighted === undefined ) areaWeighted = true;
  7193. var v, vl, f, fl, face, vertices;
  7194. vertices = new Array( this.vertices.length );
  7195. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7196. vertices[ v ] = new Vector3();
  7197. }
  7198. if ( areaWeighted ) {
  7199. // vertex normals weighted by triangle areas
  7200. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7201. var vA, vB, vC;
  7202. var cb = new Vector3(), ab = new Vector3();
  7203. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7204. face = this.faces[ f ];
  7205. vA = this.vertices[ face.a ];
  7206. vB = this.vertices[ face.b ];
  7207. vC = this.vertices[ face.c ];
  7208. cb.subVectors( vC, vB );
  7209. ab.subVectors( vA, vB );
  7210. cb.cross( ab );
  7211. vertices[ face.a ].add( cb );
  7212. vertices[ face.b ].add( cb );
  7213. vertices[ face.c ].add( cb );
  7214. }
  7215. } else {
  7216. this.computeFaceNormals();
  7217. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7218. face = this.faces[ f ];
  7219. vertices[ face.a ].add( face.normal );
  7220. vertices[ face.b ].add( face.normal );
  7221. vertices[ face.c ].add( face.normal );
  7222. }
  7223. }
  7224. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7225. vertices[ v ].normalize();
  7226. }
  7227. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7228. face = this.faces[ f ];
  7229. var vertexNormals = face.vertexNormals;
  7230. if ( vertexNormals.length === 3 ) {
  7231. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7232. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7233. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7234. } else {
  7235. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7236. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7237. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7238. }
  7239. }
  7240. if ( this.faces.length > 0 ) {
  7241. this.normalsNeedUpdate = true;
  7242. }
  7243. },
  7244. computeFlatVertexNormals: function () {
  7245. var f, fl, face;
  7246. this.computeFaceNormals();
  7247. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7248. face = this.faces[ f ];
  7249. var vertexNormals = face.vertexNormals;
  7250. if ( vertexNormals.length === 3 ) {
  7251. vertexNormals[ 0 ].copy( face.normal );
  7252. vertexNormals[ 1 ].copy( face.normal );
  7253. vertexNormals[ 2 ].copy( face.normal );
  7254. } else {
  7255. vertexNormals[ 0 ] = face.normal.clone();
  7256. vertexNormals[ 1 ] = face.normal.clone();
  7257. vertexNormals[ 2 ] = face.normal.clone();
  7258. }
  7259. }
  7260. if ( this.faces.length > 0 ) {
  7261. this.normalsNeedUpdate = true;
  7262. }
  7263. },
  7264. computeMorphNormals: function () {
  7265. var i, il, f, fl, face;
  7266. // save original normals
  7267. // - create temp variables on first access
  7268. // otherwise just copy (for faster repeated calls)
  7269. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7270. face = this.faces[ f ];
  7271. if ( ! face.__originalFaceNormal ) {
  7272. face.__originalFaceNormal = face.normal.clone();
  7273. } else {
  7274. face.__originalFaceNormal.copy( face.normal );
  7275. }
  7276. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7277. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7278. if ( ! face.__originalVertexNormals[ i ] ) {
  7279. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7280. } else {
  7281. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7282. }
  7283. }
  7284. }
  7285. // use temp geometry to compute face and vertex normals for each morph
  7286. var tmpGeo = new Geometry();
  7287. tmpGeo.faces = this.faces;
  7288. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7289. // create on first access
  7290. if ( ! this.morphNormals[ i ] ) {
  7291. this.morphNormals[ i ] = {};
  7292. this.morphNormals[ i ].faceNormals = [];
  7293. this.morphNormals[ i ].vertexNormals = [];
  7294. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7295. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7296. var faceNormal, vertexNormals;
  7297. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7298. faceNormal = new Vector3();
  7299. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7300. dstNormalsFace.push( faceNormal );
  7301. dstNormalsVertex.push( vertexNormals );
  7302. }
  7303. }
  7304. var morphNormals = this.morphNormals[ i ];
  7305. // set vertices to morph target
  7306. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7307. // compute morph normals
  7308. tmpGeo.computeFaceNormals();
  7309. tmpGeo.computeVertexNormals();
  7310. // store morph normals
  7311. var faceNormal, vertexNormals;
  7312. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7313. face = this.faces[ f ];
  7314. faceNormal = morphNormals.faceNormals[ f ];
  7315. vertexNormals = morphNormals.vertexNormals[ f ];
  7316. faceNormal.copy( face.normal );
  7317. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7318. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7319. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7320. }
  7321. }
  7322. // restore original normals
  7323. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7324. face = this.faces[ f ];
  7325. face.normal = face.__originalFaceNormal;
  7326. face.vertexNormals = face.__originalVertexNormals;
  7327. }
  7328. },
  7329. computeLineDistances: function () {
  7330. var d = 0;
  7331. var vertices = this.vertices;
  7332. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7333. if ( i > 0 ) {
  7334. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7335. }
  7336. this.lineDistances[ i ] = d;
  7337. }
  7338. },
  7339. computeBoundingBox: function () {
  7340. if ( this.boundingBox === null ) {
  7341. this.boundingBox = new Box3();
  7342. }
  7343. this.boundingBox.setFromPoints( this.vertices );
  7344. },
  7345. computeBoundingSphere: function () {
  7346. if ( this.boundingSphere === null ) {
  7347. this.boundingSphere = new Sphere();
  7348. }
  7349. this.boundingSphere.setFromPoints( this.vertices );
  7350. },
  7351. merge: function ( geometry, matrix, materialIndexOffset ) {
  7352. if ( ! ( geometry && geometry.isGeometry ) ) {
  7353. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7354. return;
  7355. }
  7356. var normalMatrix,
  7357. vertexOffset = this.vertices.length,
  7358. vertices1 = this.vertices,
  7359. vertices2 = geometry.vertices,
  7360. faces1 = this.faces,
  7361. faces2 = geometry.faces,
  7362. uvs1 = this.faceVertexUvs[ 0 ],
  7363. uvs2 = geometry.faceVertexUvs[ 0 ],
  7364. colors1 = this.colors,
  7365. colors2 = geometry.colors;
  7366. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7367. if ( matrix !== undefined ) {
  7368. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7369. }
  7370. // vertices
  7371. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7372. var vertex = vertices2[ i ];
  7373. var vertexCopy = vertex.clone();
  7374. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7375. vertices1.push( vertexCopy );
  7376. }
  7377. // colors
  7378. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7379. colors1.push( colors2[ i ].clone() );
  7380. }
  7381. // faces
  7382. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7383. var face = faces2[ i ], faceCopy, normal, color,
  7384. faceVertexNormals = face.vertexNormals,
  7385. faceVertexColors = face.vertexColors;
  7386. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7387. faceCopy.normal.copy( face.normal );
  7388. if ( normalMatrix !== undefined ) {
  7389. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7390. }
  7391. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7392. normal = faceVertexNormals[ j ].clone();
  7393. if ( normalMatrix !== undefined ) {
  7394. normal.applyMatrix3( normalMatrix ).normalize();
  7395. }
  7396. faceCopy.vertexNormals.push( normal );
  7397. }
  7398. faceCopy.color.copy( face.color );
  7399. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7400. color = faceVertexColors[ j ];
  7401. faceCopy.vertexColors.push( color.clone() );
  7402. }
  7403. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7404. faces1.push( faceCopy );
  7405. }
  7406. // uvs
  7407. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7408. var uv = uvs2[ i ], uvCopy = [];
  7409. if ( uv === undefined ) {
  7410. continue;
  7411. }
  7412. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7413. uvCopy.push( uv[ j ].clone() );
  7414. }
  7415. uvs1.push( uvCopy );
  7416. }
  7417. },
  7418. mergeMesh: function ( mesh ) {
  7419. if ( ! ( mesh && mesh.isMesh ) ) {
  7420. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7421. return;
  7422. }
  7423. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7424. this.merge( mesh.geometry, mesh.matrix );
  7425. },
  7426. /*
  7427. * Checks for duplicate vertices with hashmap.
  7428. * Duplicated vertices are removed
  7429. * and faces' vertices are updated.
  7430. */
  7431. mergeVertices: function () {
  7432. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7433. var unique = [], changes = [];
  7434. var v, key;
  7435. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7436. var precision = Math.pow( 10, precisionPoints );
  7437. var i, il, face;
  7438. var indices, j, jl;
  7439. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7440. v = this.vertices[ i ];
  7441. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7442. if ( verticesMap[ key ] === undefined ) {
  7443. verticesMap[ key ] = i;
  7444. unique.push( this.vertices[ i ] );
  7445. changes[ i ] = unique.length - 1;
  7446. } else {
  7447. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7448. changes[ i ] = changes[ verticesMap[ key ] ];
  7449. }
  7450. }
  7451. // if faces are completely degenerate after merging vertices, we
  7452. // have to remove them from the geometry.
  7453. var faceIndicesToRemove = [];
  7454. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7455. face = this.faces[ i ];
  7456. face.a = changes[ face.a ];
  7457. face.b = changes[ face.b ];
  7458. face.c = changes[ face.c ];
  7459. indices = [ face.a, face.b, face.c ];
  7460. // if any duplicate vertices are found in a Face3
  7461. // we have to remove the face as nothing can be saved
  7462. for ( var n = 0; n < 3; n ++ ) {
  7463. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7464. faceIndicesToRemove.push( i );
  7465. break;
  7466. }
  7467. }
  7468. }
  7469. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7470. var idx = faceIndicesToRemove[ i ];
  7471. this.faces.splice( idx, 1 );
  7472. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7473. this.faceVertexUvs[ j ].splice( idx, 1 );
  7474. }
  7475. }
  7476. // Use unique set of vertices
  7477. var diff = this.vertices.length - unique.length;
  7478. this.vertices = unique;
  7479. return diff;
  7480. },
  7481. sortFacesByMaterialIndex: function () {
  7482. var faces = this.faces;
  7483. var length = faces.length;
  7484. // tag faces
  7485. for ( var i = 0; i < length; i ++ ) {
  7486. faces[ i ]._id = i;
  7487. }
  7488. // sort faces
  7489. function materialIndexSort( a, b ) {
  7490. return a.materialIndex - b.materialIndex;
  7491. }
  7492. faces.sort( materialIndexSort );
  7493. // sort uvs
  7494. var uvs1 = this.faceVertexUvs[ 0 ];
  7495. var uvs2 = this.faceVertexUvs[ 1 ];
  7496. var newUvs1, newUvs2;
  7497. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7498. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7499. for ( var i = 0; i < length; i ++ ) {
  7500. var id = faces[ i ]._id;
  7501. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7502. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7503. }
  7504. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7505. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7506. },
  7507. toJSON: function () {
  7508. var data = {
  7509. metadata: {
  7510. version: 4.5,
  7511. type: 'Geometry',
  7512. generator: 'Geometry.toJSON'
  7513. }
  7514. };
  7515. // standard Geometry serialization
  7516. data.uuid = this.uuid;
  7517. data.type = this.type;
  7518. if ( this.name !== '' ) data.name = this.name;
  7519. if ( this.parameters !== undefined ) {
  7520. var parameters = this.parameters;
  7521. for ( var key in parameters ) {
  7522. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7523. }
  7524. return data;
  7525. }
  7526. var vertices = [];
  7527. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7528. var vertex = this.vertices[ i ];
  7529. vertices.push( vertex.x, vertex.y, vertex.z );
  7530. }
  7531. var faces = [];
  7532. var normals = [];
  7533. var normalsHash = {};
  7534. var colors = [];
  7535. var colorsHash = {};
  7536. var uvs = [];
  7537. var uvsHash = {};
  7538. for ( var i = 0; i < this.faces.length; i ++ ) {
  7539. var face = this.faces[ i ];
  7540. var hasMaterial = true;
  7541. var hasFaceUv = false; // deprecated
  7542. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7543. var hasFaceNormal = face.normal.length() > 0;
  7544. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7545. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7546. var hasFaceVertexColor = face.vertexColors.length > 0;
  7547. var faceType = 0;
  7548. faceType = setBit( faceType, 0, 0 ); // isQuad
  7549. faceType = setBit( faceType, 1, hasMaterial );
  7550. faceType = setBit( faceType, 2, hasFaceUv );
  7551. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7552. faceType = setBit( faceType, 4, hasFaceNormal );
  7553. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7554. faceType = setBit( faceType, 6, hasFaceColor );
  7555. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7556. faces.push( faceType );
  7557. faces.push( face.a, face.b, face.c );
  7558. faces.push( face.materialIndex );
  7559. if ( hasFaceVertexUv ) {
  7560. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7561. faces.push(
  7562. getUvIndex( faceVertexUvs[ 0 ] ),
  7563. getUvIndex( faceVertexUvs[ 1 ] ),
  7564. getUvIndex( faceVertexUvs[ 2 ] )
  7565. );
  7566. }
  7567. if ( hasFaceNormal ) {
  7568. faces.push( getNormalIndex( face.normal ) );
  7569. }
  7570. if ( hasFaceVertexNormal ) {
  7571. var vertexNormals = face.vertexNormals;
  7572. faces.push(
  7573. getNormalIndex( vertexNormals[ 0 ] ),
  7574. getNormalIndex( vertexNormals[ 1 ] ),
  7575. getNormalIndex( vertexNormals[ 2 ] )
  7576. );
  7577. }
  7578. if ( hasFaceColor ) {
  7579. faces.push( getColorIndex( face.color ) );
  7580. }
  7581. if ( hasFaceVertexColor ) {
  7582. var vertexColors = face.vertexColors;
  7583. faces.push(
  7584. getColorIndex( vertexColors[ 0 ] ),
  7585. getColorIndex( vertexColors[ 1 ] ),
  7586. getColorIndex( vertexColors[ 2 ] )
  7587. );
  7588. }
  7589. }
  7590. function setBit( value, position, enabled ) {
  7591. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7592. }
  7593. function getNormalIndex( normal ) {
  7594. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7595. if ( normalsHash[ hash ] !== undefined ) {
  7596. return normalsHash[ hash ];
  7597. }
  7598. normalsHash[ hash ] = normals.length / 3;
  7599. normals.push( normal.x, normal.y, normal.z );
  7600. return normalsHash[ hash ];
  7601. }
  7602. function getColorIndex( color ) {
  7603. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7604. if ( colorsHash[ hash ] !== undefined ) {
  7605. return colorsHash[ hash ];
  7606. }
  7607. colorsHash[ hash ] = colors.length;
  7608. colors.push( color.getHex() );
  7609. return colorsHash[ hash ];
  7610. }
  7611. function getUvIndex( uv ) {
  7612. var hash = uv.x.toString() + uv.y.toString();
  7613. if ( uvsHash[ hash ] !== undefined ) {
  7614. return uvsHash[ hash ];
  7615. }
  7616. uvsHash[ hash ] = uvs.length / 2;
  7617. uvs.push( uv.x, uv.y );
  7618. return uvsHash[ hash ];
  7619. }
  7620. data.data = {};
  7621. data.data.vertices = vertices;
  7622. data.data.normals = normals;
  7623. if ( colors.length > 0 ) data.data.colors = colors;
  7624. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7625. data.data.faces = faces;
  7626. return data;
  7627. },
  7628. clone: function () {
  7629. /*
  7630. // Handle primitives
  7631. var parameters = this.parameters;
  7632. if ( parameters !== undefined ) {
  7633. var values = [];
  7634. for ( var key in parameters ) {
  7635. values.push( parameters[ key ] );
  7636. }
  7637. var geometry = Object.create( this.constructor.prototype );
  7638. this.constructor.apply( geometry, values );
  7639. return geometry;
  7640. }
  7641. return new this.constructor().copy( this );
  7642. */
  7643. return new Geometry().copy( this );
  7644. },
  7645. copy: function ( source ) {
  7646. var i, il, j, jl, k, kl;
  7647. // reset
  7648. this.vertices = [];
  7649. this.colors = [];
  7650. this.faces = [];
  7651. this.faceVertexUvs = [[]];
  7652. this.morphTargets = [];
  7653. this.morphNormals = [];
  7654. this.skinWeights = [];
  7655. this.skinIndices = [];
  7656. this.lineDistances = [];
  7657. this.boundingBox = null;
  7658. this.boundingSphere = null;
  7659. // name
  7660. this.name = source.name;
  7661. // vertices
  7662. var vertices = source.vertices;
  7663. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  7664. this.vertices.push( vertices[ i ].clone() );
  7665. }
  7666. // colors
  7667. var colors = source.colors;
  7668. for ( i = 0, il = colors.length; i < il; i ++ ) {
  7669. this.colors.push( colors[ i ].clone() );
  7670. }
  7671. // faces
  7672. var faces = source.faces;
  7673. for ( i = 0, il = faces.length; i < il; i ++ ) {
  7674. this.faces.push( faces[ i ].clone() );
  7675. }
  7676. // face vertex uvs
  7677. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7678. var faceVertexUvs = source.faceVertexUvs[ i ];
  7679. if ( this.faceVertexUvs[ i ] === undefined ) {
  7680. this.faceVertexUvs[ i ] = [];
  7681. }
  7682. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7683. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7684. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  7685. var uv = uvs[ k ];
  7686. uvsCopy.push( uv.clone() );
  7687. }
  7688. this.faceVertexUvs[ i ].push( uvsCopy );
  7689. }
  7690. }
  7691. // morph targets
  7692. var morphTargets = source.morphTargets;
  7693. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  7694. var morphTarget = {};
  7695. morphTarget.name = morphTargets[ i ].name;
  7696. // vertices
  7697. if ( morphTargets[ i ].vertices !== undefined ) {
  7698. morphTarget.vertices = [];
  7699. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7700. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7701. }
  7702. }
  7703. // normals
  7704. if ( morphTargets[ i ].normals !== undefined ) {
  7705. morphTarget.normals = [];
  7706. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7707. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7708. }
  7709. }
  7710. this.morphTargets.push( morphTarget );
  7711. }
  7712. // morph normals
  7713. var morphNormals = source.morphNormals;
  7714. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  7715. var morphNormal = {};
  7716. // vertex normals
  7717. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7718. morphNormal.vertexNormals = [];
  7719. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7720. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7721. var destVertexNormal = {};
  7722. destVertexNormal.a = srcVertexNormal.a.clone();
  7723. destVertexNormal.b = srcVertexNormal.b.clone();
  7724. destVertexNormal.c = srcVertexNormal.c.clone();
  7725. morphNormal.vertexNormals.push( destVertexNormal );
  7726. }
  7727. }
  7728. // face normals
  7729. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7730. morphNormal.faceNormals = [];
  7731. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7732. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7733. }
  7734. }
  7735. this.morphNormals.push( morphNormal );
  7736. }
  7737. // skin weights
  7738. var skinWeights = source.skinWeights;
  7739. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  7740. this.skinWeights.push( skinWeights[ i ].clone() );
  7741. }
  7742. // skin indices
  7743. var skinIndices = source.skinIndices;
  7744. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  7745. this.skinIndices.push( skinIndices[ i ].clone() );
  7746. }
  7747. // line distances
  7748. var lineDistances = source.lineDistances;
  7749. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  7750. this.lineDistances.push( lineDistances[ i ] );
  7751. }
  7752. // bounding box
  7753. var boundingBox = source.boundingBox;
  7754. if ( boundingBox !== null ) {
  7755. this.boundingBox = boundingBox.clone();
  7756. }
  7757. // bounding sphere
  7758. var boundingSphere = source.boundingSphere;
  7759. if ( boundingSphere !== null ) {
  7760. this.boundingSphere = boundingSphere.clone();
  7761. }
  7762. // update flags
  7763. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7764. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7765. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7766. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7767. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7768. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7769. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7770. return this;
  7771. },
  7772. dispose: function () {
  7773. this.dispatchEvent( { type: 'dispose' } );
  7774. }
  7775. } );
  7776. /**
  7777. * @author mrdoob / http://mrdoob.com/
  7778. */
  7779. function BufferAttribute( array, itemSize, normalized ) {
  7780. if ( Array.isArray( array ) ) {
  7781. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7782. }
  7783. this.uuid = _Math.generateUUID();
  7784. this.name = '';
  7785. this.array = array;
  7786. this.itemSize = itemSize;
  7787. this.count = array !== undefined ? array.length / itemSize : 0;
  7788. this.normalized = normalized === true;
  7789. this.dynamic = false;
  7790. this.updateRange = { offset: 0, count: - 1 };
  7791. this.onUploadCallback = function () {};
  7792. this.version = 0;
  7793. }
  7794. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7795. set: function ( value ) {
  7796. if ( value === true ) this.version ++;
  7797. }
  7798. } );
  7799. Object.assign( BufferAttribute.prototype, {
  7800. isBufferAttribute: true,
  7801. setArray: function ( array ) {
  7802. if ( Array.isArray( array ) ) {
  7803. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7804. }
  7805. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7806. this.array = array;
  7807. },
  7808. setDynamic: function ( value ) {
  7809. this.dynamic = value;
  7810. return this;
  7811. },
  7812. copy: function ( source ) {
  7813. this.array = new source.array.constructor( source.array );
  7814. this.itemSize = source.itemSize;
  7815. this.count = source.count;
  7816. this.normalized = source.normalized;
  7817. this.dynamic = source.dynamic;
  7818. return this;
  7819. },
  7820. copyAt: function ( index1, attribute, index2 ) {
  7821. index1 *= this.itemSize;
  7822. index2 *= attribute.itemSize;
  7823. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7824. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7825. }
  7826. return this;
  7827. },
  7828. copyArray: function ( array ) {
  7829. this.array.set( array );
  7830. return this;
  7831. },
  7832. copyColorsArray: function ( colors ) {
  7833. var array = this.array, offset = 0;
  7834. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7835. var color = colors[ i ];
  7836. if ( color === undefined ) {
  7837. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7838. color = new Color();
  7839. }
  7840. array[ offset ++ ] = color.r;
  7841. array[ offset ++ ] = color.g;
  7842. array[ offset ++ ] = color.b;
  7843. }
  7844. return this;
  7845. },
  7846. copyIndicesArray: function ( indices ) {
  7847. var array = this.array, offset = 0;
  7848. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7849. var index = indices[ i ];
  7850. array[ offset ++ ] = index.a;
  7851. array[ offset ++ ] = index.b;
  7852. array[ offset ++ ] = index.c;
  7853. }
  7854. return this;
  7855. },
  7856. copyVector2sArray: function ( vectors ) {
  7857. var array = this.array, offset = 0;
  7858. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7859. var vector = vectors[ i ];
  7860. if ( vector === undefined ) {
  7861. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7862. vector = new Vector2();
  7863. }
  7864. array[ offset ++ ] = vector.x;
  7865. array[ offset ++ ] = vector.y;
  7866. }
  7867. return this;
  7868. },
  7869. copyVector3sArray: function ( vectors ) {
  7870. var array = this.array, offset = 0;
  7871. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7872. var vector = vectors[ i ];
  7873. if ( vector === undefined ) {
  7874. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7875. vector = new Vector3();
  7876. }
  7877. array[ offset ++ ] = vector.x;
  7878. array[ offset ++ ] = vector.y;
  7879. array[ offset ++ ] = vector.z;
  7880. }
  7881. return this;
  7882. },
  7883. copyVector4sArray: function ( vectors ) {
  7884. var array = this.array, offset = 0;
  7885. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7886. var vector = vectors[ i ];
  7887. if ( vector === undefined ) {
  7888. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7889. vector = new Vector4();
  7890. }
  7891. array[ offset ++ ] = vector.x;
  7892. array[ offset ++ ] = vector.y;
  7893. array[ offset ++ ] = vector.z;
  7894. array[ offset ++ ] = vector.w;
  7895. }
  7896. return this;
  7897. },
  7898. set: function ( value, offset ) {
  7899. if ( offset === undefined ) offset = 0;
  7900. this.array.set( value, offset );
  7901. return this;
  7902. },
  7903. getX: function ( index ) {
  7904. return this.array[ index * this.itemSize ];
  7905. },
  7906. setX: function ( index, x ) {
  7907. this.array[ index * this.itemSize ] = x;
  7908. return this;
  7909. },
  7910. getY: function ( index ) {
  7911. return this.array[ index * this.itemSize + 1 ];
  7912. },
  7913. setY: function ( index, y ) {
  7914. this.array[ index * this.itemSize + 1 ] = y;
  7915. return this;
  7916. },
  7917. getZ: function ( index ) {
  7918. return this.array[ index * this.itemSize + 2 ];
  7919. },
  7920. setZ: function ( index, z ) {
  7921. this.array[ index * this.itemSize + 2 ] = z;
  7922. return this;
  7923. },
  7924. getW: function ( index ) {
  7925. return this.array[ index * this.itemSize + 3 ];
  7926. },
  7927. setW: function ( index, w ) {
  7928. this.array[ index * this.itemSize + 3 ] = w;
  7929. return this;
  7930. },
  7931. setXY: function ( index, x, y ) {
  7932. index *= this.itemSize;
  7933. this.array[ index + 0 ] = x;
  7934. this.array[ index + 1 ] = y;
  7935. return this;
  7936. },
  7937. setXYZ: function ( index, x, y, z ) {
  7938. index *= this.itemSize;
  7939. this.array[ index + 0 ] = x;
  7940. this.array[ index + 1 ] = y;
  7941. this.array[ index + 2 ] = z;
  7942. return this;
  7943. },
  7944. setXYZW: function ( index, x, y, z, w ) {
  7945. index *= this.itemSize;
  7946. this.array[ index + 0 ] = x;
  7947. this.array[ index + 1 ] = y;
  7948. this.array[ index + 2 ] = z;
  7949. this.array[ index + 3 ] = w;
  7950. return this;
  7951. },
  7952. onUpload: function ( callback ) {
  7953. this.onUploadCallback = callback;
  7954. return this;
  7955. },
  7956. clone: function () {
  7957. return new this.constructor( this.array, this.itemSize ).copy( this );
  7958. }
  7959. } );
  7960. //
  7961. function Int8BufferAttribute( array, itemSize ) {
  7962. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7963. }
  7964. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7965. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7966. function Uint8BufferAttribute( array, itemSize ) {
  7967. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7968. }
  7969. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7970. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7971. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7972. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7973. }
  7974. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7975. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7976. function Int16BufferAttribute( array, itemSize ) {
  7977. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7978. }
  7979. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7980. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7981. function Uint16BufferAttribute( array, itemSize ) {
  7982. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7983. }
  7984. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7985. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7986. function Int32BufferAttribute( array, itemSize ) {
  7987. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7988. }
  7989. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7990. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7991. function Uint32BufferAttribute( array, itemSize ) {
  7992. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7993. }
  7994. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7995. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7996. function Float32BufferAttribute( array, itemSize ) {
  7997. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7998. }
  7999. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  8000. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  8001. function Float64BufferAttribute( array, itemSize ) {
  8002. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  8003. }
  8004. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  8005. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  8006. /**
  8007. * @author mrdoob / http://mrdoob.com/
  8008. */
  8009. function DirectGeometry() {
  8010. this.indices = [];
  8011. this.vertices = [];
  8012. this.normals = [];
  8013. this.colors = [];
  8014. this.uvs = [];
  8015. this.uvs2 = [];
  8016. this.groups = [];
  8017. this.morphTargets = {};
  8018. this.skinWeights = [];
  8019. this.skinIndices = [];
  8020. // this.lineDistances = [];
  8021. this.boundingBox = null;
  8022. this.boundingSphere = null;
  8023. // update flags
  8024. this.verticesNeedUpdate = false;
  8025. this.normalsNeedUpdate = false;
  8026. this.colorsNeedUpdate = false;
  8027. this.uvsNeedUpdate = false;
  8028. this.groupsNeedUpdate = false;
  8029. }
  8030. Object.assign( DirectGeometry.prototype, {
  8031. computeGroups: function ( geometry ) {
  8032. var group;
  8033. var groups = [];
  8034. var materialIndex = undefined;
  8035. var faces = geometry.faces;
  8036. for ( var i = 0; i < faces.length; i ++ ) {
  8037. var face = faces[ i ];
  8038. // materials
  8039. if ( face.materialIndex !== materialIndex ) {
  8040. materialIndex = face.materialIndex;
  8041. if ( group !== undefined ) {
  8042. group.count = ( i * 3 ) - group.start;
  8043. groups.push( group );
  8044. }
  8045. group = {
  8046. start: i * 3,
  8047. materialIndex: materialIndex
  8048. };
  8049. }
  8050. }
  8051. if ( group !== undefined ) {
  8052. group.count = ( i * 3 ) - group.start;
  8053. groups.push( group );
  8054. }
  8055. this.groups = groups;
  8056. },
  8057. fromGeometry: function ( geometry ) {
  8058. var faces = geometry.faces;
  8059. var vertices = geometry.vertices;
  8060. var faceVertexUvs = geometry.faceVertexUvs;
  8061. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  8062. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  8063. // morphs
  8064. var morphTargets = geometry.morphTargets;
  8065. var morphTargetsLength = morphTargets.length;
  8066. var morphTargetsPosition;
  8067. if ( morphTargetsLength > 0 ) {
  8068. morphTargetsPosition = [];
  8069. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  8070. morphTargetsPosition[ i ] = [];
  8071. }
  8072. this.morphTargets.position = morphTargetsPosition;
  8073. }
  8074. var morphNormals = geometry.morphNormals;
  8075. var morphNormalsLength = morphNormals.length;
  8076. var morphTargetsNormal;
  8077. if ( morphNormalsLength > 0 ) {
  8078. morphTargetsNormal = [];
  8079. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  8080. morphTargetsNormal[ i ] = [];
  8081. }
  8082. this.morphTargets.normal = morphTargetsNormal;
  8083. }
  8084. // skins
  8085. var skinIndices = geometry.skinIndices;
  8086. var skinWeights = geometry.skinWeights;
  8087. var hasSkinIndices = skinIndices.length === vertices.length;
  8088. var hasSkinWeights = skinWeights.length === vertices.length;
  8089. //
  8090. for ( var i = 0; i < faces.length; i ++ ) {
  8091. var face = faces[ i ];
  8092. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  8093. var vertexNormals = face.vertexNormals;
  8094. if ( vertexNormals.length === 3 ) {
  8095. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  8096. } else {
  8097. var normal = face.normal;
  8098. this.normals.push( normal, normal, normal );
  8099. }
  8100. var vertexColors = face.vertexColors;
  8101. if ( vertexColors.length === 3 ) {
  8102. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  8103. } else {
  8104. var color = face.color;
  8105. this.colors.push( color, color, color );
  8106. }
  8107. if ( hasFaceVertexUv === true ) {
  8108. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  8109. if ( vertexUvs !== undefined ) {
  8110. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8111. } else {
  8112. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  8113. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  8114. }
  8115. }
  8116. if ( hasFaceVertexUv2 === true ) {
  8117. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  8118. if ( vertexUvs !== undefined ) {
  8119. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8120. } else {
  8121. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  8122. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  8123. }
  8124. }
  8125. // morphs
  8126. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  8127. var morphTarget = morphTargets[ j ].vertices;
  8128. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  8129. }
  8130. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  8131. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  8132. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  8133. }
  8134. // skins
  8135. if ( hasSkinIndices ) {
  8136. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  8137. }
  8138. if ( hasSkinWeights ) {
  8139. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  8140. }
  8141. }
  8142. this.computeGroups( geometry );
  8143. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8144. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8145. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8146. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8147. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8148. return this;
  8149. }
  8150. } );
  8151. /**
  8152. * @author mrdoob / http://mrdoob.com/
  8153. */
  8154. function arrayMax( array ) {
  8155. if ( array.length === 0 ) return - Infinity;
  8156. var max = array[ 0 ];
  8157. for ( var i = 1, l = array.length; i < l; ++ i ) {
  8158. if ( array[ i ] > max ) max = array[ i ];
  8159. }
  8160. return max;
  8161. }
  8162. /**
  8163. * @author alteredq / http://alteredqualia.com/
  8164. * @author mrdoob / http://mrdoob.com/
  8165. */
  8166. function BufferGeometry() {
  8167. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8168. this.uuid = _Math.generateUUID();
  8169. this.name = '';
  8170. this.type = 'BufferGeometry';
  8171. this.index = null;
  8172. this.attributes = {};
  8173. this.morphAttributes = {};
  8174. this.groups = [];
  8175. this.boundingBox = null;
  8176. this.boundingSphere = null;
  8177. this.drawRange = { start: 0, count: Infinity };
  8178. }
  8179. BufferGeometry.MaxIndex = 65535;
  8180. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8181. isBufferGeometry: true,
  8182. getIndex: function () {
  8183. return this.index;
  8184. },
  8185. setIndex: function ( index ) {
  8186. if ( Array.isArray( index ) ) {
  8187. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8188. } else {
  8189. this.index = index;
  8190. }
  8191. },
  8192. addAttribute: function ( name, attribute ) {
  8193. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  8194. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8195. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8196. return;
  8197. }
  8198. if ( name === 'index' ) {
  8199. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8200. this.setIndex( attribute );
  8201. return;
  8202. }
  8203. this.attributes[ name ] = attribute;
  8204. return this;
  8205. },
  8206. getAttribute: function ( name ) {
  8207. return this.attributes[ name ];
  8208. },
  8209. removeAttribute: function ( name ) {
  8210. delete this.attributes[ name ];
  8211. return this;
  8212. },
  8213. addGroup: function ( start, count, materialIndex ) {
  8214. this.groups.push( {
  8215. start: start,
  8216. count: count,
  8217. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8218. } );
  8219. },
  8220. clearGroups: function () {
  8221. this.groups = [];
  8222. },
  8223. setDrawRange: function ( start, count ) {
  8224. this.drawRange.start = start;
  8225. this.drawRange.count = count;
  8226. },
  8227. applyMatrix: function ( matrix ) {
  8228. var position = this.attributes.position;
  8229. if ( position !== undefined ) {
  8230. matrix.applyToBufferAttribute( position );
  8231. position.needsUpdate = true;
  8232. }
  8233. var normal = this.attributes.normal;
  8234. if ( normal !== undefined ) {
  8235. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8236. normalMatrix.applyToBufferAttribute( normal );
  8237. normal.needsUpdate = true;
  8238. }
  8239. if ( this.boundingBox !== null ) {
  8240. this.computeBoundingBox();
  8241. }
  8242. if ( this.boundingSphere !== null ) {
  8243. this.computeBoundingSphere();
  8244. }
  8245. return this;
  8246. },
  8247. rotateX: function () {
  8248. // rotate geometry around world x-axis
  8249. var m1 = new Matrix4();
  8250. return function rotateX( angle ) {
  8251. m1.makeRotationX( angle );
  8252. this.applyMatrix( m1 );
  8253. return this;
  8254. };
  8255. }(),
  8256. rotateY: function () {
  8257. // rotate geometry around world y-axis
  8258. var m1 = new Matrix4();
  8259. return function rotateY( angle ) {
  8260. m1.makeRotationY( angle );
  8261. this.applyMatrix( m1 );
  8262. return this;
  8263. };
  8264. }(),
  8265. rotateZ: function () {
  8266. // rotate geometry around world z-axis
  8267. var m1 = new Matrix4();
  8268. return function rotateZ( angle ) {
  8269. m1.makeRotationZ( angle );
  8270. this.applyMatrix( m1 );
  8271. return this;
  8272. };
  8273. }(),
  8274. translate: function () {
  8275. // translate geometry
  8276. var m1 = new Matrix4();
  8277. return function translate( x, y, z ) {
  8278. m1.makeTranslation( x, y, z );
  8279. this.applyMatrix( m1 );
  8280. return this;
  8281. };
  8282. }(),
  8283. scale: function () {
  8284. // scale geometry
  8285. var m1 = new Matrix4();
  8286. return function scale( x, y, z ) {
  8287. m1.makeScale( x, y, z );
  8288. this.applyMatrix( m1 );
  8289. return this;
  8290. };
  8291. }(),
  8292. lookAt: function () {
  8293. var obj = new Object3D();
  8294. return function lookAt( vector ) {
  8295. obj.lookAt( vector );
  8296. obj.updateMatrix();
  8297. this.applyMatrix( obj.matrix );
  8298. };
  8299. }(),
  8300. center: function () {
  8301. this.computeBoundingBox();
  8302. var offset = this.boundingBox.getCenter().negate();
  8303. this.translate( offset.x, offset.y, offset.z );
  8304. return offset;
  8305. },
  8306. setFromObject: function ( object ) {
  8307. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8308. var geometry = object.geometry;
  8309. if ( object.isPoints || object.isLine ) {
  8310. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8311. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8312. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8313. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8314. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8315. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8316. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8317. }
  8318. if ( geometry.boundingSphere !== null ) {
  8319. this.boundingSphere = geometry.boundingSphere.clone();
  8320. }
  8321. if ( geometry.boundingBox !== null ) {
  8322. this.boundingBox = geometry.boundingBox.clone();
  8323. }
  8324. } else if ( object.isMesh ) {
  8325. if ( geometry && geometry.isGeometry ) {
  8326. this.fromGeometry( geometry );
  8327. }
  8328. }
  8329. return this;
  8330. },
  8331. updateFromObject: function ( object ) {
  8332. var geometry = object.geometry;
  8333. if ( object.isMesh ) {
  8334. var direct = geometry.__directGeometry;
  8335. if ( geometry.elementsNeedUpdate === true ) {
  8336. direct = undefined;
  8337. geometry.elementsNeedUpdate = false;
  8338. }
  8339. if ( direct === undefined ) {
  8340. return this.fromGeometry( geometry );
  8341. }
  8342. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8343. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8344. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8345. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8346. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8347. geometry.verticesNeedUpdate = false;
  8348. geometry.normalsNeedUpdate = false;
  8349. geometry.colorsNeedUpdate = false;
  8350. geometry.uvsNeedUpdate = false;
  8351. geometry.groupsNeedUpdate = false;
  8352. geometry = direct;
  8353. }
  8354. var attribute;
  8355. if ( geometry.verticesNeedUpdate === true ) {
  8356. attribute = this.attributes.position;
  8357. if ( attribute !== undefined ) {
  8358. attribute.copyVector3sArray( geometry.vertices );
  8359. attribute.needsUpdate = true;
  8360. }
  8361. geometry.verticesNeedUpdate = false;
  8362. }
  8363. if ( geometry.normalsNeedUpdate === true ) {
  8364. attribute = this.attributes.normal;
  8365. if ( attribute !== undefined ) {
  8366. attribute.copyVector3sArray( geometry.normals );
  8367. attribute.needsUpdate = true;
  8368. }
  8369. geometry.normalsNeedUpdate = false;
  8370. }
  8371. if ( geometry.colorsNeedUpdate === true ) {
  8372. attribute = this.attributes.color;
  8373. if ( attribute !== undefined ) {
  8374. attribute.copyColorsArray( geometry.colors );
  8375. attribute.needsUpdate = true;
  8376. }
  8377. geometry.colorsNeedUpdate = false;
  8378. }
  8379. if ( geometry.uvsNeedUpdate ) {
  8380. attribute = this.attributes.uv;
  8381. if ( attribute !== undefined ) {
  8382. attribute.copyVector2sArray( geometry.uvs );
  8383. attribute.needsUpdate = true;
  8384. }
  8385. geometry.uvsNeedUpdate = false;
  8386. }
  8387. if ( geometry.lineDistancesNeedUpdate ) {
  8388. attribute = this.attributes.lineDistance;
  8389. if ( attribute !== undefined ) {
  8390. attribute.copyArray( geometry.lineDistances );
  8391. attribute.needsUpdate = true;
  8392. }
  8393. geometry.lineDistancesNeedUpdate = false;
  8394. }
  8395. if ( geometry.groupsNeedUpdate ) {
  8396. geometry.computeGroups( object.geometry );
  8397. this.groups = geometry.groups;
  8398. geometry.groupsNeedUpdate = false;
  8399. }
  8400. return this;
  8401. },
  8402. fromGeometry: function ( geometry ) {
  8403. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8404. return this.fromDirectGeometry( geometry.__directGeometry );
  8405. },
  8406. fromDirectGeometry: function ( geometry ) {
  8407. var positions = new Float32Array( geometry.vertices.length * 3 );
  8408. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8409. if ( geometry.normals.length > 0 ) {
  8410. var normals = new Float32Array( geometry.normals.length * 3 );
  8411. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8412. }
  8413. if ( geometry.colors.length > 0 ) {
  8414. var colors = new Float32Array( geometry.colors.length * 3 );
  8415. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8416. }
  8417. if ( geometry.uvs.length > 0 ) {
  8418. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8419. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8420. }
  8421. if ( geometry.uvs2.length > 0 ) {
  8422. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8423. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8424. }
  8425. if ( geometry.indices.length > 0 ) {
  8426. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8427. var indices = new TypeArray( geometry.indices.length * 3 );
  8428. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8429. }
  8430. // groups
  8431. this.groups = geometry.groups;
  8432. // morphs
  8433. for ( var name in geometry.morphTargets ) {
  8434. var array = [];
  8435. var morphTargets = geometry.morphTargets[ name ];
  8436. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8437. var morphTarget = morphTargets[ i ];
  8438. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8439. array.push( attribute.copyVector3sArray( morphTarget ) );
  8440. }
  8441. this.morphAttributes[ name ] = array;
  8442. }
  8443. // skinning
  8444. if ( geometry.skinIndices.length > 0 ) {
  8445. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8446. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8447. }
  8448. if ( geometry.skinWeights.length > 0 ) {
  8449. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8450. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8451. }
  8452. //
  8453. if ( geometry.boundingSphere !== null ) {
  8454. this.boundingSphere = geometry.boundingSphere.clone();
  8455. }
  8456. if ( geometry.boundingBox !== null ) {
  8457. this.boundingBox = geometry.boundingBox.clone();
  8458. }
  8459. return this;
  8460. },
  8461. computeBoundingBox: function () {
  8462. if ( this.boundingBox === null ) {
  8463. this.boundingBox = new Box3();
  8464. }
  8465. var position = this.attributes.position;
  8466. if ( position !== undefined ) {
  8467. this.boundingBox.setFromBufferAttribute( position );
  8468. } else {
  8469. this.boundingBox.makeEmpty();
  8470. }
  8471. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8472. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8473. }
  8474. },
  8475. computeBoundingSphere: function () {
  8476. var box = new Box3();
  8477. var vector = new Vector3();
  8478. return function computeBoundingSphere() {
  8479. if ( this.boundingSphere === null ) {
  8480. this.boundingSphere = new Sphere();
  8481. }
  8482. var position = this.attributes.position;
  8483. if ( position ) {
  8484. var center = this.boundingSphere.center;
  8485. box.setFromBufferAttribute( position );
  8486. box.getCenter( center );
  8487. // hoping to find a boundingSphere with a radius smaller than the
  8488. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8489. var maxRadiusSq = 0;
  8490. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8491. vector.x = position.getX( i );
  8492. vector.y = position.getY( i );
  8493. vector.z = position.getZ( i );
  8494. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8495. }
  8496. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8497. if ( isNaN( this.boundingSphere.radius ) ) {
  8498. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8499. }
  8500. }
  8501. };
  8502. }(),
  8503. computeFaceNormals: function () {
  8504. // backwards compatibility
  8505. },
  8506. computeVertexNormals: function () {
  8507. var index = this.index;
  8508. var attributes = this.attributes;
  8509. var groups = this.groups;
  8510. if ( attributes.position ) {
  8511. var positions = attributes.position.array;
  8512. if ( attributes.normal === undefined ) {
  8513. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8514. } else {
  8515. // reset existing normals to zero
  8516. var array = attributes.normal.array;
  8517. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8518. array[ i ] = 0;
  8519. }
  8520. }
  8521. var normals = attributes.normal.array;
  8522. var vA, vB, vC;
  8523. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8524. var cb = new Vector3(), ab = new Vector3();
  8525. // indexed elements
  8526. if ( index ) {
  8527. var indices = index.array;
  8528. if ( groups.length === 0 ) {
  8529. this.addGroup( 0, indices.length );
  8530. }
  8531. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8532. var group = groups[ j ];
  8533. var start = group.start;
  8534. var count = group.count;
  8535. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8536. vA = indices[ i + 0 ] * 3;
  8537. vB = indices[ i + 1 ] * 3;
  8538. vC = indices[ i + 2 ] * 3;
  8539. pA.fromArray( positions, vA );
  8540. pB.fromArray( positions, vB );
  8541. pC.fromArray( positions, vC );
  8542. cb.subVectors( pC, pB );
  8543. ab.subVectors( pA, pB );
  8544. cb.cross( ab );
  8545. normals[ vA ] += cb.x;
  8546. normals[ vA + 1 ] += cb.y;
  8547. normals[ vA + 2 ] += cb.z;
  8548. normals[ vB ] += cb.x;
  8549. normals[ vB + 1 ] += cb.y;
  8550. normals[ vB + 2 ] += cb.z;
  8551. normals[ vC ] += cb.x;
  8552. normals[ vC + 1 ] += cb.y;
  8553. normals[ vC + 2 ] += cb.z;
  8554. }
  8555. }
  8556. } else {
  8557. // non-indexed elements (unconnected triangle soup)
  8558. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8559. pA.fromArray( positions, i );
  8560. pB.fromArray( positions, i + 3 );
  8561. pC.fromArray( positions, i + 6 );
  8562. cb.subVectors( pC, pB );
  8563. ab.subVectors( pA, pB );
  8564. cb.cross( ab );
  8565. normals[ i ] = cb.x;
  8566. normals[ i + 1 ] = cb.y;
  8567. normals[ i + 2 ] = cb.z;
  8568. normals[ i + 3 ] = cb.x;
  8569. normals[ i + 4 ] = cb.y;
  8570. normals[ i + 5 ] = cb.z;
  8571. normals[ i + 6 ] = cb.x;
  8572. normals[ i + 7 ] = cb.y;
  8573. normals[ i + 8 ] = cb.z;
  8574. }
  8575. }
  8576. this.normalizeNormals();
  8577. attributes.normal.needsUpdate = true;
  8578. }
  8579. },
  8580. merge: function ( geometry, offset ) {
  8581. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  8582. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8583. return;
  8584. }
  8585. if ( offset === undefined ) offset = 0;
  8586. var attributes = this.attributes;
  8587. for ( var key in attributes ) {
  8588. if ( geometry.attributes[ key ] === undefined ) continue;
  8589. var attribute1 = attributes[ key ];
  8590. var attributeArray1 = attribute1.array;
  8591. var attribute2 = geometry.attributes[ key ];
  8592. var attributeArray2 = attribute2.array;
  8593. var attributeSize = attribute2.itemSize;
  8594. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8595. attributeArray1[ j ] = attributeArray2[ i ];
  8596. }
  8597. }
  8598. return this;
  8599. },
  8600. normalizeNormals: function () {
  8601. var vector = new Vector3();
  8602. return function normalizeNormals() {
  8603. var normals = this.attributes.normal;
  8604. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8605. vector.x = normals.getX( i );
  8606. vector.y = normals.getY( i );
  8607. vector.z = normals.getZ( i );
  8608. vector.normalize();
  8609. normals.setXYZ( i, vector.x, vector.y, vector.z );
  8610. }
  8611. };
  8612. }(),
  8613. toNonIndexed: function () {
  8614. if ( this.index === null ) {
  8615. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8616. return this;
  8617. }
  8618. var geometry2 = new BufferGeometry();
  8619. var indices = this.index.array;
  8620. var attributes = this.attributes;
  8621. for ( var name in attributes ) {
  8622. var attribute = attributes[ name ];
  8623. var array = attribute.array;
  8624. var itemSize = attribute.itemSize;
  8625. var array2 = new array.constructor( indices.length * itemSize );
  8626. var index = 0, index2 = 0;
  8627. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8628. index = indices[ i ] * itemSize;
  8629. for ( var j = 0; j < itemSize; j ++ ) {
  8630. array2[ index2 ++ ] = array[ index ++ ];
  8631. }
  8632. }
  8633. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8634. }
  8635. return geometry2;
  8636. },
  8637. toJSON: function () {
  8638. var data = {
  8639. metadata: {
  8640. version: 4.5,
  8641. type: 'BufferGeometry',
  8642. generator: 'BufferGeometry.toJSON'
  8643. }
  8644. };
  8645. // standard BufferGeometry serialization
  8646. data.uuid = this.uuid;
  8647. data.type = this.type;
  8648. if ( this.name !== '' ) data.name = this.name;
  8649. if ( this.parameters !== undefined ) {
  8650. var parameters = this.parameters;
  8651. for ( var key in parameters ) {
  8652. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8653. }
  8654. return data;
  8655. }
  8656. data.data = { attributes: {} };
  8657. var index = this.index;
  8658. if ( index !== null ) {
  8659. var array = Array.prototype.slice.call( index.array );
  8660. data.data.index = {
  8661. type: index.array.constructor.name,
  8662. array: array
  8663. };
  8664. }
  8665. var attributes = this.attributes;
  8666. for ( var key in attributes ) {
  8667. var attribute = attributes[ key ];
  8668. var array = Array.prototype.slice.call( attribute.array );
  8669. data.data.attributes[ key ] = {
  8670. itemSize: attribute.itemSize,
  8671. type: attribute.array.constructor.name,
  8672. array: array,
  8673. normalized: attribute.normalized
  8674. };
  8675. }
  8676. var groups = this.groups;
  8677. if ( groups.length > 0 ) {
  8678. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8679. }
  8680. var boundingSphere = this.boundingSphere;
  8681. if ( boundingSphere !== null ) {
  8682. data.data.boundingSphere = {
  8683. center: boundingSphere.center.toArray(),
  8684. radius: boundingSphere.radius
  8685. };
  8686. }
  8687. return data;
  8688. },
  8689. clone: function () {
  8690. /*
  8691. // Handle primitives
  8692. var parameters = this.parameters;
  8693. if ( parameters !== undefined ) {
  8694. var values = [];
  8695. for ( var key in parameters ) {
  8696. values.push( parameters[ key ] );
  8697. }
  8698. var geometry = Object.create( this.constructor.prototype );
  8699. this.constructor.apply( geometry, values );
  8700. return geometry;
  8701. }
  8702. return new this.constructor().copy( this );
  8703. */
  8704. return new BufferGeometry().copy( this );
  8705. },
  8706. copy: function ( source ) {
  8707. var name, i, l;
  8708. // reset
  8709. this.index = null;
  8710. this.attributes = {};
  8711. this.morphAttributes = {};
  8712. this.groups = [];
  8713. this.boundingBox = null;
  8714. this.boundingSphere = null;
  8715. // name
  8716. this.name = source.name;
  8717. // index
  8718. var index = source.index;
  8719. if ( index !== null ) {
  8720. this.setIndex( index.clone() );
  8721. }
  8722. // attributes
  8723. var attributes = source.attributes;
  8724. for ( name in attributes ) {
  8725. var attribute = attributes[ name ];
  8726. this.addAttribute( name, attribute.clone() );
  8727. }
  8728. // morph attributes
  8729. var morphAttributes = source.morphAttributes;
  8730. for ( name in morphAttributes ) {
  8731. var array = [];
  8732. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8733. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8734. array.push( morphAttribute[ i ].clone() );
  8735. }
  8736. this.morphAttributes[ name ] = array;
  8737. }
  8738. // groups
  8739. var groups = source.groups;
  8740. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8741. var group = groups[ i ];
  8742. this.addGroup( group.start, group.count, group.materialIndex );
  8743. }
  8744. // bounding box
  8745. var boundingBox = source.boundingBox;
  8746. if ( boundingBox !== null ) {
  8747. this.boundingBox = boundingBox.clone();
  8748. }
  8749. // bounding sphere
  8750. var boundingSphere = source.boundingSphere;
  8751. if ( boundingSphere !== null ) {
  8752. this.boundingSphere = boundingSphere.clone();
  8753. }
  8754. // draw range
  8755. this.drawRange.start = source.drawRange.start;
  8756. this.drawRange.count = source.drawRange.count;
  8757. return this;
  8758. },
  8759. dispose: function () {
  8760. this.dispatchEvent( { type: 'dispose' } );
  8761. }
  8762. } );
  8763. /**
  8764. * @author mrdoob / http://mrdoob.com/
  8765. * @author Mugen87 / https://github.com/Mugen87
  8766. */
  8767. // BoxGeometry
  8768. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8769. Geometry.call( this );
  8770. this.type = 'BoxGeometry';
  8771. this.parameters = {
  8772. width: width,
  8773. height: height,
  8774. depth: depth,
  8775. widthSegments: widthSegments,
  8776. heightSegments: heightSegments,
  8777. depthSegments: depthSegments
  8778. };
  8779. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  8780. this.mergeVertices();
  8781. }
  8782. BoxGeometry.prototype = Object.create( Geometry.prototype );
  8783. BoxGeometry.prototype.constructor = BoxGeometry;
  8784. // BoxBufferGeometry
  8785. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8786. BufferGeometry.call( this );
  8787. this.type = 'BoxBufferGeometry';
  8788. this.parameters = {
  8789. width: width,
  8790. height: height,
  8791. depth: depth,
  8792. widthSegments: widthSegments,
  8793. heightSegments: heightSegments,
  8794. depthSegments: depthSegments
  8795. };
  8796. var scope = this;
  8797. // segments
  8798. widthSegments = Math.floor( widthSegments ) || 1;
  8799. heightSegments = Math.floor( heightSegments ) || 1;
  8800. depthSegments = Math.floor( depthSegments ) || 1;
  8801. // buffers
  8802. var indices = [];
  8803. var vertices = [];
  8804. var normals = [];
  8805. var uvs = [];
  8806. // helper variables
  8807. var numberOfVertices = 0;
  8808. var groupStart = 0;
  8809. // build each side of the box geometry
  8810. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8811. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8812. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8813. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8814. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8815. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8816. // build geometry
  8817. this.setIndex( indices );
  8818. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8819. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8820. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8821. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8822. var segmentWidth = width / gridX;
  8823. var segmentHeight = height / gridY;
  8824. var widthHalf = width / 2;
  8825. var heightHalf = height / 2;
  8826. var depthHalf = depth / 2;
  8827. var gridX1 = gridX + 1;
  8828. var gridY1 = gridY + 1;
  8829. var vertexCounter = 0;
  8830. var groupCount = 0;
  8831. var ix, iy;
  8832. var vector = new Vector3();
  8833. // generate vertices, normals and uvs
  8834. for ( iy = 0; iy < gridY1; iy ++ ) {
  8835. var y = iy * segmentHeight - heightHalf;
  8836. for ( ix = 0; ix < gridX1; ix ++ ) {
  8837. var x = ix * segmentWidth - widthHalf;
  8838. // set values to correct vector component
  8839. vector[ u ] = x * udir;
  8840. vector[ v ] = y * vdir;
  8841. vector[ w ] = depthHalf;
  8842. // now apply vector to vertex buffer
  8843. vertices.push( vector.x, vector.y, vector.z );
  8844. // set values to correct vector component
  8845. vector[ u ] = 0;
  8846. vector[ v ] = 0;
  8847. vector[ w ] = depth > 0 ? 1 : - 1;
  8848. // now apply vector to normal buffer
  8849. normals.push( vector.x, vector.y, vector.z );
  8850. // uvs
  8851. uvs.push( ix / gridX );
  8852. uvs.push( 1 - ( iy / gridY ) );
  8853. // counters
  8854. vertexCounter += 1;
  8855. }
  8856. }
  8857. // indices
  8858. // 1. you need three indices to draw a single face
  8859. // 2. a single segment consists of two faces
  8860. // 3. so we need to generate six (2*3) indices per segment
  8861. for ( iy = 0; iy < gridY; iy ++ ) {
  8862. for ( ix = 0; ix < gridX; ix ++ ) {
  8863. var a = numberOfVertices + ix + gridX1 * iy;
  8864. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8865. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8866. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8867. // faces
  8868. indices.push( a, b, d );
  8869. indices.push( b, c, d );
  8870. // increase counter
  8871. groupCount += 6;
  8872. }
  8873. }
  8874. // add a group to the geometry. this will ensure multi material support
  8875. scope.addGroup( groupStart, groupCount, materialIndex );
  8876. // calculate new start value for groups
  8877. groupStart += groupCount;
  8878. // update total number of vertices
  8879. numberOfVertices += vertexCounter;
  8880. }
  8881. }
  8882. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8883. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8884. /**
  8885. * @author mrdoob / http://mrdoob.com/
  8886. * @author Mugen87 / https://github.com/Mugen87
  8887. */
  8888. // PlaneGeometry
  8889. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  8890. Geometry.call( this );
  8891. this.type = 'PlaneGeometry';
  8892. this.parameters = {
  8893. width: width,
  8894. height: height,
  8895. widthSegments: widthSegments,
  8896. heightSegments: heightSegments
  8897. };
  8898. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8899. this.mergeVertices();
  8900. }
  8901. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  8902. PlaneGeometry.prototype.constructor = PlaneGeometry;
  8903. // PlaneBufferGeometry
  8904. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8905. BufferGeometry.call( this );
  8906. this.type = 'PlaneBufferGeometry';
  8907. this.parameters = {
  8908. width: width,
  8909. height: height,
  8910. widthSegments: widthSegments,
  8911. heightSegments: heightSegments
  8912. };
  8913. var width_half = width / 2;
  8914. var height_half = height / 2;
  8915. var gridX = Math.floor( widthSegments ) || 1;
  8916. var gridY = Math.floor( heightSegments ) || 1;
  8917. var gridX1 = gridX + 1;
  8918. var gridY1 = gridY + 1;
  8919. var segment_width = width / gridX;
  8920. var segment_height = height / gridY;
  8921. var ix, iy;
  8922. // buffers
  8923. var indices = [];
  8924. var vertices = [];
  8925. var normals = [];
  8926. var uvs = [];
  8927. // generate vertices, normals and uvs
  8928. for ( iy = 0; iy < gridY1; iy ++ ) {
  8929. var y = iy * segment_height - height_half;
  8930. for ( ix = 0; ix < gridX1; ix ++ ) {
  8931. var x = ix * segment_width - width_half;
  8932. vertices.push( x, - y, 0 );
  8933. normals.push( 0, 0, 1 );
  8934. uvs.push( ix / gridX );
  8935. uvs.push( 1 - ( iy / gridY ) );
  8936. }
  8937. }
  8938. // indices
  8939. for ( iy = 0; iy < gridY; iy ++ ) {
  8940. for ( ix = 0; ix < gridX; ix ++ ) {
  8941. var a = ix + gridX1 * iy;
  8942. var b = ix + gridX1 * ( iy + 1 );
  8943. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8944. var d = ( ix + 1 ) + gridX1 * iy;
  8945. // faces
  8946. indices.push( a, b, d );
  8947. indices.push( b, c, d );
  8948. }
  8949. }
  8950. // build geometry
  8951. this.setIndex( indices );
  8952. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8953. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8954. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8955. }
  8956. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8957. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  8958. /**
  8959. * @author mrdoob / http://mrdoob.com/
  8960. * @author alteredq / http://alteredqualia.com/
  8961. *
  8962. * parameters = {
  8963. * color: <hex>,
  8964. * opacity: <float>,
  8965. * map: new THREE.Texture( <Image> ),
  8966. *
  8967. * lightMap: new THREE.Texture( <Image> ),
  8968. * lightMapIntensity: <float>
  8969. *
  8970. * aoMap: new THREE.Texture( <Image> ),
  8971. * aoMapIntensity: <float>
  8972. *
  8973. * specularMap: new THREE.Texture( <Image> ),
  8974. *
  8975. * alphaMap: new THREE.Texture( <Image> ),
  8976. *
  8977. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8978. * combine: THREE.Multiply,
  8979. * reflectivity: <float>,
  8980. * refractionRatio: <float>,
  8981. *
  8982. * depthTest: <bool>,
  8983. * depthWrite: <bool>,
  8984. *
  8985. * wireframe: <boolean>,
  8986. * wireframeLinewidth: <float>,
  8987. *
  8988. * skinning: <bool>,
  8989. * morphTargets: <bool>
  8990. * }
  8991. */
  8992. function MeshBasicMaterial( parameters ) {
  8993. Material.call( this );
  8994. this.type = 'MeshBasicMaterial';
  8995. this.color = new Color( 0xffffff ); // emissive
  8996. this.map = null;
  8997. this.lightMap = null;
  8998. this.lightMapIntensity = 1.0;
  8999. this.aoMap = null;
  9000. this.aoMapIntensity = 1.0;
  9001. this.specularMap = null;
  9002. this.alphaMap = null;
  9003. this.envMap = null;
  9004. this.combine = MultiplyOperation;
  9005. this.reflectivity = 1;
  9006. this.refractionRatio = 0.98;
  9007. this.wireframe = false;
  9008. this.wireframeLinewidth = 1;
  9009. this.wireframeLinecap = 'round';
  9010. this.wireframeLinejoin = 'round';
  9011. this.skinning = false;
  9012. this.morphTargets = false;
  9013. this.lights = false;
  9014. this.setValues( parameters );
  9015. }
  9016. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  9017. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  9018. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  9019. MeshBasicMaterial.prototype.copy = function ( source ) {
  9020. Material.prototype.copy.call( this, source );
  9021. this.color.copy( source.color );
  9022. this.map = source.map;
  9023. this.lightMap = source.lightMap;
  9024. this.lightMapIntensity = source.lightMapIntensity;
  9025. this.aoMap = source.aoMap;
  9026. this.aoMapIntensity = source.aoMapIntensity;
  9027. this.specularMap = source.specularMap;
  9028. this.alphaMap = source.alphaMap;
  9029. this.envMap = source.envMap;
  9030. this.combine = source.combine;
  9031. this.reflectivity = source.reflectivity;
  9032. this.refractionRatio = source.refractionRatio;
  9033. this.wireframe = source.wireframe;
  9034. this.wireframeLinewidth = source.wireframeLinewidth;
  9035. this.wireframeLinecap = source.wireframeLinecap;
  9036. this.wireframeLinejoin = source.wireframeLinejoin;
  9037. this.skinning = source.skinning;
  9038. this.morphTargets = source.morphTargets;
  9039. return this;
  9040. };
  9041. /**
  9042. * @author bhouston / http://clara.io
  9043. */
  9044. function Ray( origin, direction ) {
  9045. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  9046. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  9047. }
  9048. Object.assign( Ray.prototype, {
  9049. set: function ( origin, direction ) {
  9050. this.origin.copy( origin );
  9051. this.direction.copy( direction );
  9052. return this;
  9053. },
  9054. clone: function () {
  9055. return new this.constructor().copy( this );
  9056. },
  9057. copy: function ( ray ) {
  9058. this.origin.copy( ray.origin );
  9059. this.direction.copy( ray.direction );
  9060. return this;
  9061. },
  9062. at: function ( t, optionalTarget ) {
  9063. var result = optionalTarget || new Vector3();
  9064. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9065. },
  9066. lookAt: function ( v ) {
  9067. this.direction.copy( v ).sub( this.origin ).normalize();
  9068. return this;
  9069. },
  9070. recast: function () {
  9071. var v1 = new Vector3();
  9072. return function recast( t ) {
  9073. this.origin.copy( this.at( t, v1 ) );
  9074. return this;
  9075. };
  9076. }(),
  9077. closestPointToPoint: function ( point, optionalTarget ) {
  9078. var result = optionalTarget || new Vector3();
  9079. result.subVectors( point, this.origin );
  9080. var directionDistance = result.dot( this.direction );
  9081. if ( directionDistance < 0 ) {
  9082. return result.copy( this.origin );
  9083. }
  9084. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9085. },
  9086. distanceToPoint: function ( point ) {
  9087. return Math.sqrt( this.distanceSqToPoint( point ) );
  9088. },
  9089. distanceSqToPoint: function () {
  9090. var v1 = new Vector3();
  9091. return function distanceSqToPoint( point ) {
  9092. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  9093. // point behind the ray
  9094. if ( directionDistance < 0 ) {
  9095. return this.origin.distanceToSquared( point );
  9096. }
  9097. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9098. return v1.distanceToSquared( point );
  9099. };
  9100. }(),
  9101. distanceSqToSegment: function () {
  9102. var segCenter = new Vector3();
  9103. var segDir = new Vector3();
  9104. var diff = new Vector3();
  9105. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9106. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9107. // It returns the min distance between the ray and the segment
  9108. // defined by v0 and v1
  9109. // It can also set two optional targets :
  9110. // - The closest point on the ray
  9111. // - The closest point on the segment
  9112. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9113. segDir.copy( v1 ).sub( v0 ).normalize();
  9114. diff.copy( this.origin ).sub( segCenter );
  9115. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9116. var a01 = - this.direction.dot( segDir );
  9117. var b0 = diff.dot( this.direction );
  9118. var b1 = - diff.dot( segDir );
  9119. var c = diff.lengthSq();
  9120. var det = Math.abs( 1 - a01 * a01 );
  9121. var s0, s1, sqrDist, extDet;
  9122. if ( det > 0 ) {
  9123. // The ray and segment are not parallel.
  9124. s0 = a01 * b1 - b0;
  9125. s1 = a01 * b0 - b1;
  9126. extDet = segExtent * det;
  9127. if ( s0 >= 0 ) {
  9128. if ( s1 >= - extDet ) {
  9129. if ( s1 <= extDet ) {
  9130. // region 0
  9131. // Minimum at interior points of ray and segment.
  9132. var invDet = 1 / det;
  9133. s0 *= invDet;
  9134. s1 *= invDet;
  9135. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9136. } else {
  9137. // region 1
  9138. s1 = segExtent;
  9139. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9140. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9141. }
  9142. } else {
  9143. // region 5
  9144. s1 = - segExtent;
  9145. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9146. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9147. }
  9148. } else {
  9149. if ( s1 <= - extDet ) {
  9150. // region 4
  9151. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9152. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9153. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9154. } else if ( s1 <= extDet ) {
  9155. // region 3
  9156. s0 = 0;
  9157. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9158. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9159. } else {
  9160. // region 2
  9161. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9162. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9163. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9164. }
  9165. }
  9166. } else {
  9167. // Ray and segment are parallel.
  9168. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9169. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9170. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9171. }
  9172. if ( optionalPointOnRay ) {
  9173. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9174. }
  9175. if ( optionalPointOnSegment ) {
  9176. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  9177. }
  9178. return sqrDist;
  9179. };
  9180. }(),
  9181. intersectSphere: function () {
  9182. var v1 = new Vector3();
  9183. return function intersectSphere( sphere, optionalTarget ) {
  9184. v1.subVectors( sphere.center, this.origin );
  9185. var tca = v1.dot( this.direction );
  9186. var d2 = v1.dot( v1 ) - tca * tca;
  9187. var radius2 = sphere.radius * sphere.radius;
  9188. if ( d2 > radius2 ) return null;
  9189. var thc = Math.sqrt( radius2 - d2 );
  9190. // t0 = first intersect point - entrance on front of sphere
  9191. var t0 = tca - thc;
  9192. // t1 = second intersect point - exit point on back of sphere
  9193. var t1 = tca + thc;
  9194. // test to see if both t0 and t1 are behind the ray - if so, return null
  9195. if ( t0 < 0 && t1 < 0 ) return null;
  9196. // test to see if t0 is behind the ray:
  9197. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9198. // in order to always return an intersect point that is in front of the ray.
  9199. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  9200. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9201. return this.at( t0, optionalTarget );
  9202. };
  9203. }(),
  9204. intersectsSphere: function ( sphere ) {
  9205. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  9206. },
  9207. distanceToPlane: function ( plane ) {
  9208. var denominator = plane.normal.dot( this.direction );
  9209. if ( denominator === 0 ) {
  9210. // line is coplanar, return origin
  9211. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9212. return 0;
  9213. }
  9214. // Null is preferable to undefined since undefined means.... it is undefined
  9215. return null;
  9216. }
  9217. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9218. // Return if the ray never intersects the plane
  9219. return t >= 0 ? t : null;
  9220. },
  9221. intersectPlane: function ( plane, optionalTarget ) {
  9222. var t = this.distanceToPlane( plane );
  9223. if ( t === null ) {
  9224. return null;
  9225. }
  9226. return this.at( t, optionalTarget );
  9227. },
  9228. intersectsPlane: function ( plane ) {
  9229. // check if the ray lies on the plane first
  9230. var distToPoint = plane.distanceToPoint( this.origin );
  9231. if ( distToPoint === 0 ) {
  9232. return true;
  9233. }
  9234. var denominator = plane.normal.dot( this.direction );
  9235. if ( denominator * distToPoint < 0 ) {
  9236. return true;
  9237. }
  9238. // ray origin is behind the plane (and is pointing behind it)
  9239. return false;
  9240. },
  9241. intersectBox: function ( box, optionalTarget ) {
  9242. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9243. var invdirx = 1 / this.direction.x,
  9244. invdiry = 1 / this.direction.y,
  9245. invdirz = 1 / this.direction.z;
  9246. var origin = this.origin;
  9247. if ( invdirx >= 0 ) {
  9248. tmin = ( box.min.x - origin.x ) * invdirx;
  9249. tmax = ( box.max.x - origin.x ) * invdirx;
  9250. } else {
  9251. tmin = ( box.max.x - origin.x ) * invdirx;
  9252. tmax = ( box.min.x - origin.x ) * invdirx;
  9253. }
  9254. if ( invdiry >= 0 ) {
  9255. tymin = ( box.min.y - origin.y ) * invdiry;
  9256. tymax = ( box.max.y - origin.y ) * invdiry;
  9257. } else {
  9258. tymin = ( box.max.y - origin.y ) * invdiry;
  9259. tymax = ( box.min.y - origin.y ) * invdiry;
  9260. }
  9261. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  9262. // These lines also handle the case where tmin or tmax is NaN
  9263. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9264. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  9265. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  9266. if ( invdirz >= 0 ) {
  9267. tzmin = ( box.min.z - origin.z ) * invdirz;
  9268. tzmax = ( box.max.z - origin.z ) * invdirz;
  9269. } else {
  9270. tzmin = ( box.max.z - origin.z ) * invdirz;
  9271. tzmax = ( box.min.z - origin.z ) * invdirz;
  9272. }
  9273. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  9274. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  9275. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  9276. //return point closest to the ray (positive side)
  9277. if ( tmax < 0 ) return null;
  9278. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  9279. },
  9280. intersectsBox: ( function () {
  9281. var v = new Vector3();
  9282. return function intersectsBox( box ) {
  9283. return this.intersectBox( box, v ) !== null;
  9284. };
  9285. } )(),
  9286. intersectTriangle: function () {
  9287. // Compute the offset origin, edges, and normal.
  9288. var diff = new Vector3();
  9289. var edge1 = new Vector3();
  9290. var edge2 = new Vector3();
  9291. var normal = new Vector3();
  9292. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  9293. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9294. edge1.subVectors( b, a );
  9295. edge2.subVectors( c, a );
  9296. normal.crossVectors( edge1, edge2 );
  9297. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9298. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9299. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9300. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9301. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9302. var DdN = this.direction.dot( normal );
  9303. var sign;
  9304. if ( DdN > 0 ) {
  9305. if ( backfaceCulling ) return null;
  9306. sign = 1;
  9307. } else if ( DdN < 0 ) {
  9308. sign = - 1;
  9309. DdN = - DdN;
  9310. } else {
  9311. return null;
  9312. }
  9313. diff.subVectors( this.origin, a );
  9314. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  9315. // b1 < 0, no intersection
  9316. if ( DdQxE2 < 0 ) {
  9317. return null;
  9318. }
  9319. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  9320. // b2 < 0, no intersection
  9321. if ( DdE1xQ < 0 ) {
  9322. return null;
  9323. }
  9324. // b1+b2 > 1, no intersection
  9325. if ( DdQxE2 + DdE1xQ > DdN ) {
  9326. return null;
  9327. }
  9328. // Line intersects triangle, check if ray does.
  9329. var QdN = - sign * diff.dot( normal );
  9330. // t < 0, no intersection
  9331. if ( QdN < 0 ) {
  9332. return null;
  9333. }
  9334. // Ray intersects triangle.
  9335. return this.at( QdN / DdN, optionalTarget );
  9336. };
  9337. }(),
  9338. applyMatrix4: function ( matrix4 ) {
  9339. this.origin.applyMatrix4( matrix4 );
  9340. this.direction.transformDirection( matrix4 );
  9341. return this;
  9342. },
  9343. equals: function ( ray ) {
  9344. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9345. }
  9346. } );
  9347. /**
  9348. * @author bhouston / http://clara.io
  9349. */
  9350. function Line3( start, end ) {
  9351. this.start = ( start !== undefined ) ? start : new Vector3();
  9352. this.end = ( end !== undefined ) ? end : new Vector3();
  9353. }
  9354. Object.assign( Line3.prototype, {
  9355. set: function ( start, end ) {
  9356. this.start.copy( start );
  9357. this.end.copy( end );
  9358. return this;
  9359. },
  9360. clone: function () {
  9361. return new this.constructor().copy( this );
  9362. },
  9363. copy: function ( line ) {
  9364. this.start.copy( line.start );
  9365. this.end.copy( line.end );
  9366. return this;
  9367. },
  9368. getCenter: function ( optionalTarget ) {
  9369. var result = optionalTarget || new Vector3();
  9370. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9371. },
  9372. delta: function ( optionalTarget ) {
  9373. var result = optionalTarget || new Vector3();
  9374. return result.subVectors( this.end, this.start );
  9375. },
  9376. distanceSq: function () {
  9377. return this.start.distanceToSquared( this.end );
  9378. },
  9379. distance: function () {
  9380. return this.start.distanceTo( this.end );
  9381. },
  9382. at: function ( t, optionalTarget ) {
  9383. var result = optionalTarget || new Vector3();
  9384. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9385. },
  9386. closestPointToPointParameter: function () {
  9387. var startP = new Vector3();
  9388. var startEnd = new Vector3();
  9389. return function closestPointToPointParameter( point, clampToLine ) {
  9390. startP.subVectors( point, this.start );
  9391. startEnd.subVectors( this.end, this.start );
  9392. var startEnd2 = startEnd.dot( startEnd );
  9393. var startEnd_startP = startEnd.dot( startP );
  9394. var t = startEnd_startP / startEnd2;
  9395. if ( clampToLine ) {
  9396. t = _Math.clamp( t, 0, 1 );
  9397. }
  9398. return t;
  9399. };
  9400. }(),
  9401. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9402. var t = this.closestPointToPointParameter( point, clampToLine );
  9403. var result = optionalTarget || new Vector3();
  9404. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9405. },
  9406. applyMatrix4: function ( matrix ) {
  9407. this.start.applyMatrix4( matrix );
  9408. this.end.applyMatrix4( matrix );
  9409. return this;
  9410. },
  9411. equals: function ( line ) {
  9412. return line.start.equals( this.start ) && line.end.equals( this.end );
  9413. }
  9414. } );
  9415. /**
  9416. * @author bhouston / http://clara.io
  9417. * @author mrdoob / http://mrdoob.com/
  9418. */
  9419. function Triangle( a, b, c ) {
  9420. this.a = ( a !== undefined ) ? a : new Vector3();
  9421. this.b = ( b !== undefined ) ? b : new Vector3();
  9422. this.c = ( c !== undefined ) ? c : new Vector3();
  9423. }
  9424. Object.assign( Triangle, {
  9425. normal: function () {
  9426. var v0 = new Vector3();
  9427. return function normal( a, b, c, optionalTarget ) {
  9428. var result = optionalTarget || new Vector3();
  9429. result.subVectors( c, b );
  9430. v0.subVectors( a, b );
  9431. result.cross( v0 );
  9432. var resultLengthSq = result.lengthSq();
  9433. if ( resultLengthSq > 0 ) {
  9434. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  9435. }
  9436. return result.set( 0, 0, 0 );
  9437. };
  9438. }(),
  9439. // static/instance method to calculate barycentric coordinates
  9440. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9441. barycoordFromPoint: function () {
  9442. var v0 = new Vector3();
  9443. var v1 = new Vector3();
  9444. var v2 = new Vector3();
  9445. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  9446. v0.subVectors( c, a );
  9447. v1.subVectors( b, a );
  9448. v2.subVectors( point, a );
  9449. var dot00 = v0.dot( v0 );
  9450. var dot01 = v0.dot( v1 );
  9451. var dot02 = v0.dot( v2 );
  9452. var dot11 = v1.dot( v1 );
  9453. var dot12 = v1.dot( v2 );
  9454. var denom = ( dot00 * dot11 - dot01 * dot01 );
  9455. var result = optionalTarget || new Vector3();
  9456. // collinear or singular triangle
  9457. if ( denom === 0 ) {
  9458. // arbitrary location outside of triangle?
  9459. // not sure if this is the best idea, maybe should be returning undefined
  9460. return result.set( - 2, - 1, - 1 );
  9461. }
  9462. var invDenom = 1 / denom;
  9463. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9464. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9465. // barycentric coordinates must always sum to 1
  9466. return result.set( 1 - u - v, v, u );
  9467. };
  9468. }(),
  9469. containsPoint: function () {
  9470. var v1 = new Vector3();
  9471. return function containsPoint( point, a, b, c ) {
  9472. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  9473. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  9474. };
  9475. }()
  9476. } );
  9477. Object.assign( Triangle.prototype, {
  9478. set: function ( a, b, c ) {
  9479. this.a.copy( a );
  9480. this.b.copy( b );
  9481. this.c.copy( c );
  9482. return this;
  9483. },
  9484. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  9485. this.a.copy( points[ i0 ] );
  9486. this.b.copy( points[ i1 ] );
  9487. this.c.copy( points[ i2 ] );
  9488. return this;
  9489. },
  9490. clone: function () {
  9491. return new this.constructor().copy( this );
  9492. },
  9493. copy: function ( triangle ) {
  9494. this.a.copy( triangle.a );
  9495. this.b.copy( triangle.b );
  9496. this.c.copy( triangle.c );
  9497. return this;
  9498. },
  9499. area: function () {
  9500. var v0 = new Vector3();
  9501. var v1 = new Vector3();
  9502. return function area() {
  9503. v0.subVectors( this.c, this.b );
  9504. v1.subVectors( this.a, this.b );
  9505. return v0.cross( v1 ).length() * 0.5;
  9506. };
  9507. }(),
  9508. midpoint: function ( optionalTarget ) {
  9509. var result = optionalTarget || new Vector3();
  9510. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9511. },
  9512. normal: function ( optionalTarget ) {
  9513. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  9514. },
  9515. plane: function ( optionalTarget ) {
  9516. var result = optionalTarget || new Plane();
  9517. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  9518. },
  9519. barycoordFromPoint: function ( point, optionalTarget ) {
  9520. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  9521. },
  9522. containsPoint: function ( point ) {
  9523. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9524. },
  9525. closestPointToPoint: function () {
  9526. var plane = new Plane();
  9527. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  9528. var projectedPoint = new Vector3();
  9529. var closestPoint = new Vector3();
  9530. return function closestPointToPoint( point, optionalTarget ) {
  9531. var result = optionalTarget || new Vector3();
  9532. var minDistance = Infinity;
  9533. // project the point onto the plane of the triangle
  9534. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  9535. plane.projectPoint( point, projectedPoint );
  9536. // check if the projection lies within the triangle
  9537. if( this.containsPoint( projectedPoint ) === true ) {
  9538. // if so, this is the closest point
  9539. result.copy( projectedPoint );
  9540. } else {
  9541. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  9542. edgeList[ 0 ].set( this.a, this.b );
  9543. edgeList[ 1 ].set( this.b, this.c );
  9544. edgeList[ 2 ].set( this.c, this.a );
  9545. for( var i = 0; i < edgeList.length; i ++ ) {
  9546. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  9547. var distance = projectedPoint.distanceToSquared( closestPoint );
  9548. if( distance < minDistance ) {
  9549. minDistance = distance;
  9550. result.copy( closestPoint );
  9551. }
  9552. }
  9553. }
  9554. return result;
  9555. };
  9556. }(),
  9557. equals: function ( triangle ) {
  9558. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9559. }
  9560. } );
  9561. /**
  9562. * @author mrdoob / http://mrdoob.com/
  9563. * @author alteredq / http://alteredqualia.com/
  9564. * @author mikael emtinger / http://gomo.se/
  9565. * @author jonobr1 / http://jonobr1.com/
  9566. */
  9567. function Mesh( geometry, material ) {
  9568. Object3D.call( this );
  9569. this.type = 'Mesh';
  9570. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9571. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9572. this.drawMode = TrianglesDrawMode;
  9573. this.updateMorphTargets();
  9574. }
  9575. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9576. constructor: Mesh,
  9577. isMesh: true,
  9578. setDrawMode: function ( value ) {
  9579. this.drawMode = value;
  9580. },
  9581. copy: function ( source ) {
  9582. Object3D.prototype.copy.call( this, source );
  9583. this.drawMode = source.drawMode;
  9584. return this;
  9585. },
  9586. updateMorphTargets: function () {
  9587. var geometry = this.geometry;
  9588. var m, ml, name;
  9589. if ( geometry.isBufferGeometry ) {
  9590. var morphAttributes = geometry.morphAttributes;
  9591. var keys = Object.keys( morphAttributes );
  9592. if ( keys.length > 0 ) {
  9593. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  9594. if ( morphAttribute !== undefined ) {
  9595. this.morphTargetInfluences = [];
  9596. this.morphTargetDictionary = {};
  9597. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9598. name = morphAttribute[ m ].name || String( m );
  9599. this.morphTargetInfluences.push( 0 );
  9600. this.morphTargetDictionary[ name ] = m;
  9601. }
  9602. }
  9603. }
  9604. } else {
  9605. var morphTargets = geometry.morphTargets;
  9606. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  9607. this.morphTargetInfluences = [];
  9608. this.morphTargetDictionary = {};
  9609. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  9610. name = morphTargets[ m ].name || String( m );
  9611. this.morphTargetInfluences.push( 0 );
  9612. this.morphTargetDictionary[ name ] = m;
  9613. }
  9614. }
  9615. }
  9616. },
  9617. raycast: ( function () {
  9618. var inverseMatrix = new Matrix4();
  9619. var ray = new Ray();
  9620. var sphere = new Sphere();
  9621. var vA = new Vector3();
  9622. var vB = new Vector3();
  9623. var vC = new Vector3();
  9624. var tempA = new Vector3();
  9625. var tempB = new Vector3();
  9626. var tempC = new Vector3();
  9627. var uvA = new Vector2();
  9628. var uvB = new Vector2();
  9629. var uvC = new Vector2();
  9630. var barycoord = new Vector3();
  9631. var intersectionPoint = new Vector3();
  9632. var intersectionPointWorld = new Vector3();
  9633. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  9634. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  9635. uv1.multiplyScalar( barycoord.x );
  9636. uv2.multiplyScalar( barycoord.y );
  9637. uv3.multiplyScalar( barycoord.z );
  9638. uv1.add( uv2 ).add( uv3 );
  9639. return uv1.clone();
  9640. }
  9641. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  9642. var intersect;
  9643. if ( material.side === BackSide ) {
  9644. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  9645. } else {
  9646. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  9647. }
  9648. if ( intersect === null ) return null;
  9649. intersectionPointWorld.copy( point );
  9650. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  9651. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  9652. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  9653. return {
  9654. distance: distance,
  9655. point: intersectionPointWorld.clone(),
  9656. object: object
  9657. };
  9658. }
  9659. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  9660. vA.fromBufferAttribute( position, a );
  9661. vB.fromBufferAttribute( position, b );
  9662. vC.fromBufferAttribute( position, c );
  9663. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  9664. if ( intersection ) {
  9665. if ( uv ) {
  9666. uvA.fromBufferAttribute( uv, a );
  9667. uvB.fromBufferAttribute( uv, b );
  9668. uvC.fromBufferAttribute( uv, c );
  9669. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  9670. }
  9671. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  9672. intersection.faceIndex = a;
  9673. }
  9674. return intersection;
  9675. }
  9676. return function raycast( raycaster, intersects ) {
  9677. var geometry = this.geometry;
  9678. var material = this.material;
  9679. var matrixWorld = this.matrixWorld;
  9680. if ( material === undefined ) return;
  9681. // Checking boundingSphere distance to ray
  9682. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9683. sphere.copy( geometry.boundingSphere );
  9684. sphere.applyMatrix4( matrixWorld );
  9685. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9686. //
  9687. inverseMatrix.getInverse( matrixWorld );
  9688. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9689. // Check boundingBox before continuing
  9690. if ( geometry.boundingBox !== null ) {
  9691. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9692. }
  9693. var intersection;
  9694. if ( geometry.isBufferGeometry ) {
  9695. var a, b, c;
  9696. var index = geometry.index;
  9697. var position = geometry.attributes.position;
  9698. var uv = geometry.attributes.uv;
  9699. var i, l;
  9700. if ( index !== null ) {
  9701. // indexed buffer geometry
  9702. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9703. a = index.getX( i );
  9704. b = index.getX( i + 1 );
  9705. c = index.getX( i + 2 );
  9706. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9707. if ( intersection ) {
  9708. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9709. intersects.push( intersection );
  9710. }
  9711. }
  9712. } else {
  9713. // non-indexed buffer geometry
  9714. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9715. a = i;
  9716. b = i + 1;
  9717. c = i + 2;
  9718. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9719. if ( intersection ) {
  9720. intersection.index = a; // triangle number in positions buffer semantics
  9721. intersects.push( intersection );
  9722. }
  9723. }
  9724. }
  9725. } else if ( geometry.isGeometry ) {
  9726. var fvA, fvB, fvC;
  9727. var isMultiMaterial = Array.isArray( material );
  9728. var vertices = geometry.vertices;
  9729. var faces = geometry.faces;
  9730. var uvs;
  9731. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9732. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9733. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9734. var face = faces[ f ];
  9735. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9736. if ( faceMaterial === undefined ) continue;
  9737. fvA = vertices[ face.a ];
  9738. fvB = vertices[ face.b ];
  9739. fvC = vertices[ face.c ];
  9740. if ( faceMaterial.morphTargets === true ) {
  9741. var morphTargets = geometry.morphTargets;
  9742. var morphInfluences = this.morphTargetInfluences;
  9743. vA.set( 0, 0, 0 );
  9744. vB.set( 0, 0, 0 );
  9745. vC.set( 0, 0, 0 );
  9746. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9747. var influence = morphInfluences[ t ];
  9748. if ( influence === 0 ) continue;
  9749. var targets = morphTargets[ t ].vertices;
  9750. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9751. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9752. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9753. }
  9754. vA.add( fvA );
  9755. vB.add( fvB );
  9756. vC.add( fvC );
  9757. fvA = vA;
  9758. fvB = vB;
  9759. fvC = vC;
  9760. }
  9761. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9762. if ( intersection ) {
  9763. if ( uvs && uvs[ f ] ) {
  9764. var uvs_f = uvs[ f ];
  9765. uvA.copy( uvs_f[ 0 ] );
  9766. uvB.copy( uvs_f[ 1 ] );
  9767. uvC.copy( uvs_f[ 2 ] );
  9768. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9769. }
  9770. intersection.face = face;
  9771. intersection.faceIndex = f;
  9772. intersects.push( intersection );
  9773. }
  9774. }
  9775. }
  9776. };
  9777. }() ),
  9778. clone: function () {
  9779. return new this.constructor( this.geometry, this.material ).copy( this );
  9780. }
  9781. } );
  9782. /**
  9783. * @author mrdoob / http://mrdoob.com/
  9784. */
  9785. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  9786. var clearColor = new Color( 0x000000 );
  9787. var clearAlpha = 0;
  9788. var planeCamera, planeMesh;
  9789. var boxMesh;
  9790. function render( renderList, scene, camera, forceClear ) {
  9791. var background = scene.background;
  9792. if ( background === null ) {
  9793. setClear( clearColor, clearAlpha );
  9794. } else if ( background && background.isColor ) {
  9795. setClear( background, 1 );
  9796. forceClear = true;
  9797. }
  9798. if ( renderer.autoClear || forceClear ) {
  9799. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9800. }
  9801. if ( background && background.isCubeTexture ) {
  9802. if ( boxMesh === undefined ) {
  9803. boxMesh = new Mesh(
  9804. new BoxBufferGeometry( 1, 1, 1 ),
  9805. new ShaderMaterial( {
  9806. uniforms: ShaderLib.cube.uniforms,
  9807. vertexShader: ShaderLib.cube.vertexShader,
  9808. fragmentShader: ShaderLib.cube.fragmentShader,
  9809. side: BackSide,
  9810. depthTest: true,
  9811. depthWrite: false,
  9812. polygonOffset: true,
  9813. fog: false
  9814. } )
  9815. );
  9816. boxMesh.geometry.removeAttribute( 'normal' );
  9817. boxMesh.geometry.removeAttribute( 'uv' );
  9818. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9819. var scale = camera.far;
  9820. this.matrixWorld.makeScale( scale, scale, scale );
  9821. this.matrixWorld.copyPosition( camera.matrixWorld );
  9822. this.material.polygonOffsetUnits = scale * 10;
  9823. };
  9824. geometries.update( boxMesh.geometry );
  9825. }
  9826. boxMesh.material.uniforms.tCube.value = background;
  9827. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  9828. } else if ( background && background.isTexture ) {
  9829. if ( planeCamera === undefined ) {
  9830. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9831. planeMesh = new Mesh(
  9832. new PlaneBufferGeometry( 2, 2 ),
  9833. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  9834. );
  9835. geometries.update( planeMesh.geometry );
  9836. }
  9837. planeMesh.material.map = background;
  9838. // TODO Push this to renderList
  9839. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  9840. }
  9841. }
  9842. function setClear( color, alpha ) {
  9843. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9844. }
  9845. return {
  9846. getClearColor: function () {
  9847. return clearColor;
  9848. },
  9849. setClearColor: function ( color, alpha ) {
  9850. clearColor.set( color );
  9851. clearAlpha = alpha !== undefined ? alpha : 1;
  9852. setClear( clearColor, clearAlpha );
  9853. },
  9854. getClearAlpha: function () {
  9855. return clearAlpha;
  9856. },
  9857. setClearAlpha: function ( alpha ) {
  9858. clearAlpha = alpha;
  9859. setClear( clearColor, clearAlpha );
  9860. },
  9861. render: render
  9862. };
  9863. }
  9864. /**
  9865. * @author mrdoob / http://mrdoob.com/
  9866. */
  9867. function painterSortStable( a, b ) {
  9868. if ( a.renderOrder !== b.renderOrder ) {
  9869. return a.renderOrder - b.renderOrder;
  9870. } else if ( a.program && b.program && a.program !== b.program ) {
  9871. return a.program.id - b.program.id;
  9872. } else if ( a.material.id !== b.material.id ) {
  9873. return a.material.id - b.material.id;
  9874. } else if ( a.z !== b.z ) {
  9875. return a.z - b.z;
  9876. } else {
  9877. return a.id - b.id;
  9878. }
  9879. }
  9880. function reversePainterSortStable( a, b ) {
  9881. if ( a.renderOrder !== b.renderOrder ) {
  9882. return a.renderOrder - b.renderOrder;
  9883. } if ( a.z !== b.z ) {
  9884. return b.z - a.z;
  9885. } else {
  9886. return a.id - b.id;
  9887. }
  9888. }
  9889. function WebGLRenderList() {
  9890. var renderItems = [];
  9891. var renderItemsIndex = 0;
  9892. var opaque = [];
  9893. var transparent = [];
  9894. function init() {
  9895. renderItemsIndex = 0;
  9896. opaque.length = 0;
  9897. transparent.length = 0;
  9898. }
  9899. function push( object, geometry, material, z, group ) {
  9900. var renderItem = renderItems[ renderItemsIndex ];
  9901. if ( renderItem === undefined ) {
  9902. renderItem = {
  9903. id: object.id,
  9904. object: object,
  9905. geometry: geometry,
  9906. material: material,
  9907. program: material.program,
  9908. renderOrder: object.renderOrder,
  9909. z: z,
  9910. group: group
  9911. };
  9912. renderItems[ renderItemsIndex ] = renderItem;
  9913. } else {
  9914. renderItem.id = object.id;
  9915. renderItem.object = object;
  9916. renderItem.geometry = geometry;
  9917. renderItem.material = material;
  9918. renderItem.program = material.program;
  9919. renderItem.renderOrder = object.renderOrder;
  9920. renderItem.z = z;
  9921. renderItem.group = group;
  9922. }
  9923. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  9924. renderItemsIndex ++;
  9925. }
  9926. function sort() {
  9927. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  9928. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  9929. }
  9930. return {
  9931. opaque: opaque,
  9932. transparent: transparent,
  9933. init: init,
  9934. push: push,
  9935. sort: sort
  9936. };
  9937. }
  9938. function WebGLRenderLists() {
  9939. var lists = {};
  9940. function get( scene, camera ) {
  9941. var hash = scene.id + ',' + camera.id;
  9942. var list = lists[ hash ];
  9943. if ( list === undefined ) {
  9944. // console.log( 'THREE.WebGLRenderLists:', hash );
  9945. list = new WebGLRenderList();
  9946. lists[ hash ] = list;
  9947. }
  9948. return list;
  9949. }
  9950. function dispose() {
  9951. lists = {};
  9952. }
  9953. return {
  9954. get: get,
  9955. dispose: dispose
  9956. };
  9957. }
  9958. /**
  9959. * @author mrdoob / http://mrdoob.com/
  9960. */
  9961. function absNumericalSort( a, b ) {
  9962. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9963. }
  9964. function WebGLMorphtargets( gl ) {
  9965. var influencesList = {};
  9966. var morphInfluences = new Float32Array( 8 );
  9967. function update( object, geometry, material, program ) {
  9968. var objectInfluences = object.morphTargetInfluences;
  9969. var length = objectInfluences.length;
  9970. var influences = influencesList[ geometry.id ];
  9971. if ( influences === undefined ) {
  9972. // initialise list
  9973. influences = [];
  9974. for ( var i = 0; i < length; i ++ ) {
  9975. influences[ i ] = [ i, 0 ];
  9976. }
  9977. influencesList[ geometry.id ] = influences;
  9978. }
  9979. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9980. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9981. // Remove current morphAttributes
  9982. for ( var i = 0; i < length; i ++ ) {
  9983. var influence = influences[ i ];
  9984. if ( influence[ 1 ] !== 0 ) {
  9985. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  9986. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  9987. }
  9988. }
  9989. // Collect influences
  9990. for ( var i = 0; i < length; i ++ ) {
  9991. var influence = influences[ i ];
  9992. influence[ 0 ] = i;
  9993. influence[ 1 ] = objectInfluences[ i ];
  9994. }
  9995. influences.sort( absNumericalSort );
  9996. // Add morphAttributes
  9997. for ( var i = 0; i < 8; i ++ ) {
  9998. var influence = influences[ i ];
  9999. if ( influence ) {
  10000. var index = influence[ 0 ];
  10001. var value = influence[ 1 ];
  10002. if ( value ) {
  10003. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10004. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10005. morphInfluences[ i ] = value;
  10006. continue;
  10007. }
  10008. }
  10009. morphInfluences[ i ] = 0;
  10010. }
  10011. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10012. }
  10013. return {
  10014. update: update
  10015. }
  10016. }
  10017. /**
  10018. * @author mrdoob / http://mrdoob.com/
  10019. */
  10020. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  10021. var mode;
  10022. function setMode( value ) {
  10023. mode = value;
  10024. }
  10025. var type, bytesPerElement;
  10026. function setIndex( value ) {
  10027. type = value.type;
  10028. bytesPerElement = value.bytesPerElement;
  10029. }
  10030. function render( start, count ) {
  10031. gl.drawElements( mode, count, type, start * bytesPerElement );
  10032. infoRender.calls ++;
  10033. infoRender.vertices += count;
  10034. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  10035. else if ( mode === gl.POINTS ) infoRender.points += count;
  10036. }
  10037. function renderInstances( geometry, start, count ) {
  10038. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10039. if ( extension === null ) {
  10040. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10041. return;
  10042. }
  10043. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  10044. infoRender.calls ++;
  10045. infoRender.vertices += count * geometry.maxInstancedCount;
  10046. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  10047. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  10048. }
  10049. //
  10050. this.setMode = setMode;
  10051. this.setIndex = setIndex;
  10052. this.render = render;
  10053. this.renderInstances = renderInstances;
  10054. }
  10055. /**
  10056. * @author mrdoob / http://mrdoob.com/
  10057. */
  10058. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  10059. var mode;
  10060. function setMode( value ) {
  10061. mode = value;
  10062. }
  10063. function render( start, count ) {
  10064. gl.drawArrays( mode, start, count );
  10065. infoRender.calls ++;
  10066. infoRender.vertices += count;
  10067. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  10068. else if ( mode === gl.POINTS ) infoRender.points += count;
  10069. }
  10070. function renderInstances( geometry, start, count ) {
  10071. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10072. if ( extension === null ) {
  10073. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10074. return;
  10075. }
  10076. var position = geometry.attributes.position;
  10077. if ( position.isInterleavedBufferAttribute ) {
  10078. count = position.data.count;
  10079. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10080. } else {
  10081. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  10082. }
  10083. infoRender.calls ++;
  10084. infoRender.vertices += count * geometry.maxInstancedCount;
  10085. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  10086. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  10087. }
  10088. //
  10089. this.setMode = setMode;
  10090. this.render = render;
  10091. this.renderInstances = renderInstances;
  10092. }
  10093. /**
  10094. * @author mrdoob / http://mrdoob.com/
  10095. */
  10096. function WebGLGeometries( gl, attributes, infoMemory ) {
  10097. var geometries = {};
  10098. var wireframeAttributes = {};
  10099. function onGeometryDispose( event ) {
  10100. var geometry = event.target;
  10101. var buffergeometry = geometries[ geometry.id ];
  10102. if ( buffergeometry.index !== null ) {
  10103. attributes.remove( buffergeometry.index );
  10104. }
  10105. for ( var name in buffergeometry.attributes ) {
  10106. attributes.remove( buffergeometry.attributes[ name ] );
  10107. }
  10108. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10109. delete geometries[ geometry.id ];
  10110. // TODO Remove duplicate code
  10111. var attribute = wireframeAttributes[ geometry.id ];
  10112. if ( attribute ) {
  10113. attributes.remove( attribute );
  10114. delete wireframeAttributes[ geometry.id ];
  10115. }
  10116. attribute = wireframeAttributes[ buffergeometry.id ];
  10117. if ( attribute ) {
  10118. attributes.remove( attribute );
  10119. delete wireframeAttributes[ buffergeometry.id ];
  10120. }
  10121. //
  10122. infoMemory.geometries --;
  10123. }
  10124. function get( object, geometry ) {
  10125. var buffergeometry = geometries[ geometry.id ];
  10126. if ( buffergeometry ) return buffergeometry;
  10127. geometry.addEventListener( 'dispose', onGeometryDispose );
  10128. if ( geometry.isBufferGeometry ) {
  10129. buffergeometry = geometry;
  10130. } else if ( geometry.isGeometry ) {
  10131. if ( geometry._bufferGeometry === undefined ) {
  10132. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10133. }
  10134. buffergeometry = geometry._bufferGeometry;
  10135. }
  10136. geometries[ geometry.id ] = buffergeometry;
  10137. infoMemory.geometries ++;
  10138. return buffergeometry;
  10139. }
  10140. function update( geometry ) {
  10141. var index = geometry.index;
  10142. var geometryAttributes = geometry.attributes;
  10143. if ( index !== null ) {
  10144. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  10145. }
  10146. for ( var name in geometryAttributes ) {
  10147. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10148. }
  10149. // morph targets
  10150. var morphAttributes = geometry.morphAttributes;
  10151. for ( var name in morphAttributes ) {
  10152. var array = morphAttributes[ name ];
  10153. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10154. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10155. }
  10156. }
  10157. }
  10158. function getWireframeAttribute( geometry ) {
  10159. var attribute = wireframeAttributes[ geometry.id ];
  10160. if ( attribute ) return attribute;
  10161. var indices = [];
  10162. var geometryIndex = geometry.index;
  10163. var geometryAttributes = geometry.attributes;
  10164. // console.time( 'wireframe' );
  10165. if ( geometryIndex !== null ) {
  10166. var array = geometryIndex.array;
  10167. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10168. var a = array[ i + 0 ];
  10169. var b = array[ i + 1 ];
  10170. var c = array[ i + 2 ];
  10171. indices.push( a, b, b, c, c, a );
  10172. }
  10173. } else {
  10174. var array = geometryAttributes.position.array;
  10175. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10176. var a = i + 0;
  10177. var b = i + 1;
  10178. var c = i + 2;
  10179. indices.push( a, b, b, c, c, a );
  10180. }
  10181. }
  10182. // console.timeEnd( 'wireframe' );
  10183. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10184. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10185. wireframeAttributes[ geometry.id ] = attribute;
  10186. return attribute;
  10187. }
  10188. return {
  10189. get: get,
  10190. update: update,
  10191. getWireframeAttribute: getWireframeAttribute
  10192. };
  10193. }
  10194. /**
  10195. * @author mrdoob / http://mrdoob.com/
  10196. */
  10197. function UniformsCache() {
  10198. var lights = {};
  10199. return {
  10200. get: function ( light ) {
  10201. if ( lights[ light.id ] !== undefined ) {
  10202. return lights[ light.id ];
  10203. }
  10204. var uniforms;
  10205. switch ( light.type ) {
  10206. case 'DirectionalLight':
  10207. uniforms = {
  10208. direction: new Vector3(),
  10209. color: new Color(),
  10210. shadow: false,
  10211. shadowBias: 0,
  10212. shadowRadius: 1,
  10213. shadowMapSize: new Vector2()
  10214. };
  10215. break;
  10216. case 'SpotLight':
  10217. uniforms = {
  10218. position: new Vector3(),
  10219. direction: new Vector3(),
  10220. color: new Color(),
  10221. distance: 0,
  10222. coneCos: 0,
  10223. penumbraCos: 0,
  10224. decay: 0,
  10225. shadow: false,
  10226. shadowBias: 0,
  10227. shadowRadius: 1,
  10228. shadowMapSize: new Vector2()
  10229. };
  10230. break;
  10231. case 'PointLight':
  10232. uniforms = {
  10233. position: new Vector3(),
  10234. color: new Color(),
  10235. distance: 0,
  10236. decay: 0,
  10237. shadow: false,
  10238. shadowBias: 0,
  10239. shadowRadius: 1,
  10240. shadowMapSize: new Vector2(),
  10241. shadowCameraNear: 1,
  10242. shadowCameraFar: 1000
  10243. };
  10244. break;
  10245. case 'HemisphereLight':
  10246. uniforms = {
  10247. direction: new Vector3(),
  10248. skyColor: new Color(),
  10249. groundColor: new Color()
  10250. };
  10251. break;
  10252. case 'RectAreaLight':
  10253. uniforms = {
  10254. color: new Color(),
  10255. position: new Vector3(),
  10256. halfWidth: new Vector3(),
  10257. halfHeight: new Vector3()
  10258. // TODO (abelnation): set RectAreaLight shadow uniforms
  10259. };
  10260. break;
  10261. }
  10262. lights[ light.id ] = uniforms;
  10263. return uniforms;
  10264. }
  10265. };
  10266. }
  10267. function WebGLLights() {
  10268. var cache = new UniformsCache();
  10269. var state = {
  10270. hash: '',
  10271. ambient: [ 0, 0, 0 ],
  10272. directional: [],
  10273. directionalShadowMap: [],
  10274. directionalShadowMatrix: [],
  10275. spot: [],
  10276. spotShadowMap: [],
  10277. spotShadowMatrix: [],
  10278. rectArea: [],
  10279. point: [],
  10280. pointShadowMap: [],
  10281. pointShadowMatrix: [],
  10282. hemi: []
  10283. };
  10284. var vector3 = new Vector3();
  10285. var matrix4 = new Matrix4();
  10286. var matrix42 = new Matrix4();
  10287. function setup( lights, shadows, camera ) {
  10288. var r = 0, g = 0, b = 0;
  10289. var directionalLength = 0;
  10290. var pointLength = 0;
  10291. var spotLength = 0;
  10292. var rectAreaLength = 0;
  10293. var hemiLength = 0;
  10294. var viewMatrix = camera.matrixWorldInverse;
  10295. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  10296. var light = lights[ i ];
  10297. var color = light.color;
  10298. var intensity = light.intensity;
  10299. var distance = light.distance;
  10300. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10301. if ( light.isAmbientLight ) {
  10302. r += color.r * intensity;
  10303. g += color.g * intensity;
  10304. b += color.b * intensity;
  10305. } else if ( light.isDirectionalLight ) {
  10306. var uniforms = cache.get( light );
  10307. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10308. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10309. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10310. uniforms.direction.sub( vector3 );
  10311. uniforms.direction.transformDirection( viewMatrix );
  10312. uniforms.shadow = light.castShadow;
  10313. if ( light.castShadow ) {
  10314. var shadow = light.shadow;
  10315. uniforms.shadowBias = shadow.bias;
  10316. uniforms.shadowRadius = shadow.radius;
  10317. uniforms.shadowMapSize = shadow.mapSize;
  10318. }
  10319. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10320. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10321. state.directional[ directionalLength ] = uniforms;
  10322. directionalLength ++;
  10323. } else if ( light.isSpotLight ) {
  10324. var uniforms = cache.get( light );
  10325. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10326. uniforms.position.applyMatrix4( viewMatrix );
  10327. uniforms.color.copy( color ).multiplyScalar( intensity );
  10328. uniforms.distance = distance;
  10329. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10330. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10331. uniforms.direction.sub( vector3 );
  10332. uniforms.direction.transformDirection( viewMatrix );
  10333. uniforms.coneCos = Math.cos( light.angle );
  10334. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10335. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10336. uniforms.shadow = light.castShadow;
  10337. if ( light.castShadow ) {
  10338. var shadow = light.shadow;
  10339. uniforms.shadowBias = shadow.bias;
  10340. uniforms.shadowRadius = shadow.radius;
  10341. uniforms.shadowMapSize = shadow.mapSize;
  10342. }
  10343. state.spotShadowMap[ spotLength ] = shadowMap;
  10344. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10345. state.spot[ spotLength ] = uniforms;
  10346. spotLength ++;
  10347. } else if ( light.isRectAreaLight ) {
  10348. var uniforms = cache.get( light );
  10349. // (a) intensity controls irradiance of entire light
  10350. uniforms.color
  10351. .copy( color )
  10352. .multiplyScalar( intensity / ( light.width * light.height ) );
  10353. // (b) intensity controls the radiance per light area
  10354. // uniforms.color.copy( color ).multiplyScalar( intensity );
  10355. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10356. uniforms.position.applyMatrix4( viewMatrix );
  10357. // extract local rotation of light to derive width/height half vectors
  10358. matrix42.identity();
  10359. matrix4.copy( light.matrixWorld );
  10360. matrix4.premultiply( viewMatrix );
  10361. matrix42.extractRotation( matrix4 );
  10362. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10363. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10364. uniforms.halfWidth.applyMatrix4( matrix42 );
  10365. uniforms.halfHeight.applyMatrix4( matrix42 );
  10366. // TODO (abelnation): RectAreaLight distance?
  10367. // uniforms.distance = distance;
  10368. state.rectArea[ rectAreaLength ] = uniforms;
  10369. rectAreaLength ++;
  10370. } else if ( light.isPointLight ) {
  10371. var uniforms = cache.get( light );
  10372. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10373. uniforms.position.applyMatrix4( viewMatrix );
  10374. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10375. uniforms.distance = light.distance;
  10376. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10377. uniforms.shadow = light.castShadow;
  10378. if ( light.castShadow ) {
  10379. var shadow = light.shadow;
  10380. uniforms.shadowBias = shadow.bias;
  10381. uniforms.shadowRadius = shadow.radius;
  10382. uniforms.shadowMapSize = shadow.mapSize;
  10383. uniforms.shadowCameraNear = shadow.camera.near;
  10384. uniforms.shadowCameraFar = shadow.camera.far;
  10385. }
  10386. state.pointShadowMap[ pointLength ] = shadowMap;
  10387. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10388. state.point[ pointLength ] = uniforms;
  10389. pointLength ++;
  10390. } else if ( light.isHemisphereLight ) {
  10391. var uniforms = cache.get( light );
  10392. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10393. uniforms.direction.transformDirection( viewMatrix );
  10394. uniforms.direction.normalize();
  10395. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10396. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10397. state.hemi[ hemiLength ] = uniforms;
  10398. hemiLength ++;
  10399. }
  10400. }
  10401. state.ambient[ 0 ] = r;
  10402. state.ambient[ 1 ] = g;
  10403. state.ambient[ 2 ] = b;
  10404. state.directional.length = directionalLength;
  10405. state.spot.length = spotLength;
  10406. state.rectArea.length = rectAreaLength;
  10407. state.point.length = pointLength;
  10408. state.hemi.length = hemiLength;
  10409. // TODO (sam-g-steel) why aren't we using join
  10410. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  10411. }
  10412. return {
  10413. setup: setup,
  10414. state: state
  10415. }
  10416. }
  10417. /**
  10418. * @author mrdoob / http://mrdoob.com/
  10419. */
  10420. function WebGLObjects( geometries, infoRender ) {
  10421. var updateList = {};
  10422. function update( object ) {
  10423. var frame = infoRender.frame;
  10424. var geometry = object.geometry;
  10425. var buffergeometry = geometries.get( object, geometry );
  10426. // Update once per frame
  10427. if ( updateList[ buffergeometry.id ] !== frame ) {
  10428. if ( geometry.isGeometry ) {
  10429. buffergeometry.updateFromObject( object );
  10430. }
  10431. geometries.update( buffergeometry );
  10432. updateList[ buffergeometry.id ] = frame;
  10433. }
  10434. return buffergeometry;
  10435. }
  10436. function clear() {
  10437. updateList = {};
  10438. }
  10439. return {
  10440. update: update,
  10441. clear: clear
  10442. };
  10443. }
  10444. /**
  10445. * @author mrdoob / http://mrdoob.com/
  10446. */
  10447. function addLineNumbers( string ) {
  10448. var lines = string.split( '\n' );
  10449. for ( var i = 0; i < lines.length; i ++ ) {
  10450. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10451. }
  10452. return lines.join( '\n' );
  10453. }
  10454. function WebGLShader( gl, type, string ) {
  10455. var shader = gl.createShader( type );
  10456. gl.shaderSource( shader, string );
  10457. gl.compileShader( shader );
  10458. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10459. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10460. }
  10461. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10462. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10463. }
  10464. // --enable-privileged-webgl-extension
  10465. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10466. return shader;
  10467. }
  10468. /**
  10469. * @author mrdoob / http://mrdoob.com/
  10470. */
  10471. var programIdCount = 0;
  10472. function getEncodingComponents( encoding ) {
  10473. switch ( encoding ) {
  10474. case LinearEncoding:
  10475. return [ 'Linear','( value )' ];
  10476. case sRGBEncoding:
  10477. return [ 'sRGB','( value )' ];
  10478. case RGBEEncoding:
  10479. return [ 'RGBE','( value )' ];
  10480. case RGBM7Encoding:
  10481. return [ 'RGBM','( value, 7.0 )' ];
  10482. case RGBM16Encoding:
  10483. return [ 'RGBM','( value, 16.0 )' ];
  10484. case RGBDEncoding:
  10485. return [ 'RGBD','( value, 256.0 )' ];
  10486. case GammaEncoding:
  10487. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10488. default:
  10489. throw new Error( 'unsupported encoding: ' + encoding );
  10490. }
  10491. }
  10492. function getTexelDecodingFunction( functionName, encoding ) {
  10493. var components = getEncodingComponents( encoding );
  10494. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10495. }
  10496. function getTexelEncodingFunction( functionName, encoding ) {
  10497. var components = getEncodingComponents( encoding );
  10498. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10499. }
  10500. function getToneMappingFunction( functionName, toneMapping ) {
  10501. var toneMappingName;
  10502. switch ( toneMapping ) {
  10503. case LinearToneMapping:
  10504. toneMappingName = "Linear";
  10505. break;
  10506. case ReinhardToneMapping:
  10507. toneMappingName = "Reinhard";
  10508. break;
  10509. case Uncharted2ToneMapping:
  10510. toneMappingName = "Uncharted2";
  10511. break;
  10512. case CineonToneMapping:
  10513. toneMappingName = "OptimizedCineon";
  10514. break;
  10515. default:
  10516. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10517. }
  10518. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10519. }
  10520. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10521. extensions = extensions || {};
  10522. var chunks = [
  10523. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10524. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10525. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10526. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10527. ];
  10528. return chunks.filter( filterEmptyLine ).join( '\n' );
  10529. }
  10530. function generateDefines( defines ) {
  10531. var chunks = [];
  10532. for ( var name in defines ) {
  10533. var value = defines[ name ];
  10534. if ( value === false ) continue;
  10535. chunks.push( '#define ' + name + ' ' + value );
  10536. }
  10537. return chunks.join( '\n' );
  10538. }
  10539. function fetchAttributeLocations( gl, program, identifiers ) {
  10540. var attributes = {};
  10541. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10542. for ( var i = 0; i < n; i ++ ) {
  10543. var info = gl.getActiveAttrib( program, i );
  10544. var name = info.name;
  10545. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10546. attributes[ name ] = gl.getAttribLocation( program, name );
  10547. }
  10548. return attributes;
  10549. }
  10550. function filterEmptyLine( string ) {
  10551. return string !== '';
  10552. }
  10553. function replaceLightNums( string, parameters ) {
  10554. return string
  10555. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10556. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10557. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10558. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10559. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10560. }
  10561. function parseIncludes( string ) {
  10562. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10563. function replace( match, include ) {
  10564. var replace = ShaderChunk[ include ];
  10565. if ( replace === undefined ) {
  10566. throw new Error( 'Can not resolve #include <' + include + '>' );
  10567. }
  10568. return parseIncludes( replace );
  10569. }
  10570. return string.replace( pattern, replace );
  10571. }
  10572. function unrollLoops( string ) {
  10573. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10574. function replace( match, start, end, snippet ) {
  10575. var unroll = '';
  10576. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10577. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10578. }
  10579. return unroll;
  10580. }
  10581. return string.replace( pattern, replace );
  10582. }
  10583. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  10584. var gl = renderer.context;
  10585. var defines = material.defines;
  10586. var vertexShader = shader.vertexShader;
  10587. var fragmentShader = shader.fragmentShader;
  10588. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10589. if ( parameters.shadowMapType === PCFShadowMap ) {
  10590. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10591. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10592. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10593. }
  10594. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10595. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10596. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10597. if ( parameters.envMap ) {
  10598. switch ( material.envMap.mapping ) {
  10599. case CubeReflectionMapping:
  10600. case CubeRefractionMapping:
  10601. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10602. break;
  10603. case CubeUVReflectionMapping:
  10604. case CubeUVRefractionMapping:
  10605. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10606. break;
  10607. case EquirectangularReflectionMapping:
  10608. case EquirectangularRefractionMapping:
  10609. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10610. break;
  10611. case SphericalReflectionMapping:
  10612. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10613. break;
  10614. }
  10615. switch ( material.envMap.mapping ) {
  10616. case CubeRefractionMapping:
  10617. case EquirectangularRefractionMapping:
  10618. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10619. break;
  10620. }
  10621. switch ( material.combine ) {
  10622. case MultiplyOperation:
  10623. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10624. break;
  10625. case MixOperation:
  10626. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10627. break;
  10628. case AddOperation:
  10629. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10630. break;
  10631. }
  10632. }
  10633. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10634. // console.log( 'building new program ' );
  10635. //
  10636. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  10637. var customDefines = generateDefines( defines );
  10638. //
  10639. var program = gl.createProgram();
  10640. var prefixVertex, prefixFragment;
  10641. if ( material.isRawShaderMaterial ) {
  10642. prefixVertex = [
  10643. customDefines,
  10644. '\n'
  10645. ].filter( filterEmptyLine ).join( '\n' );
  10646. prefixFragment = [
  10647. customExtensions,
  10648. customDefines,
  10649. '\n'
  10650. ].filter( filterEmptyLine ).join( '\n' );
  10651. } else {
  10652. prefixVertex = [
  10653. 'precision ' + parameters.precision + ' float;',
  10654. 'precision ' + parameters.precision + ' int;',
  10655. '#define SHADER_NAME ' + shader.name,
  10656. customDefines,
  10657. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10658. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10659. '#define MAX_BONES ' + parameters.maxBones,
  10660. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10661. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10662. parameters.map ? '#define USE_MAP' : '',
  10663. parameters.envMap ? '#define USE_ENVMAP' : '',
  10664. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10665. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10666. parameters.aoMap ? '#define USE_AOMAP' : '',
  10667. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10668. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10669. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10670. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10671. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10672. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10673. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10674. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10675. parameters.vertexColors ? '#define USE_COLOR' : '',
  10676. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10677. parameters.skinning ? '#define USE_SKINNING' : '',
  10678. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10679. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10680. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10681. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10682. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10683. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10684. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10685. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10686. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10687. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10688. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10689. 'uniform mat4 modelMatrix;',
  10690. 'uniform mat4 modelViewMatrix;',
  10691. 'uniform mat4 projectionMatrix;',
  10692. 'uniform mat4 viewMatrix;',
  10693. 'uniform mat3 normalMatrix;',
  10694. 'uniform vec3 cameraPosition;',
  10695. 'attribute vec3 position;',
  10696. 'attribute vec3 normal;',
  10697. 'attribute vec2 uv;',
  10698. '#ifdef USE_COLOR',
  10699. ' attribute vec3 color;',
  10700. '#endif',
  10701. '#ifdef USE_MORPHTARGETS',
  10702. ' attribute vec3 morphTarget0;',
  10703. ' attribute vec3 morphTarget1;',
  10704. ' attribute vec3 morphTarget2;',
  10705. ' attribute vec3 morphTarget3;',
  10706. ' #ifdef USE_MORPHNORMALS',
  10707. ' attribute vec3 morphNormal0;',
  10708. ' attribute vec3 morphNormal1;',
  10709. ' attribute vec3 morphNormal2;',
  10710. ' attribute vec3 morphNormal3;',
  10711. ' #else',
  10712. ' attribute vec3 morphTarget4;',
  10713. ' attribute vec3 morphTarget5;',
  10714. ' attribute vec3 morphTarget6;',
  10715. ' attribute vec3 morphTarget7;',
  10716. ' #endif',
  10717. '#endif',
  10718. '#ifdef USE_SKINNING',
  10719. ' attribute vec4 skinIndex;',
  10720. ' attribute vec4 skinWeight;',
  10721. '#endif',
  10722. '\n'
  10723. ].filter( filterEmptyLine ).join( '\n' );
  10724. prefixFragment = [
  10725. customExtensions,
  10726. 'precision ' + parameters.precision + ' float;',
  10727. 'precision ' + parameters.precision + ' int;',
  10728. '#define SHADER_NAME ' + shader.name,
  10729. customDefines,
  10730. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10731. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10732. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10733. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10734. parameters.map ? '#define USE_MAP' : '',
  10735. parameters.envMap ? '#define USE_ENVMAP' : '',
  10736. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10737. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10738. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10739. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10740. parameters.aoMap ? '#define USE_AOMAP' : '',
  10741. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10742. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10743. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10744. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10745. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10746. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10747. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10748. parameters.vertexColors ? '#define USE_COLOR' : '',
  10749. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10750. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10751. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10752. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10753. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10754. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10755. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10756. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10757. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10758. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10759. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10760. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10761. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10762. 'uniform mat4 viewMatrix;',
  10763. 'uniform vec3 cameraPosition;',
  10764. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10765. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10766. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10767. parameters.dithering ? '#define DITHERING' : '',
  10768. ( 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
  10769. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10770. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10771. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10772. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10773. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10774. '\n'
  10775. ].filter( filterEmptyLine ).join( '\n' );
  10776. }
  10777. vertexShader = parseIncludes( vertexShader );
  10778. vertexShader = replaceLightNums( vertexShader, parameters );
  10779. fragmentShader = parseIncludes( fragmentShader );
  10780. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10781. if ( ! material.isShaderMaterial ) {
  10782. vertexShader = unrollLoops( vertexShader );
  10783. fragmentShader = unrollLoops( fragmentShader );
  10784. }
  10785. var vertexGlsl = prefixVertex + vertexShader;
  10786. var fragmentGlsl = prefixFragment + fragmentShader;
  10787. // console.log( '*VERTEX*', vertexGlsl );
  10788. // console.log( '*FRAGMENT*', fragmentGlsl );
  10789. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10790. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10791. gl.attachShader( program, glVertexShader );
  10792. gl.attachShader( program, glFragmentShader );
  10793. // Force a particular attribute to index 0.
  10794. if ( material.index0AttributeName !== undefined ) {
  10795. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10796. } else if ( parameters.morphTargets === true ) {
  10797. // programs with morphTargets displace position out of attribute 0
  10798. gl.bindAttribLocation( program, 0, 'position' );
  10799. }
  10800. gl.linkProgram( program );
  10801. var programLog = gl.getProgramInfoLog( program );
  10802. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10803. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10804. var runnable = true;
  10805. var haveDiagnostics = true;
  10806. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10807. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10808. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10809. runnable = false;
  10810. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10811. } else if ( programLog !== '' ) {
  10812. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10813. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10814. haveDiagnostics = false;
  10815. }
  10816. if ( haveDiagnostics ) {
  10817. this.diagnostics = {
  10818. runnable: runnable,
  10819. material: material,
  10820. programLog: programLog,
  10821. vertexShader: {
  10822. log: vertexLog,
  10823. prefix: prefixVertex
  10824. },
  10825. fragmentShader: {
  10826. log: fragmentLog,
  10827. prefix: prefixFragment
  10828. }
  10829. };
  10830. }
  10831. // clean up
  10832. gl.deleteShader( glVertexShader );
  10833. gl.deleteShader( glFragmentShader );
  10834. // set up caching for uniform locations
  10835. var cachedUniforms;
  10836. this.getUniforms = function () {
  10837. if ( cachedUniforms === undefined ) {
  10838. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  10839. }
  10840. return cachedUniforms;
  10841. };
  10842. // set up caching for attribute locations
  10843. var cachedAttributes;
  10844. this.getAttributes = function () {
  10845. if ( cachedAttributes === undefined ) {
  10846. cachedAttributes = fetchAttributeLocations( gl, program );
  10847. }
  10848. return cachedAttributes;
  10849. };
  10850. // free resource
  10851. this.destroy = function() {
  10852. gl.deleteProgram( program );
  10853. this.program = undefined;
  10854. };
  10855. // DEPRECATED
  10856. Object.defineProperties( this, {
  10857. uniforms: {
  10858. get: function() {
  10859. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10860. return this.getUniforms();
  10861. }
  10862. },
  10863. attributes: {
  10864. get: function() {
  10865. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10866. return this.getAttributes();
  10867. }
  10868. }
  10869. } );
  10870. //
  10871. this.id = programIdCount ++;
  10872. this.code = code;
  10873. this.usedTimes = 1;
  10874. this.program = program;
  10875. this.vertexShader = glVertexShader;
  10876. this.fragmentShader = glFragmentShader;
  10877. return this;
  10878. }
  10879. /**
  10880. * @author mrdoob / http://mrdoob.com/
  10881. */
  10882. function WebGLPrograms( renderer, extensions, capabilities ) {
  10883. var programs = [];
  10884. var shaderIDs = {
  10885. MeshDepthMaterial: 'depth',
  10886. MeshDistanceMaterial: 'distanceRGBA',
  10887. MeshNormalMaterial: 'normal',
  10888. MeshBasicMaterial: 'basic',
  10889. MeshLambertMaterial: 'lambert',
  10890. MeshPhongMaterial: 'phong',
  10891. MeshToonMaterial: 'phong',
  10892. MeshStandardMaterial: 'physical',
  10893. MeshPhysicalMaterial: 'physical',
  10894. LineBasicMaterial: 'basic',
  10895. LineDashedMaterial: 'dashed',
  10896. PointsMaterial: 'points',
  10897. ShadowMaterial: 'shadow'
  10898. };
  10899. var parameterNames = [
  10900. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10901. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10902. "roughnessMap", "metalnessMap", "gradientMap",
  10903. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10904. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10905. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10906. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10907. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10908. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10909. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10910. ];
  10911. function allocateBones( object ) {
  10912. var skeleton = object.skeleton;
  10913. var bones = skeleton.bones;
  10914. if ( capabilities.floatVertexTextures ) {
  10915. return 1024;
  10916. } else {
  10917. // default for when object is not specified
  10918. // ( for example when prebuilding shader to be used with multiple objects )
  10919. //
  10920. // - leave some extra space for other uniforms
  10921. // - limit here is ANGLE's 254 max uniform vectors
  10922. // (up to 54 should be safe)
  10923. var nVertexUniforms = capabilities.maxVertexUniforms;
  10924. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10925. var maxBones = Math.min( nVertexMatrices, bones.length );
  10926. if ( maxBones < bones.length ) {
  10927. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10928. return 0;
  10929. }
  10930. return maxBones;
  10931. }
  10932. }
  10933. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10934. var encoding;
  10935. if ( ! map ) {
  10936. encoding = LinearEncoding;
  10937. } else if ( map.isTexture ) {
  10938. encoding = map.encoding;
  10939. } else if ( map.isWebGLRenderTarget ) {
  10940. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10941. encoding = map.texture.encoding;
  10942. }
  10943. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10944. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10945. encoding = GammaEncoding;
  10946. }
  10947. return encoding;
  10948. }
  10949. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  10950. var shaderID = shaderIDs[ material.type ];
  10951. // heuristics to create shader parameters according to lights in the scene
  10952. // (not to blow over maxLights budget)
  10953. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10954. var precision = capabilities.precision;
  10955. if ( material.precision !== null ) {
  10956. precision = capabilities.getMaxPrecision( material.precision );
  10957. if ( precision !== material.precision ) {
  10958. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10959. }
  10960. }
  10961. var currentRenderTarget = renderer.getRenderTarget();
  10962. var parameters = {
  10963. shaderID: shaderID,
  10964. precision: precision,
  10965. supportsVertexTextures: capabilities.vertexTextures,
  10966. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10967. map: !! material.map,
  10968. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10969. envMap: !! material.envMap,
  10970. envMapMode: material.envMap && material.envMap.mapping,
  10971. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10972. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10973. lightMap: !! material.lightMap,
  10974. aoMap: !! material.aoMap,
  10975. emissiveMap: !! material.emissiveMap,
  10976. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10977. bumpMap: !! material.bumpMap,
  10978. normalMap: !! material.normalMap,
  10979. displacementMap: !! material.displacementMap,
  10980. roughnessMap: !! material.roughnessMap,
  10981. metalnessMap: !! material.metalnessMap,
  10982. specularMap: !! material.specularMap,
  10983. alphaMap: !! material.alphaMap,
  10984. gradientMap: !! material.gradientMap,
  10985. combine: material.combine,
  10986. vertexColors: material.vertexColors,
  10987. fog: !! fog,
  10988. useFog: material.fog,
  10989. fogExp: ( fog && fog.isFogExp2 ),
  10990. flatShading: material.flatShading,
  10991. sizeAttenuation: material.sizeAttenuation,
  10992. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10993. skinning: material.skinning && maxBones > 0,
  10994. maxBones: maxBones,
  10995. useVertexTexture: capabilities.floatVertexTextures,
  10996. morphTargets: material.morphTargets,
  10997. morphNormals: material.morphNormals,
  10998. maxMorphTargets: renderer.maxMorphTargets,
  10999. maxMorphNormals: renderer.maxMorphNormals,
  11000. numDirLights: lights.directional.length,
  11001. numPointLights: lights.point.length,
  11002. numSpotLights: lights.spot.length,
  11003. numRectAreaLights: lights.rectArea.length,
  11004. numHemiLights: lights.hemi.length,
  11005. numClippingPlanes: nClipPlanes,
  11006. numClipIntersection: nClipIntersection,
  11007. dithering: material.dithering,
  11008. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  11009. shadowMapType: renderer.shadowMap.type,
  11010. toneMapping: renderer.toneMapping,
  11011. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11012. premultipliedAlpha: material.premultipliedAlpha,
  11013. alphaTest: material.alphaTest,
  11014. doubleSided: material.side === DoubleSide,
  11015. flipSided: material.side === BackSide,
  11016. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  11017. };
  11018. return parameters;
  11019. };
  11020. this.getProgramCode = function ( material, parameters ) {
  11021. var array = [];
  11022. if ( parameters.shaderID ) {
  11023. array.push( parameters.shaderID );
  11024. } else {
  11025. array.push( material.fragmentShader );
  11026. array.push( material.vertexShader );
  11027. }
  11028. if ( material.defines !== undefined ) {
  11029. for ( var name in material.defines ) {
  11030. array.push( name );
  11031. array.push( material.defines[ name ] );
  11032. }
  11033. }
  11034. for ( var i = 0; i < parameterNames.length; i ++ ) {
  11035. array.push( parameters[ parameterNames[ i ] ] );
  11036. }
  11037. array.push( material.onBeforeCompile.toString() );
  11038. array.push( renderer.gammaOutput );
  11039. return array.join();
  11040. };
  11041. this.acquireProgram = function ( material, shader, parameters, code ) {
  11042. var program;
  11043. // Check if code has been already compiled
  11044. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  11045. var programInfo = programs[ p ];
  11046. if ( programInfo.code === code ) {
  11047. program = programInfo;
  11048. ++ program.usedTimes;
  11049. break;
  11050. }
  11051. }
  11052. if ( program === undefined ) {
  11053. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  11054. programs.push( program );
  11055. }
  11056. return program;
  11057. };
  11058. this.releaseProgram = function ( program ) {
  11059. if ( -- program.usedTimes === 0 ) {
  11060. // Remove from unordered set
  11061. var i = programs.indexOf( program );
  11062. programs[ i ] = programs[ programs.length - 1 ];
  11063. programs.pop();
  11064. // Free WebGL resources
  11065. program.destroy();
  11066. }
  11067. };
  11068. // Exposed for resource monitoring & error feedback via renderer.info:
  11069. this.programs = programs;
  11070. }
  11071. /**
  11072. * @author mrdoob / http://mrdoob.com/
  11073. */
  11074. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, infoMemory ) {
  11075. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  11076. //
  11077. function clampToMaxSize( image, maxSize ) {
  11078. if ( image.width > maxSize || image.height > maxSize ) {
  11079. // Warning: Scaling through the canvas will only work with images that use
  11080. // premultiplied alpha.
  11081. var scale = maxSize / Math.max( image.width, image.height );
  11082. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11083. canvas.width = Math.floor( image.width * scale );
  11084. canvas.height = Math.floor( image.height * scale );
  11085. var context = canvas.getContext( '2d' );
  11086. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  11087. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11088. return canvas;
  11089. }
  11090. return image;
  11091. }
  11092. function isPowerOfTwo( image ) {
  11093. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  11094. }
  11095. function makePowerOfTwo( image ) {
  11096. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  11097. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11098. canvas.width = _Math.nearestPowerOfTwo( image.width );
  11099. canvas.height = _Math.nearestPowerOfTwo( image.height );
  11100. var context = canvas.getContext( '2d' );
  11101. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  11102. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  11103. return canvas;
  11104. }
  11105. return image;
  11106. }
  11107. function textureNeedsPowerOfTwo( texture ) {
  11108. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  11109. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  11110. }
  11111. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  11112. return texture.generateMipmaps && isPowerOfTwo &&
  11113. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  11114. }
  11115. // Fallback filters for non-power-of-2 textures
  11116. function filterFallback( f ) {
  11117. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  11118. return _gl.NEAREST;
  11119. }
  11120. return _gl.LINEAR;
  11121. }
  11122. //
  11123. function onTextureDispose( event ) {
  11124. var texture = event.target;
  11125. texture.removeEventListener( 'dispose', onTextureDispose );
  11126. deallocateTexture( texture );
  11127. infoMemory.textures --;
  11128. }
  11129. function onRenderTargetDispose( event ) {
  11130. var renderTarget = event.target;
  11131. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11132. deallocateRenderTarget( renderTarget );
  11133. infoMemory.textures --;
  11134. }
  11135. //
  11136. function deallocateTexture( texture ) {
  11137. var textureProperties = properties.get( texture );
  11138. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  11139. // cube texture
  11140. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  11141. } else {
  11142. // 2D texture
  11143. if ( textureProperties.__webglInit === undefined ) return;
  11144. _gl.deleteTexture( textureProperties.__webglTexture );
  11145. }
  11146. // remove all webgl properties
  11147. properties.remove( texture );
  11148. }
  11149. function deallocateRenderTarget( renderTarget ) {
  11150. var renderTargetProperties = properties.get( renderTarget );
  11151. var textureProperties = properties.get( renderTarget.texture );
  11152. if ( ! renderTarget ) return;
  11153. if ( textureProperties.__webglTexture !== undefined ) {
  11154. _gl.deleteTexture( textureProperties.__webglTexture );
  11155. }
  11156. if ( renderTarget.depthTexture ) {
  11157. renderTarget.depthTexture.dispose();
  11158. }
  11159. if ( renderTarget.isWebGLRenderTargetCube ) {
  11160. for ( var i = 0; i < 6; i ++ ) {
  11161. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  11162. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  11163. }
  11164. } else {
  11165. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  11166. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  11167. }
  11168. properties.remove( renderTarget.texture );
  11169. properties.remove( renderTarget );
  11170. }
  11171. //
  11172. function setTexture2D( texture, slot ) {
  11173. var textureProperties = properties.get( texture );
  11174. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11175. var image = texture.image;
  11176. if ( image === undefined ) {
  11177. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  11178. } else if ( image.complete === false ) {
  11179. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  11180. } else {
  11181. uploadTexture( textureProperties, texture, slot );
  11182. return;
  11183. }
  11184. }
  11185. state.activeTexture( _gl.TEXTURE0 + slot );
  11186. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11187. }
  11188. function setTextureCube( texture, slot ) {
  11189. var textureProperties = properties.get( texture );
  11190. if ( texture.image.length === 6 ) {
  11191. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11192. if ( ! textureProperties.__image__webglTextureCube ) {
  11193. texture.addEventListener( 'dispose', onTextureDispose );
  11194. textureProperties.__image__webglTextureCube = _gl.createTexture();
  11195. infoMemory.textures ++;
  11196. }
  11197. state.activeTexture( _gl.TEXTURE0 + slot );
  11198. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11199. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11200. var isCompressed = ( texture && texture.isCompressedTexture );
  11201. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  11202. var cubeImage = [];
  11203. for ( var i = 0; i < 6; i ++ ) {
  11204. if ( ! isCompressed && ! isDataTexture ) {
  11205. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  11206. } else {
  11207. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  11208. }
  11209. }
  11210. var image = cubeImage[ 0 ],
  11211. isPowerOfTwoImage = isPowerOfTwo( image ),
  11212. glFormat = utils.convert( texture.format ),
  11213. glType = utils.convert( texture.type );
  11214. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  11215. for ( var i = 0; i < 6; i ++ ) {
  11216. if ( ! isCompressed ) {
  11217. if ( isDataTexture ) {
  11218. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  11219. } else {
  11220. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  11221. }
  11222. } else {
  11223. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  11224. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  11225. mipmap = mipmaps[ j ];
  11226. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11227. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11228. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11229. } else {
  11230. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  11231. }
  11232. } else {
  11233. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11234. }
  11235. }
  11236. }
  11237. }
  11238. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  11239. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11240. }
  11241. textureProperties.__version = texture.version;
  11242. if ( texture.onUpdate ) texture.onUpdate( texture );
  11243. } else {
  11244. state.activeTexture( _gl.TEXTURE0 + slot );
  11245. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11246. }
  11247. }
  11248. }
  11249. function setTextureCubeDynamic( texture, slot ) {
  11250. state.activeTexture( _gl.TEXTURE0 + slot );
  11251. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  11252. }
  11253. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  11254. var extension;
  11255. if ( isPowerOfTwoImage ) {
  11256. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  11257. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  11258. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  11259. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  11260. } else {
  11261. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11262. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11263. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  11264. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  11265. }
  11266. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  11267. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  11268. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  11269. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  11270. }
  11271. }
  11272. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11273. if ( extension ) {
  11274. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  11275. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  11276. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  11277. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  11278. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  11279. }
  11280. }
  11281. }
  11282. function uploadTexture( textureProperties, texture, slot ) {
  11283. if ( textureProperties.__webglInit === undefined ) {
  11284. textureProperties.__webglInit = true;
  11285. texture.addEventListener( 'dispose', onTextureDispose );
  11286. textureProperties.__webglTexture = _gl.createTexture();
  11287. infoMemory.textures ++;
  11288. }
  11289. state.activeTexture( _gl.TEXTURE0 + slot );
  11290. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11291. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11292. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  11293. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  11294. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  11295. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  11296. image = makePowerOfTwo( image );
  11297. }
  11298. var isPowerOfTwoImage = isPowerOfTwo( image ),
  11299. glFormat = utils.convert( texture.format ),
  11300. glType = utils.convert( texture.type );
  11301. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  11302. var mipmap, mipmaps = texture.mipmaps;
  11303. if ( texture.isDepthTexture ) {
  11304. // populate depth texture with dummy data
  11305. var internalFormat = _gl.DEPTH_COMPONENT;
  11306. if ( texture.type === FloatType ) {
  11307. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  11308. internalFormat = _gl.DEPTH_COMPONENT32F;
  11309. } else if ( _isWebGL2 ) {
  11310. // WebGL 2.0 requires signed internalformat for glTexImage2D
  11311. internalFormat = _gl.DEPTH_COMPONENT16;
  11312. }
  11313. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  11314. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11315. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  11316. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11317. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  11318. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  11319. texture.type = UnsignedShortType;
  11320. glType = utils.convert( texture.type );
  11321. }
  11322. }
  11323. // Depth stencil textures need the DEPTH_STENCIL internal format
  11324. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11325. if ( texture.format === DepthStencilFormat ) {
  11326. internalFormat = _gl.DEPTH_STENCIL;
  11327. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11328. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  11329. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11330. if ( texture.type !== UnsignedInt248Type ) {
  11331. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  11332. texture.type = UnsignedInt248Type;
  11333. glType = utils.convert( texture.type );
  11334. }
  11335. }
  11336. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  11337. } else if ( texture.isDataTexture ) {
  11338. // use manually created mipmaps if available
  11339. // if there are no manual mipmaps
  11340. // set 0 level mipmap and then use GL to generate other mipmap levels
  11341. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11342. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11343. mipmap = mipmaps[ i ];
  11344. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11345. }
  11346. texture.generateMipmaps = false;
  11347. } else {
  11348. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  11349. }
  11350. } else if ( texture.isCompressedTexture ) {
  11351. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11352. mipmap = mipmaps[ i ];
  11353. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11354. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11355. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11356. } else {
  11357. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  11358. }
  11359. } else {
  11360. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11361. }
  11362. }
  11363. } else {
  11364. // regular Texture (image, video, canvas)
  11365. // use manually created mipmaps if available
  11366. // if there are no manual mipmaps
  11367. // set 0 level mipmap and then use GL to generate other mipmap levels
  11368. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11369. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11370. mipmap = mipmaps[ i ];
  11371. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  11372. }
  11373. texture.generateMipmaps = false;
  11374. } else {
  11375. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  11376. }
  11377. }
  11378. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11379. textureProperties.__version = texture.version;
  11380. if ( texture.onUpdate ) texture.onUpdate( texture );
  11381. }
  11382. // Render targets
  11383. // Setup storage for target texture and bind it to correct framebuffer
  11384. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  11385. var glFormat = utils.convert( renderTarget.texture.format );
  11386. var glType = utils.convert( renderTarget.texture.type );
  11387. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  11388. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11389. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  11390. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11391. }
  11392. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  11393. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  11394. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  11395. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  11396. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  11397. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11398. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  11399. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  11400. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11401. } else {
  11402. // FIXME: We don't support !depth !stencil
  11403. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  11404. }
  11405. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  11406. }
  11407. // Setup resources for a Depth Texture for a FBO (needs an extension)
  11408. function setupDepthTexture( framebuffer, renderTarget ) {
  11409. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  11410. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  11411. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11412. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  11413. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  11414. }
  11415. // upload an empty depth texture with framebuffer size
  11416. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11417. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11418. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11419. renderTarget.depthTexture.image.width = renderTarget.width;
  11420. renderTarget.depthTexture.image.height = renderTarget.height;
  11421. renderTarget.depthTexture.needsUpdate = true;
  11422. }
  11423. setTexture2D( renderTarget.depthTexture, 0 );
  11424. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11425. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11426. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11427. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11428. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11429. } else {
  11430. throw new Error( 'Unknown depthTexture format' );
  11431. }
  11432. }
  11433. // Setup GL resources for a non-texture depth buffer
  11434. function setupDepthRenderbuffer( renderTarget ) {
  11435. var renderTargetProperties = properties.get( renderTarget );
  11436. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11437. if ( renderTarget.depthTexture ) {
  11438. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  11439. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11440. } else {
  11441. if ( isCube ) {
  11442. renderTargetProperties.__webglDepthbuffer = [];
  11443. for ( var i = 0; i < 6; i ++ ) {
  11444. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11445. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11446. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11447. }
  11448. } else {
  11449. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11450. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11451. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11452. }
  11453. }
  11454. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11455. }
  11456. // Set up GL resources for the render target
  11457. function setupRenderTarget( renderTarget ) {
  11458. var renderTargetProperties = properties.get( renderTarget );
  11459. var textureProperties = properties.get( renderTarget.texture );
  11460. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11461. textureProperties.__webglTexture = _gl.createTexture();
  11462. infoMemory.textures ++;
  11463. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11464. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11465. // Setup framebuffer
  11466. if ( isCube ) {
  11467. renderTargetProperties.__webglFramebuffer = [];
  11468. for ( var i = 0; i < 6; i ++ ) {
  11469. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11470. }
  11471. } else {
  11472. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11473. }
  11474. // Setup color buffer
  11475. if ( isCube ) {
  11476. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11477. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11478. for ( var i = 0; i < 6; i ++ ) {
  11479. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11480. }
  11481. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11482. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11483. } else {
  11484. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11485. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11486. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11487. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11488. state.bindTexture( _gl.TEXTURE_2D, null );
  11489. }
  11490. // Setup depth and stencil buffers
  11491. if ( renderTarget.depthBuffer ) {
  11492. setupDepthRenderbuffer( renderTarget );
  11493. }
  11494. }
  11495. function updateRenderTargetMipmap( renderTarget ) {
  11496. var texture = renderTarget.texture;
  11497. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11498. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  11499. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11500. var webglTexture = properties.get( texture ).__webglTexture;
  11501. state.bindTexture( target, webglTexture );
  11502. _gl.generateMipmap( target );
  11503. state.bindTexture( target, null );
  11504. }
  11505. }
  11506. this.setTexture2D = setTexture2D;
  11507. this.setTextureCube = setTextureCube;
  11508. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11509. this.setupRenderTarget = setupRenderTarget;
  11510. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11511. }
  11512. /**
  11513. * @author fordacious / fordacious.github.io
  11514. */
  11515. function WebGLProperties() {
  11516. var properties = {};
  11517. function get( object ) {
  11518. var uuid = object.uuid;
  11519. var map = properties[ uuid ];
  11520. if ( map === undefined ) {
  11521. map = {};
  11522. properties[ uuid ] = map;
  11523. }
  11524. return map;
  11525. }
  11526. function remove( object ) {
  11527. delete properties[ object.uuid ];
  11528. }
  11529. function clear() {
  11530. properties = {};
  11531. }
  11532. return {
  11533. get: get,
  11534. remove: remove,
  11535. clear: clear
  11536. };
  11537. }
  11538. /**
  11539. * @author mrdoob / http://mrdoob.com/
  11540. */
  11541. function WebGLState( gl, extensions, utils ) {
  11542. function ColorBuffer() {
  11543. var locked = false;
  11544. var color = new Vector4();
  11545. var currentColorMask = null;
  11546. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  11547. return {
  11548. setMask: function ( colorMask ) {
  11549. if ( currentColorMask !== colorMask && ! locked ) {
  11550. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11551. currentColorMask = colorMask;
  11552. }
  11553. },
  11554. setLocked: function ( lock ) {
  11555. locked = lock;
  11556. },
  11557. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11558. if ( premultipliedAlpha === true ) {
  11559. r *= a; g *= a; b *= a;
  11560. }
  11561. color.set( r, g, b, a );
  11562. if ( currentColorClear.equals( color ) === false ) {
  11563. gl.clearColor( r, g, b, a );
  11564. currentColorClear.copy( color );
  11565. }
  11566. },
  11567. reset: function () {
  11568. locked = false;
  11569. currentColorMask = null;
  11570. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11571. }
  11572. };
  11573. }
  11574. function DepthBuffer() {
  11575. var locked = false;
  11576. var currentDepthMask = null;
  11577. var currentDepthFunc = null;
  11578. var currentDepthClear = null;
  11579. return {
  11580. setTest: function ( depthTest ) {
  11581. if ( depthTest ) {
  11582. enable( gl.DEPTH_TEST );
  11583. } else {
  11584. disable( gl.DEPTH_TEST );
  11585. }
  11586. },
  11587. setMask: function ( depthMask ) {
  11588. if ( currentDepthMask !== depthMask && ! locked ) {
  11589. gl.depthMask( depthMask );
  11590. currentDepthMask = depthMask;
  11591. }
  11592. },
  11593. setFunc: function ( depthFunc ) {
  11594. if ( currentDepthFunc !== depthFunc ) {
  11595. if ( depthFunc ) {
  11596. switch ( depthFunc ) {
  11597. case NeverDepth:
  11598. gl.depthFunc( gl.NEVER );
  11599. break;
  11600. case AlwaysDepth:
  11601. gl.depthFunc( gl.ALWAYS );
  11602. break;
  11603. case LessDepth:
  11604. gl.depthFunc( gl.LESS );
  11605. break;
  11606. case LessEqualDepth:
  11607. gl.depthFunc( gl.LEQUAL );
  11608. break;
  11609. case EqualDepth:
  11610. gl.depthFunc( gl.EQUAL );
  11611. break;
  11612. case GreaterEqualDepth:
  11613. gl.depthFunc( gl.GEQUAL );
  11614. break;
  11615. case GreaterDepth:
  11616. gl.depthFunc( gl.GREATER );
  11617. break;
  11618. case NotEqualDepth:
  11619. gl.depthFunc( gl.NOTEQUAL );
  11620. break;
  11621. default:
  11622. gl.depthFunc( gl.LEQUAL );
  11623. }
  11624. } else {
  11625. gl.depthFunc( gl.LEQUAL );
  11626. }
  11627. currentDepthFunc = depthFunc;
  11628. }
  11629. },
  11630. setLocked: function ( lock ) {
  11631. locked = lock;
  11632. },
  11633. setClear: function ( depth ) {
  11634. if ( currentDepthClear !== depth ) {
  11635. gl.clearDepth( depth );
  11636. currentDepthClear = depth;
  11637. }
  11638. },
  11639. reset: function () {
  11640. locked = false;
  11641. currentDepthMask = null;
  11642. currentDepthFunc = null;
  11643. currentDepthClear = null;
  11644. }
  11645. };
  11646. }
  11647. function StencilBuffer() {
  11648. var locked = false;
  11649. var currentStencilMask = null;
  11650. var currentStencilFunc = null;
  11651. var currentStencilRef = null;
  11652. var currentStencilFuncMask = null;
  11653. var currentStencilFail = null;
  11654. var currentStencilZFail = null;
  11655. var currentStencilZPass = null;
  11656. var currentStencilClear = null;
  11657. return {
  11658. setTest: function ( stencilTest ) {
  11659. if ( stencilTest ) {
  11660. enable( gl.STENCIL_TEST );
  11661. } else {
  11662. disable( gl.STENCIL_TEST );
  11663. }
  11664. },
  11665. setMask: function ( stencilMask ) {
  11666. if ( currentStencilMask !== stencilMask && ! locked ) {
  11667. gl.stencilMask( stencilMask );
  11668. currentStencilMask = stencilMask;
  11669. }
  11670. },
  11671. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11672. if ( currentStencilFunc !== stencilFunc ||
  11673. currentStencilRef !== stencilRef ||
  11674. currentStencilFuncMask !== stencilMask ) {
  11675. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11676. currentStencilFunc = stencilFunc;
  11677. currentStencilRef = stencilRef;
  11678. currentStencilFuncMask = stencilMask;
  11679. }
  11680. },
  11681. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11682. if ( currentStencilFail !== stencilFail ||
  11683. currentStencilZFail !== stencilZFail ||
  11684. currentStencilZPass !== stencilZPass ) {
  11685. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11686. currentStencilFail = stencilFail;
  11687. currentStencilZFail = stencilZFail;
  11688. currentStencilZPass = stencilZPass;
  11689. }
  11690. },
  11691. setLocked: function ( lock ) {
  11692. locked = lock;
  11693. },
  11694. setClear: function ( stencil ) {
  11695. if ( currentStencilClear !== stencil ) {
  11696. gl.clearStencil( stencil );
  11697. currentStencilClear = stencil;
  11698. }
  11699. },
  11700. reset: function () {
  11701. locked = false;
  11702. currentStencilMask = null;
  11703. currentStencilFunc = null;
  11704. currentStencilRef = null;
  11705. currentStencilFuncMask = null;
  11706. currentStencilFail = null;
  11707. currentStencilZFail = null;
  11708. currentStencilZPass = null;
  11709. currentStencilClear = null;
  11710. }
  11711. };
  11712. }
  11713. //
  11714. var colorBuffer = new ColorBuffer();
  11715. var depthBuffer = new DepthBuffer();
  11716. var stencilBuffer = new StencilBuffer();
  11717. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11718. var newAttributes = new Uint8Array( maxVertexAttributes );
  11719. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11720. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11721. var capabilities = {};
  11722. var compressedTextureFormats = null;
  11723. var currentProgram = null;
  11724. var currentBlending = null;
  11725. var currentBlendEquation = null;
  11726. var currentBlendSrc = null;
  11727. var currentBlendDst = null;
  11728. var currentBlendEquationAlpha = null;
  11729. var currentBlendSrcAlpha = null;
  11730. var currentBlendDstAlpha = null;
  11731. var currentPremultipledAlpha = false;
  11732. var currentFlipSided = null;
  11733. var currentCullFace = null;
  11734. var currentLineWidth = null;
  11735. var currentPolygonOffsetFactor = null;
  11736. var currentPolygonOffsetUnits = null;
  11737. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11738. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11739. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11740. var currentTextureSlot = null;
  11741. var currentBoundTextures = {};
  11742. var currentScissor = new Vector4();
  11743. var currentViewport = new Vector4();
  11744. function createTexture( type, target, count ) {
  11745. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11746. var texture = gl.createTexture();
  11747. gl.bindTexture( type, texture );
  11748. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11749. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11750. for ( var i = 0; i < count; i ++ ) {
  11751. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11752. }
  11753. return texture;
  11754. }
  11755. var emptyTextures = {};
  11756. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11757. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11758. // init
  11759. colorBuffer.setClear( 0, 0, 0, 1 );
  11760. depthBuffer.setClear( 1 );
  11761. stencilBuffer.setClear( 0 );
  11762. enable( gl.DEPTH_TEST );
  11763. depthBuffer.setFunc( LessEqualDepth );
  11764. setFlipSided( false );
  11765. setCullFace( CullFaceBack );
  11766. enable( gl.CULL_FACE );
  11767. enable( gl.BLEND );
  11768. setBlending( NormalBlending );
  11769. //
  11770. function initAttributes() {
  11771. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11772. newAttributes[ i ] = 0;
  11773. }
  11774. }
  11775. function enableAttribute( attribute ) {
  11776. newAttributes[ attribute ] = 1;
  11777. if ( enabledAttributes[ attribute ] === 0 ) {
  11778. gl.enableVertexAttribArray( attribute );
  11779. enabledAttributes[ attribute ] = 1;
  11780. }
  11781. if ( attributeDivisors[ attribute ] !== 0 ) {
  11782. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11783. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11784. attributeDivisors[ attribute ] = 0;
  11785. }
  11786. }
  11787. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11788. newAttributes[ attribute ] = 1;
  11789. if ( enabledAttributes[ attribute ] === 0 ) {
  11790. gl.enableVertexAttribArray( attribute );
  11791. enabledAttributes[ attribute ] = 1;
  11792. }
  11793. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11794. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11795. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11796. attributeDivisors[ attribute ] = meshPerAttribute;
  11797. }
  11798. }
  11799. function disableUnusedAttributes() {
  11800. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11801. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11802. gl.disableVertexAttribArray( i );
  11803. enabledAttributes[ i ] = 0;
  11804. }
  11805. }
  11806. }
  11807. function enable( id ) {
  11808. if ( capabilities[ id ] !== true ) {
  11809. gl.enable( id );
  11810. capabilities[ id ] = true;
  11811. }
  11812. }
  11813. function disable( id ) {
  11814. if ( capabilities[ id ] !== false ) {
  11815. gl.disable( id );
  11816. capabilities[ id ] = false;
  11817. }
  11818. }
  11819. function getCompressedTextureFormats() {
  11820. if ( compressedTextureFormats === null ) {
  11821. compressedTextureFormats = [];
  11822. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11823. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11824. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11825. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11826. for ( var i = 0; i < formats.length; i ++ ) {
  11827. compressedTextureFormats.push( formats[ i ] );
  11828. }
  11829. }
  11830. }
  11831. return compressedTextureFormats;
  11832. }
  11833. function useProgram( program ) {
  11834. if ( currentProgram !== program ) {
  11835. gl.useProgram( program );
  11836. currentProgram = program;
  11837. return true;
  11838. }
  11839. return false;
  11840. }
  11841. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11842. if ( blending !== NoBlending ) {
  11843. enable( gl.BLEND );
  11844. } else {
  11845. disable( gl.BLEND );
  11846. }
  11847. if ( blending !== CustomBlending ) {
  11848. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11849. switch ( blending ) {
  11850. case AdditiveBlending:
  11851. if ( premultipliedAlpha ) {
  11852. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11853. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11854. } else {
  11855. gl.blendEquation( gl.FUNC_ADD );
  11856. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11857. }
  11858. break;
  11859. case SubtractiveBlending:
  11860. if ( premultipliedAlpha ) {
  11861. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11862. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11863. } else {
  11864. gl.blendEquation( gl.FUNC_ADD );
  11865. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11866. }
  11867. break;
  11868. case MultiplyBlending:
  11869. if ( premultipliedAlpha ) {
  11870. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11871. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11872. } else {
  11873. gl.blendEquation( gl.FUNC_ADD );
  11874. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11875. }
  11876. break;
  11877. default:
  11878. if ( premultipliedAlpha ) {
  11879. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11880. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11881. } else {
  11882. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11883. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11884. }
  11885. }
  11886. }
  11887. currentBlendEquation = null;
  11888. currentBlendSrc = null;
  11889. currentBlendDst = null;
  11890. currentBlendEquationAlpha = null;
  11891. currentBlendSrcAlpha = null;
  11892. currentBlendDstAlpha = null;
  11893. } else {
  11894. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11895. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11896. blendDstAlpha = blendDstAlpha || blendDst;
  11897. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11898. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  11899. currentBlendEquation = blendEquation;
  11900. currentBlendEquationAlpha = blendEquationAlpha;
  11901. }
  11902. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11903. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  11904. currentBlendSrc = blendSrc;
  11905. currentBlendDst = blendDst;
  11906. currentBlendSrcAlpha = blendSrcAlpha;
  11907. currentBlendDstAlpha = blendDstAlpha;
  11908. }
  11909. }
  11910. currentBlending = blending;
  11911. currentPremultipledAlpha = premultipliedAlpha;
  11912. }
  11913. function setMaterial( material ) {
  11914. material.side === DoubleSide
  11915. ? disable( gl.CULL_FACE )
  11916. : enable( gl.CULL_FACE );
  11917. setFlipSided( material.side === BackSide );
  11918. material.transparent === true
  11919. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11920. : setBlending( NoBlending );
  11921. depthBuffer.setFunc( material.depthFunc );
  11922. depthBuffer.setTest( material.depthTest );
  11923. depthBuffer.setMask( material.depthWrite );
  11924. colorBuffer.setMask( material.colorWrite );
  11925. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11926. }
  11927. //
  11928. function setFlipSided( flipSided ) {
  11929. if ( currentFlipSided !== flipSided ) {
  11930. if ( flipSided ) {
  11931. gl.frontFace( gl.CW );
  11932. } else {
  11933. gl.frontFace( gl.CCW );
  11934. }
  11935. currentFlipSided = flipSided;
  11936. }
  11937. }
  11938. function setCullFace( cullFace ) {
  11939. if ( cullFace !== CullFaceNone ) {
  11940. enable( gl.CULL_FACE );
  11941. if ( cullFace !== currentCullFace ) {
  11942. if ( cullFace === CullFaceBack ) {
  11943. gl.cullFace( gl.BACK );
  11944. } else if ( cullFace === CullFaceFront ) {
  11945. gl.cullFace( gl.FRONT );
  11946. } else {
  11947. gl.cullFace( gl.FRONT_AND_BACK );
  11948. }
  11949. }
  11950. } else {
  11951. disable( gl.CULL_FACE );
  11952. }
  11953. currentCullFace = cullFace;
  11954. }
  11955. function setLineWidth( width ) {
  11956. if ( width !== currentLineWidth ) {
  11957. if ( lineWidthAvailable ) gl.lineWidth( width );
  11958. currentLineWidth = width;
  11959. }
  11960. }
  11961. function setPolygonOffset( polygonOffset, factor, units ) {
  11962. if ( polygonOffset ) {
  11963. enable( gl.POLYGON_OFFSET_FILL );
  11964. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11965. gl.polygonOffset( factor, units );
  11966. currentPolygonOffsetFactor = factor;
  11967. currentPolygonOffsetUnits = units;
  11968. }
  11969. } else {
  11970. disable( gl.POLYGON_OFFSET_FILL );
  11971. }
  11972. }
  11973. function setScissorTest( scissorTest ) {
  11974. if ( scissorTest ) {
  11975. enable( gl.SCISSOR_TEST );
  11976. } else {
  11977. disable( gl.SCISSOR_TEST );
  11978. }
  11979. }
  11980. // texture
  11981. function activeTexture( webglSlot ) {
  11982. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11983. if ( currentTextureSlot !== webglSlot ) {
  11984. gl.activeTexture( webglSlot );
  11985. currentTextureSlot = webglSlot;
  11986. }
  11987. }
  11988. function bindTexture( webglType, webglTexture ) {
  11989. if ( currentTextureSlot === null ) {
  11990. activeTexture();
  11991. }
  11992. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11993. if ( boundTexture === undefined ) {
  11994. boundTexture = { type: undefined, texture: undefined };
  11995. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11996. }
  11997. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11998. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11999. boundTexture.type = webglType;
  12000. boundTexture.texture = webglTexture;
  12001. }
  12002. }
  12003. function compressedTexImage2D() {
  12004. try {
  12005. gl.compressedTexImage2D.apply( gl, arguments );
  12006. } catch ( error ) {
  12007. console.error( 'THREE.WebGLState:', error );
  12008. }
  12009. }
  12010. function texImage2D() {
  12011. try {
  12012. gl.texImage2D.apply( gl, arguments );
  12013. } catch ( error ) {
  12014. console.error( 'THREE.WebGLState:', error );
  12015. }
  12016. }
  12017. //
  12018. function scissor( scissor ) {
  12019. if ( currentScissor.equals( scissor ) === false ) {
  12020. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12021. currentScissor.copy( scissor );
  12022. }
  12023. }
  12024. function viewport( viewport ) {
  12025. if ( currentViewport.equals( viewport ) === false ) {
  12026. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12027. currentViewport.copy( viewport );
  12028. }
  12029. }
  12030. //
  12031. function reset() {
  12032. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  12033. if ( enabledAttributes[ i ] === 1 ) {
  12034. gl.disableVertexAttribArray( i );
  12035. enabledAttributes[ i ] = 0;
  12036. }
  12037. }
  12038. capabilities = {};
  12039. compressedTextureFormats = null;
  12040. currentTextureSlot = null;
  12041. currentBoundTextures = {};
  12042. currentProgram = null;
  12043. currentBlending = null;
  12044. currentFlipSided = null;
  12045. currentCullFace = null;
  12046. colorBuffer.reset();
  12047. depthBuffer.reset();
  12048. stencilBuffer.reset();
  12049. }
  12050. return {
  12051. buffers: {
  12052. color: colorBuffer,
  12053. depth: depthBuffer,
  12054. stencil: stencilBuffer
  12055. },
  12056. initAttributes: initAttributes,
  12057. enableAttribute: enableAttribute,
  12058. enableAttributeAndDivisor: enableAttributeAndDivisor,
  12059. disableUnusedAttributes: disableUnusedAttributes,
  12060. enable: enable,
  12061. disable: disable,
  12062. getCompressedTextureFormats: getCompressedTextureFormats,
  12063. useProgram: useProgram,
  12064. setBlending: setBlending,
  12065. setMaterial: setMaterial,
  12066. setFlipSided: setFlipSided,
  12067. setCullFace: setCullFace,
  12068. setLineWidth: setLineWidth,
  12069. setPolygonOffset: setPolygonOffset,
  12070. setScissorTest: setScissorTest,
  12071. activeTexture: activeTexture,
  12072. bindTexture: bindTexture,
  12073. compressedTexImage2D: compressedTexImage2D,
  12074. texImage2D: texImage2D,
  12075. scissor: scissor,
  12076. viewport: viewport,
  12077. reset: reset
  12078. };
  12079. }
  12080. /**
  12081. * @author mrdoob / http://mrdoob.com/
  12082. */
  12083. function WebGLCapabilities( gl, extensions, parameters ) {
  12084. var maxAnisotropy;
  12085. function getMaxAnisotropy() {
  12086. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  12087. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12088. if ( extension !== null ) {
  12089. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12090. } else {
  12091. maxAnisotropy = 0;
  12092. }
  12093. return maxAnisotropy;
  12094. }
  12095. function getMaxPrecision( precision ) {
  12096. if ( precision === 'highp' ) {
  12097. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  12098. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  12099. return 'highp';
  12100. }
  12101. precision = 'mediump';
  12102. }
  12103. if ( precision === 'mediump' ) {
  12104. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  12105. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  12106. return 'mediump';
  12107. }
  12108. }
  12109. return 'lowp';
  12110. }
  12111. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  12112. var maxPrecision = getMaxPrecision( precision );
  12113. if ( maxPrecision !== precision ) {
  12114. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12115. precision = maxPrecision;
  12116. }
  12117. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  12118. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  12119. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12120. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  12121. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12122. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  12123. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  12124. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  12125. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  12126. var vertexTextures = maxVertexTextures > 0;
  12127. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  12128. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12129. return {
  12130. getMaxAnisotropy: getMaxAnisotropy,
  12131. getMaxPrecision: getMaxPrecision,
  12132. precision: precision,
  12133. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12134. maxTextures: maxTextures,
  12135. maxVertexTextures: maxVertexTextures,
  12136. maxTextureSize: maxTextureSize,
  12137. maxCubemapSize: maxCubemapSize,
  12138. maxAttributes: maxAttributes,
  12139. maxVertexUniforms: maxVertexUniforms,
  12140. maxVaryings: maxVaryings,
  12141. maxFragmentUniforms: maxFragmentUniforms,
  12142. vertexTextures: vertexTextures,
  12143. floatFragmentTextures: floatFragmentTextures,
  12144. floatVertexTextures: floatVertexTextures
  12145. };
  12146. }
  12147. /**
  12148. * @author mrdoob / http://mrdoob.com/
  12149. */
  12150. function ArrayCamera( array ) {
  12151. PerspectiveCamera.call( this );
  12152. this.cameras = array || [];
  12153. }
  12154. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  12155. constructor: ArrayCamera,
  12156. isArrayCamera: true
  12157. } );
  12158. /**
  12159. * @author mrdoob / http://mrdoob.com/
  12160. */
  12161. function WebVRManager( renderer ) {
  12162. var scope = this;
  12163. var device = null;
  12164. var frameData = null;
  12165. if ( 'VRFrameData' in window ) {
  12166. frameData = new window.VRFrameData();
  12167. }
  12168. var matrixWorldInverse = new Matrix4();
  12169. var standingMatrix = new Matrix4();
  12170. var standingMatrixInverse = new Matrix4();
  12171. var cameraL = new PerspectiveCamera();
  12172. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  12173. cameraL.layers.enable( 1 );
  12174. var cameraR = new PerspectiveCamera();
  12175. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  12176. cameraR.layers.enable( 2 );
  12177. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  12178. cameraVR.layers.enable( 1 );
  12179. cameraVR.layers.enable( 2 );
  12180. //
  12181. var currentSize, currentPixelRatio;
  12182. function onVRDisplayPresentChange() {
  12183. if ( device !== null && device.isPresenting ) {
  12184. var eyeParameters = device.getEyeParameters( 'left' );
  12185. var renderWidth = eyeParameters.renderWidth;
  12186. var renderHeight = eyeParameters.renderHeight;
  12187. currentPixelRatio = renderer.getPixelRatio();
  12188. currentSize = renderer.getSize();
  12189. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  12190. } else if ( scope.enabled ) {
  12191. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  12192. }
  12193. }
  12194. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  12195. //
  12196. this.enabled = false;
  12197. this.standing = false;
  12198. this.getDevice = function () {
  12199. return device;
  12200. };
  12201. this.setDevice = function ( value ) {
  12202. if ( value !== undefined ) device = value;
  12203. };
  12204. this.getCamera = function ( camera ) {
  12205. if ( device === null ) return camera;
  12206. device.depthNear = camera.near;
  12207. device.depthFar = camera.far;
  12208. device.getFrameData( frameData );
  12209. //
  12210. var pose = frameData.pose;
  12211. if ( pose.position !== null ) {
  12212. camera.position.fromArray( pose.position );
  12213. } else {
  12214. camera.position.set( 0, 0, 0 );
  12215. }
  12216. if ( pose.orientation !== null ) {
  12217. camera.quaternion.fromArray( pose.orientation );
  12218. }
  12219. camera.updateMatrixWorld();
  12220. var stageParameters = device.stageParameters;
  12221. if ( this.standing && stageParameters ) {
  12222. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  12223. standingMatrixInverse.getInverse( standingMatrix );
  12224. camera.matrixWorld.multiply( standingMatrix );
  12225. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  12226. }
  12227. if ( device.isPresenting === false ) return camera;
  12228. //
  12229. cameraL.near = camera.near;
  12230. cameraR.near = camera.near;
  12231. cameraL.far = camera.far;
  12232. cameraR.far = camera.far;
  12233. cameraVR.matrixWorld.copy( camera.matrixWorld );
  12234. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  12235. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  12236. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  12237. if ( this.standing && stageParameters ) {
  12238. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  12239. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  12240. }
  12241. var parent = camera.parent;
  12242. if ( parent !== null ) {
  12243. matrixWorldInverse.getInverse( parent.matrixWorld );
  12244. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  12245. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  12246. }
  12247. // envMap and Mirror needs camera.matrixWorld
  12248. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  12249. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  12250. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  12251. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  12252. // HACK @mrdoob
  12253. // https://github.com/w3c/webvr/issues/203
  12254. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  12255. //
  12256. var layers = device.getLayers();
  12257. if ( layers.length ) {
  12258. var layer = layers[ 0 ];
  12259. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  12260. cameraL.bounds.fromArray( layer.leftBounds );
  12261. }
  12262. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  12263. cameraR.bounds.fromArray( layer.rightBounds );
  12264. }
  12265. }
  12266. return cameraVR;
  12267. };
  12268. this.getStandingMatrix = function () {
  12269. return standingMatrix;
  12270. };
  12271. this.submitFrame = function () {
  12272. if ( device && device.isPresenting ) device.submitFrame();
  12273. };
  12274. this.dispose = function() {
  12275. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  12276. };
  12277. }
  12278. /**
  12279. * @author mrdoob / http://mrdoob.com/
  12280. */
  12281. function WebGLExtensions( gl ) {
  12282. var extensions = {};
  12283. return {
  12284. get: function ( name ) {
  12285. if ( extensions[ name ] !== undefined ) {
  12286. return extensions[ name ];
  12287. }
  12288. var extension;
  12289. switch ( name ) {
  12290. case 'WEBGL_depth_texture':
  12291. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12292. break;
  12293. case 'EXT_texture_filter_anisotropic':
  12294. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12295. break;
  12296. case 'WEBGL_compressed_texture_s3tc':
  12297. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12298. break;
  12299. case 'WEBGL_compressed_texture_pvrtc':
  12300. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12301. break;
  12302. case 'WEBGL_compressed_texture_etc1':
  12303. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  12304. break;
  12305. default:
  12306. extension = gl.getExtension( name );
  12307. }
  12308. if ( extension === null ) {
  12309. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12310. }
  12311. extensions[ name ] = extension;
  12312. return extension;
  12313. }
  12314. };
  12315. }
  12316. /**
  12317. * @author tschw
  12318. */
  12319. function WebGLClipping() {
  12320. var scope = this,
  12321. globalState = null,
  12322. numGlobalPlanes = 0,
  12323. localClippingEnabled = false,
  12324. renderingShadows = false,
  12325. plane = new Plane(),
  12326. viewNormalMatrix = new Matrix3(),
  12327. uniform = { value: null, needsUpdate: false };
  12328. this.uniform = uniform;
  12329. this.numPlanes = 0;
  12330. this.numIntersection = 0;
  12331. this.init = function( planes, enableLocalClipping, camera ) {
  12332. var enabled =
  12333. planes.length !== 0 ||
  12334. enableLocalClipping ||
  12335. // enable state of previous frame - the clipping code has to
  12336. // run another frame in order to reset the state:
  12337. numGlobalPlanes !== 0 ||
  12338. localClippingEnabled;
  12339. localClippingEnabled = enableLocalClipping;
  12340. globalState = projectPlanes( planes, camera, 0 );
  12341. numGlobalPlanes = planes.length;
  12342. return enabled;
  12343. };
  12344. this.beginShadows = function() {
  12345. renderingShadows = true;
  12346. projectPlanes( null );
  12347. };
  12348. this.endShadows = function() {
  12349. renderingShadows = false;
  12350. resetGlobalState();
  12351. };
  12352. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12353. if ( ! localClippingEnabled ||
  12354. planes === null || planes.length === 0 ||
  12355. renderingShadows && ! clipShadows ) {
  12356. // there's no local clipping
  12357. if ( renderingShadows ) {
  12358. // there's no global clipping
  12359. projectPlanes( null );
  12360. } else {
  12361. resetGlobalState();
  12362. }
  12363. } else {
  12364. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12365. lGlobal = nGlobal * 4,
  12366. dstArray = cache.clippingState || null;
  12367. uniform.value = dstArray; // ensure unique state
  12368. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12369. for ( var i = 0; i !== lGlobal; ++ i ) {
  12370. dstArray[ i ] = globalState[ i ];
  12371. }
  12372. cache.clippingState = dstArray;
  12373. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12374. this.numPlanes += nGlobal;
  12375. }
  12376. };
  12377. function resetGlobalState() {
  12378. if ( uniform.value !== globalState ) {
  12379. uniform.value = globalState;
  12380. uniform.needsUpdate = numGlobalPlanes > 0;
  12381. }
  12382. scope.numPlanes = numGlobalPlanes;
  12383. scope.numIntersection = 0;
  12384. }
  12385. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12386. var nPlanes = planes !== null ? planes.length : 0,
  12387. dstArray = null;
  12388. if ( nPlanes !== 0 ) {
  12389. dstArray = uniform.value;
  12390. if ( skipTransform !== true || dstArray === null ) {
  12391. var flatSize = dstOffset + nPlanes * 4,
  12392. viewMatrix = camera.matrixWorldInverse;
  12393. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12394. if ( dstArray === null || dstArray.length < flatSize ) {
  12395. dstArray = new Float32Array( flatSize );
  12396. }
  12397. for ( var i = 0, i4 = dstOffset;
  12398. i !== nPlanes; ++ i, i4 += 4 ) {
  12399. plane.copy( planes[ i ] ).
  12400. applyMatrix4( viewMatrix, viewNormalMatrix );
  12401. plane.normal.toArray( dstArray, i4 );
  12402. dstArray[ i4 + 3 ] = plane.constant;
  12403. }
  12404. }
  12405. uniform.value = dstArray;
  12406. uniform.needsUpdate = true;
  12407. }
  12408. scope.numPlanes = nPlanes;
  12409. return dstArray;
  12410. }
  12411. }
  12412. /**
  12413. * @author thespite / http://www.twitter.com/thespite
  12414. */
  12415. function WebGLUtils ( gl, extensions ) {
  12416. function convert ( p ) {
  12417. var extension;
  12418. if ( p === RepeatWrapping ) return gl.REPEAT;
  12419. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  12420. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  12421. if ( p === NearestFilter ) return gl.NEAREST;
  12422. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  12423. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  12424. if ( p === LinearFilter ) return gl.LINEAR;
  12425. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  12426. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  12427. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  12428. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  12429. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  12430. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  12431. if ( p === ByteType ) return gl.BYTE;
  12432. if ( p === ShortType ) return gl.SHORT;
  12433. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  12434. if ( p === IntType ) return gl.INT;
  12435. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  12436. if ( p === FloatType ) return gl.FLOAT;
  12437. if ( p === HalfFloatType ) {
  12438. extension = extensions.get( 'OES_texture_half_float' );
  12439. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  12440. }
  12441. if ( p === AlphaFormat ) return gl.ALPHA;
  12442. if ( p === RGBFormat ) return gl.RGB;
  12443. if ( p === RGBAFormat ) return gl.RGBA;
  12444. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  12445. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  12446. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  12447. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  12448. if ( p === AddEquation ) return gl.FUNC_ADD;
  12449. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  12450. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  12451. if ( p === ZeroFactor ) return gl.ZERO;
  12452. if ( p === OneFactor ) return gl.ONE;
  12453. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  12454. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  12455. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  12456. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  12457. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  12458. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  12459. if ( p === DstColorFactor ) return gl.DST_COLOR;
  12460. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  12461. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  12462. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  12463. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  12464. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  12465. if ( extension !== null ) {
  12466. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  12467. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  12468. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  12469. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  12470. }
  12471. }
  12472. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  12473. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  12474. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  12475. if ( extension !== null ) {
  12476. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  12477. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  12478. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  12479. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  12480. }
  12481. }
  12482. if ( p === RGB_ETC1_Format ) {
  12483. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  12484. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  12485. }
  12486. if ( p === MinEquation || p === MaxEquation ) {
  12487. extension = extensions.get( 'EXT_blend_minmax' );
  12488. if ( extension !== null ) {
  12489. if ( p === MinEquation ) return extension.MIN_EXT;
  12490. if ( p === MaxEquation ) return extension.MAX_EXT;
  12491. }
  12492. }
  12493. if ( p === UnsignedInt248Type ) {
  12494. extension = extensions.get( 'WEBGL_depth_texture' );
  12495. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  12496. }
  12497. return 0;
  12498. }
  12499. return { convert: convert }
  12500. }
  12501. /**
  12502. * @author supereggbert / http://www.paulbrunt.co.uk/
  12503. * @author mrdoob / http://mrdoob.com/
  12504. * @author alteredq / http://alteredqualia.com/
  12505. * @author szimek / https://github.com/szimek/
  12506. * @author tschw
  12507. */
  12508. function WebGLRenderer( parameters ) {
  12509. console.log( 'THREE.WebGLRenderer', REVISION );
  12510. parameters = parameters || {};
  12511. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12512. _context = parameters.context !== undefined ? parameters.context : null,
  12513. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12514. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12515. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12516. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12517. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12518. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  12519. var lightsArray = [];
  12520. var shadowsArray = [];
  12521. var currentRenderList = null;
  12522. var spritesArray = [];
  12523. var flaresArray = [];
  12524. // public properties
  12525. this.domElement = _canvas;
  12526. this.context = null;
  12527. // clearing
  12528. this.autoClear = true;
  12529. this.autoClearColor = true;
  12530. this.autoClearDepth = true;
  12531. this.autoClearStencil = true;
  12532. // scene graph
  12533. this.sortObjects = true;
  12534. // user-defined clipping
  12535. this.clippingPlanes = [];
  12536. this.localClippingEnabled = false;
  12537. // physically based shading
  12538. this.gammaFactor = 2.0; // for backwards compatibility
  12539. this.gammaInput = false;
  12540. this.gammaOutput = false;
  12541. // physical lights
  12542. this.physicallyCorrectLights = false;
  12543. // tone mapping
  12544. this.toneMapping = LinearToneMapping;
  12545. this.toneMappingExposure = 1.0;
  12546. this.toneMappingWhitePoint = 1.0;
  12547. // morphs
  12548. this.maxMorphTargets = 8;
  12549. this.maxMorphNormals = 4;
  12550. // internal properties
  12551. var _this = this,
  12552. _isContextLost = false,
  12553. // internal state cache
  12554. _currentRenderTarget = null,
  12555. _currentFramebuffer = null,
  12556. _currentMaterialId = - 1,
  12557. _currentGeometryProgram = '',
  12558. _currentCamera = null,
  12559. _currentArrayCamera = null,
  12560. _currentViewport = new Vector4(),
  12561. _currentScissor = new Vector4(),
  12562. _currentScissorTest = null,
  12563. //
  12564. _usedTextureUnits = 0,
  12565. //
  12566. _width = _canvas.width,
  12567. _height = _canvas.height,
  12568. _pixelRatio = 1,
  12569. _viewport = new Vector4( 0, 0, _width, _height ),
  12570. _scissor = new Vector4( 0, 0, _width, _height ),
  12571. _scissorTest = false,
  12572. // frustum
  12573. _frustum = new Frustum(),
  12574. // clipping
  12575. _clipping = new WebGLClipping(),
  12576. _clippingEnabled = false,
  12577. _localClippingEnabled = false,
  12578. // camera matrices cache
  12579. _projScreenMatrix = new Matrix4(),
  12580. _vector3 = new Vector3(),
  12581. // info
  12582. _infoMemory = {
  12583. geometries: 0,
  12584. textures: 0
  12585. },
  12586. _infoRender = {
  12587. frame: 0,
  12588. calls: 0,
  12589. vertices: 0,
  12590. faces: 0,
  12591. points: 0
  12592. };
  12593. this.info = {
  12594. render: _infoRender,
  12595. memory: _infoMemory,
  12596. programs: null
  12597. };
  12598. function getTargetPixelRatio() {
  12599. return _currentRenderTarget === null ? _pixelRatio : 1;
  12600. }
  12601. // initialize
  12602. var _gl;
  12603. try {
  12604. var contextAttributes = {
  12605. alpha: _alpha,
  12606. depth: _depth,
  12607. stencil: _stencil,
  12608. antialias: _antialias,
  12609. premultipliedAlpha: _premultipliedAlpha,
  12610. preserveDrawingBuffer: _preserveDrawingBuffer
  12611. };
  12612. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  12613. if ( _gl === null ) {
  12614. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12615. throw 'Error creating WebGL context with your selected attributes.';
  12616. } else {
  12617. throw 'Error creating WebGL context.';
  12618. }
  12619. }
  12620. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  12621. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12622. _gl.getShaderPrecisionFormat = function () {
  12623. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12624. };
  12625. }
  12626. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12627. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  12628. } catch ( error ) {
  12629. console.error( 'THREE.WebGLRenderer: ' + error );
  12630. }
  12631. var extensions, capabilities, state;
  12632. var properties, textures, attributes, geometries, objects, lights;
  12633. var programCache, renderLists;
  12634. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  12635. var flareRenderer, spriteRenderer;
  12636. var utils;
  12637. function initGLContext() {
  12638. extensions = new WebGLExtensions( _gl );
  12639. extensions.get( 'WEBGL_depth_texture' );
  12640. extensions.get( 'OES_texture_float' );
  12641. extensions.get( 'OES_texture_float_linear' );
  12642. extensions.get( 'OES_texture_half_float' );
  12643. extensions.get( 'OES_texture_half_float_linear' );
  12644. extensions.get( 'OES_standard_derivatives' );
  12645. extensions.get( 'ANGLE_instanced_arrays' );
  12646. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12647. BufferGeometry.MaxIndex = 4294967296;
  12648. }
  12649. utils = new WebGLUtils( _gl, extensions );
  12650. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12651. state = new WebGLState( _gl, extensions, utils );
  12652. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12653. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12654. properties = new WebGLProperties();
  12655. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _infoMemory );
  12656. attributes = new WebGLAttributes( _gl );
  12657. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12658. objects = new WebGLObjects( geometries, _infoRender );
  12659. morphtargets = new WebGLMorphtargets( _gl );
  12660. programCache = new WebGLPrograms( _this, extensions, capabilities );
  12661. lights = new WebGLLights();
  12662. renderLists = new WebGLRenderLists();
  12663. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  12664. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12665. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12666. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, textures, capabilities );
  12667. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  12668. _this.info.programs = programCache.programs;
  12669. _this.context = _gl;
  12670. _this.capabilities = capabilities;
  12671. _this.extensions = extensions;
  12672. _this.properties = properties;
  12673. _this.renderLists = renderLists;
  12674. _this.state = state;
  12675. }
  12676. initGLContext();
  12677. // vr
  12678. var vr = new WebVRManager( _this );
  12679. this.vr = vr;
  12680. // shadow map
  12681. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  12682. this.shadowMap = shadowMap;
  12683. // API
  12684. this.getContext = function () {
  12685. return _gl;
  12686. };
  12687. this.getContextAttributes = function () {
  12688. return _gl.getContextAttributes();
  12689. };
  12690. this.forceContextLoss = function () {
  12691. var extension = extensions.get( 'WEBGL_lose_context' );
  12692. if ( extension ) extension.loseContext();
  12693. };
  12694. this.forceContextRestore = function () {
  12695. var extension = extensions.get( 'WEBGL_lose_context' );
  12696. if ( extension ) extension.restoreContext();
  12697. };
  12698. this.getPixelRatio = function () {
  12699. return _pixelRatio;
  12700. };
  12701. this.setPixelRatio = function ( value ) {
  12702. if ( value === undefined ) return;
  12703. _pixelRatio = value;
  12704. this.setSize( _width, _height, false );
  12705. };
  12706. this.getSize = function () {
  12707. return {
  12708. width: _width,
  12709. height: _height
  12710. };
  12711. };
  12712. this.setSize = function ( width, height, updateStyle ) {
  12713. var device = vr.getDevice();
  12714. if ( device && device.isPresenting ) {
  12715. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  12716. return;
  12717. }
  12718. _width = width;
  12719. _height = height;
  12720. _canvas.width = width * _pixelRatio;
  12721. _canvas.height = height * _pixelRatio;
  12722. if ( updateStyle !== false ) {
  12723. _canvas.style.width = width + 'px';
  12724. _canvas.style.height = height + 'px';
  12725. }
  12726. this.setViewport( 0, 0, width, height );
  12727. };
  12728. this.getDrawingBufferSize = function () {
  12729. return {
  12730. width: _width * _pixelRatio,
  12731. height: _height * _pixelRatio
  12732. };
  12733. };
  12734. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  12735. _width = width;
  12736. _height = height;
  12737. _pixelRatio = pixelRatio;
  12738. _canvas.width = width * pixelRatio;
  12739. _canvas.height = height * pixelRatio;
  12740. this.setViewport( 0, 0, width, height );
  12741. };
  12742. this.setViewport = function ( x, y, width, height ) {
  12743. _viewport.set( x, _height - y - height, width, height );
  12744. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12745. };
  12746. this.setScissor = function ( x, y, width, height ) {
  12747. _scissor.set( x, _height - y - height, width, height );
  12748. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12749. };
  12750. this.setScissorTest = function ( boolean ) {
  12751. state.setScissorTest( _scissorTest = boolean );
  12752. };
  12753. // Clearing
  12754. this.getClearColor = background.getClearColor;
  12755. this.setClearColor = background.setClearColor;
  12756. this.getClearAlpha = background.getClearAlpha;
  12757. this.setClearAlpha = background.setClearAlpha;
  12758. this.clear = function ( color, depth, stencil ) {
  12759. var bits = 0;
  12760. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12761. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12762. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12763. _gl.clear( bits );
  12764. };
  12765. this.clearColor = function () {
  12766. this.clear( true, false, false );
  12767. };
  12768. this.clearDepth = function () {
  12769. this.clear( false, true, false );
  12770. };
  12771. this.clearStencil = function () {
  12772. this.clear( false, false, true );
  12773. };
  12774. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12775. this.setRenderTarget( renderTarget );
  12776. this.clear( color, depth, stencil );
  12777. };
  12778. //
  12779. this.dispose = function () {
  12780. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12781. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  12782. renderLists.dispose();
  12783. vr.dispose();
  12784. };
  12785. // Events
  12786. function onContextLost( event ) {
  12787. event.preventDefault();
  12788. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  12789. _isContextLost = true;
  12790. }
  12791. function onContextRestore( event ) {
  12792. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  12793. _isContextLost = false;
  12794. initGLContext();
  12795. }
  12796. function onMaterialDispose( event ) {
  12797. var material = event.target;
  12798. material.removeEventListener( 'dispose', onMaterialDispose );
  12799. deallocateMaterial( material );
  12800. }
  12801. // Buffer deallocation
  12802. function deallocateMaterial( material ) {
  12803. releaseMaterialProgramReference( material );
  12804. properties.remove( material );
  12805. }
  12806. function releaseMaterialProgramReference( material ) {
  12807. var programInfo = properties.get( material ).program;
  12808. material.program = undefined;
  12809. if ( programInfo !== undefined ) {
  12810. programCache.releaseProgram( programInfo );
  12811. }
  12812. }
  12813. // Buffer rendering
  12814. function renderObjectImmediate( object, program, material ) {
  12815. object.render( function ( object ) {
  12816. _this.renderBufferImmediate( object, program, material );
  12817. } );
  12818. }
  12819. this.renderBufferImmediate = function ( object, program, material ) {
  12820. state.initAttributes();
  12821. var buffers = properties.get( object );
  12822. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12823. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12824. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12825. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12826. var programAttributes = program.getAttributes();
  12827. if ( object.hasPositions ) {
  12828. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12829. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12830. state.enableAttribute( programAttributes.position );
  12831. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12832. }
  12833. if ( object.hasNormals ) {
  12834. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12835. if ( ! material.isMeshPhongMaterial &&
  12836. ! material.isMeshStandardMaterial &&
  12837. ! material.isMeshNormalMaterial &&
  12838. material.flatShading === true ) {
  12839. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12840. var array = object.normalArray;
  12841. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12842. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12843. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12844. array[ i + 0 ] = nx;
  12845. array[ i + 1 ] = ny;
  12846. array[ i + 2 ] = nz;
  12847. array[ i + 3 ] = nx;
  12848. array[ i + 4 ] = ny;
  12849. array[ i + 5 ] = nz;
  12850. array[ i + 6 ] = nx;
  12851. array[ i + 7 ] = ny;
  12852. array[ i + 8 ] = nz;
  12853. }
  12854. }
  12855. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12856. state.enableAttribute( programAttributes.normal );
  12857. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12858. }
  12859. if ( object.hasUvs && material.map ) {
  12860. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12861. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12862. state.enableAttribute( programAttributes.uv );
  12863. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12864. }
  12865. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12866. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12867. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12868. state.enableAttribute( programAttributes.color );
  12869. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12870. }
  12871. state.disableUnusedAttributes();
  12872. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12873. object.count = 0;
  12874. };
  12875. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12876. state.setMaterial( material );
  12877. var program = setProgram( camera, fog, material, object );
  12878. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12879. var updateBuffers = false;
  12880. if ( geometryProgram !== _currentGeometryProgram ) {
  12881. _currentGeometryProgram = geometryProgram;
  12882. updateBuffers = true;
  12883. }
  12884. if ( object.morphTargetInfluences ) {
  12885. morphtargets.update( object, geometry, material, program );
  12886. updateBuffers = true;
  12887. }
  12888. //
  12889. var index = geometry.index;
  12890. var position = geometry.attributes.position;
  12891. var rangeFactor = 1;
  12892. if ( material.wireframe === true ) {
  12893. index = geometries.getWireframeAttribute( geometry );
  12894. rangeFactor = 2;
  12895. }
  12896. var attribute;
  12897. var renderer = bufferRenderer;
  12898. if ( index !== null ) {
  12899. attribute = attributes.get( index );
  12900. renderer = indexedBufferRenderer;
  12901. renderer.setIndex( attribute );
  12902. }
  12903. if ( updateBuffers ) {
  12904. setupVertexAttributes( material, program, geometry );
  12905. if ( index !== null ) {
  12906. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  12907. }
  12908. }
  12909. //
  12910. var dataCount = 0;
  12911. if ( index !== null ) {
  12912. dataCount = index.count;
  12913. } else if ( position !== undefined ) {
  12914. dataCount = position.count;
  12915. }
  12916. var rangeStart = geometry.drawRange.start * rangeFactor;
  12917. var rangeCount = geometry.drawRange.count * rangeFactor;
  12918. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12919. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12920. var drawStart = Math.max( rangeStart, groupStart );
  12921. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12922. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12923. if ( drawCount === 0 ) return;
  12924. //
  12925. if ( object.isMesh ) {
  12926. if ( material.wireframe === true ) {
  12927. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12928. renderer.setMode( _gl.LINES );
  12929. } else {
  12930. switch ( object.drawMode ) {
  12931. case TrianglesDrawMode:
  12932. renderer.setMode( _gl.TRIANGLES );
  12933. break;
  12934. case TriangleStripDrawMode:
  12935. renderer.setMode( _gl.TRIANGLE_STRIP );
  12936. break;
  12937. case TriangleFanDrawMode:
  12938. renderer.setMode( _gl.TRIANGLE_FAN );
  12939. break;
  12940. }
  12941. }
  12942. } else if ( object.isLine ) {
  12943. var lineWidth = material.linewidth;
  12944. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12945. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12946. if ( object.isLineSegments ) {
  12947. renderer.setMode( _gl.LINES );
  12948. } else if ( object.isLineLoop ) {
  12949. renderer.setMode( _gl.LINE_LOOP );
  12950. } else {
  12951. renderer.setMode( _gl.LINE_STRIP );
  12952. }
  12953. } else if ( object.isPoints ) {
  12954. renderer.setMode( _gl.POINTS );
  12955. }
  12956. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12957. if ( geometry.maxInstancedCount > 0 ) {
  12958. renderer.renderInstances( geometry, drawStart, drawCount );
  12959. }
  12960. } else {
  12961. renderer.render( drawStart, drawCount );
  12962. }
  12963. };
  12964. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12965. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12966. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12967. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12968. return;
  12969. }
  12970. }
  12971. if ( startIndex === undefined ) startIndex = 0;
  12972. state.initAttributes();
  12973. var geometryAttributes = geometry.attributes;
  12974. var programAttributes = program.getAttributes();
  12975. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12976. for ( var name in programAttributes ) {
  12977. var programAttribute = programAttributes[ name ];
  12978. if ( programAttribute >= 0 ) {
  12979. var geometryAttribute = geometryAttributes[ name ];
  12980. if ( geometryAttribute !== undefined ) {
  12981. var normalized = geometryAttribute.normalized;
  12982. var size = geometryAttribute.itemSize;
  12983. var attribute = attributes.get( geometryAttribute );
  12984. // TODO Attribute may not be available on context restore
  12985. if ( attribute === undefined ) continue;
  12986. var buffer = attribute.buffer;
  12987. var type = attribute.type;
  12988. var bytesPerElement = attribute.bytesPerElement;
  12989. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12990. var data = geometryAttribute.data;
  12991. var stride = data.stride;
  12992. var offset = geometryAttribute.offset;
  12993. if ( data && data.isInstancedInterleavedBuffer ) {
  12994. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12995. if ( geometry.maxInstancedCount === undefined ) {
  12996. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12997. }
  12998. } else {
  12999. state.enableAttribute( programAttribute );
  13000. }
  13001. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13002. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  13003. } else {
  13004. if ( geometryAttribute.isInstancedBufferAttribute ) {
  13005. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  13006. if ( geometry.maxInstancedCount === undefined ) {
  13007. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  13008. }
  13009. } else {
  13010. state.enableAttribute( programAttribute );
  13011. }
  13012. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13013. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  13014. }
  13015. } else if ( materialDefaultAttributeValues !== undefined ) {
  13016. var value = materialDefaultAttributeValues[ name ];
  13017. if ( value !== undefined ) {
  13018. switch ( value.length ) {
  13019. case 2:
  13020. _gl.vertexAttrib2fv( programAttribute, value );
  13021. break;
  13022. case 3:
  13023. _gl.vertexAttrib3fv( programAttribute, value );
  13024. break;
  13025. case 4:
  13026. _gl.vertexAttrib4fv( programAttribute, value );
  13027. break;
  13028. default:
  13029. _gl.vertexAttrib1fv( programAttribute, value );
  13030. }
  13031. }
  13032. }
  13033. }
  13034. }
  13035. state.disableUnusedAttributes();
  13036. }
  13037. // Compile
  13038. this.compile = function ( scene, camera ) {
  13039. lightsArray.length = 0;
  13040. shadowsArray.length = 0;
  13041. scene.traverse( function ( object ) {
  13042. if ( object.isLight ) {
  13043. lightsArray.push( object );
  13044. if ( object.castShadow ) {
  13045. shadowsArray.push( object );
  13046. }
  13047. }
  13048. } );
  13049. lights.setup( lightsArray, shadowsArray, camera );
  13050. scene.traverse( function ( object ) {
  13051. if ( object.material ) {
  13052. if ( Array.isArray( object.material ) ) {
  13053. for ( var i = 0; i < object.material.length; i ++ ) {
  13054. initMaterial( object.material[ i ], scene.fog, object );
  13055. }
  13056. } else {
  13057. initMaterial( object.material, scene.fog, object );
  13058. }
  13059. }
  13060. } );
  13061. };
  13062. // Animation Loop
  13063. var isAnimating = false;
  13064. var onAnimationFrame = null;
  13065. function start() {
  13066. if ( isAnimating ) return;
  13067. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  13068. isAnimating = true;
  13069. }
  13070. function loop( time ) {
  13071. if ( onAnimationFrame !== null ) onAnimationFrame( time );
  13072. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  13073. }
  13074. this.animate = function ( callback ) {
  13075. onAnimationFrame = callback;
  13076. start();
  13077. };
  13078. // Rendering
  13079. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13080. if ( ! ( camera && camera.isCamera ) ) {
  13081. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13082. return;
  13083. }
  13084. if ( _isContextLost ) return;
  13085. // reset caching for this frame
  13086. _currentGeometryProgram = '';
  13087. _currentMaterialId = - 1;
  13088. _currentCamera = null;
  13089. // update scene graph
  13090. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13091. // update camera matrices and frustum
  13092. if ( camera.parent === null ) camera.updateMatrixWorld();
  13093. if ( vr.enabled ) {
  13094. camera = vr.getCamera( camera );
  13095. }
  13096. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13097. _frustum.setFromMatrix( _projScreenMatrix );
  13098. lightsArray.length = 0;
  13099. shadowsArray.length = 0;
  13100. spritesArray.length = 0;
  13101. flaresArray.length = 0;
  13102. _localClippingEnabled = this.localClippingEnabled;
  13103. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  13104. currentRenderList = renderLists.get( scene, camera );
  13105. currentRenderList.init();
  13106. projectObject( scene, camera, _this.sortObjects );
  13107. if ( _this.sortObjects === true ) {
  13108. currentRenderList.sort();
  13109. }
  13110. //
  13111. if ( _clippingEnabled ) _clipping.beginShadows();
  13112. shadowMap.render( shadowsArray, scene, camera );
  13113. lights.setup( lightsArray, shadowsArray, camera );
  13114. if ( _clippingEnabled ) _clipping.endShadows();
  13115. //
  13116. _infoRender.frame ++;
  13117. _infoRender.calls = 0;
  13118. _infoRender.vertices = 0;
  13119. _infoRender.faces = 0;
  13120. _infoRender.points = 0;
  13121. if ( renderTarget === undefined ) {
  13122. renderTarget = null;
  13123. }
  13124. this.setRenderTarget( renderTarget );
  13125. //
  13126. background.render( currentRenderList, scene, camera, forceClear );
  13127. // render scene
  13128. var opaqueObjects = currentRenderList.opaque;
  13129. var transparentObjects = currentRenderList.transparent;
  13130. if ( scene.overrideMaterial ) {
  13131. var overrideMaterial = scene.overrideMaterial;
  13132. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  13133. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  13134. } else {
  13135. // opaque pass (front-to-back order)
  13136. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  13137. // transparent pass (back-to-front order)
  13138. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  13139. }
  13140. // custom renderers
  13141. spriteRenderer.render( spritesArray, scene, camera );
  13142. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  13143. // Generate mipmap if we're using any kind of mipmap filtering
  13144. if ( renderTarget ) {
  13145. textures.updateRenderTargetMipmap( renderTarget );
  13146. }
  13147. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13148. state.buffers.depth.setTest( true );
  13149. state.buffers.depth.setMask( true );
  13150. state.buffers.color.setMask( true );
  13151. state.setPolygonOffset( false );
  13152. if ( vr.enabled ) {
  13153. vr.submitFrame();
  13154. }
  13155. // _gl.finish();
  13156. };
  13157. /*
  13158. // TODO Duplicated code (Frustum)
  13159. var _sphere = new Sphere();
  13160. function isObjectViewable( object ) {
  13161. var geometry = object.geometry;
  13162. if ( geometry.boundingSphere === null )
  13163. geometry.computeBoundingSphere();
  13164. _sphere.copy( geometry.boundingSphere ).
  13165. applyMatrix4( object.matrixWorld );
  13166. return isSphereViewable( _sphere );
  13167. }
  13168. function isSpriteViewable( sprite ) {
  13169. _sphere.center.set( 0, 0, 0 );
  13170. _sphere.radius = 0.7071067811865476;
  13171. _sphere.applyMatrix4( sprite.matrixWorld );
  13172. return isSphereViewable( _sphere );
  13173. }
  13174. function isSphereViewable( sphere ) {
  13175. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  13176. var numPlanes = _clipping.numPlanes;
  13177. if ( numPlanes === 0 ) return true;
  13178. var planes = _this.clippingPlanes,
  13179. center = sphere.center,
  13180. negRad = - sphere.radius,
  13181. i = 0;
  13182. do {
  13183. // out when deeper than radius in the negative halfspace
  13184. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  13185. } while ( ++ i !== numPlanes );
  13186. return true;
  13187. }
  13188. */
  13189. function projectObject( object, camera, sortObjects ) {
  13190. if ( ! object.visible ) return;
  13191. var visible = object.layers.test( camera.layers );
  13192. if ( visible ) {
  13193. if ( object.isLight ) {
  13194. lightsArray.push( object );
  13195. if ( object.castShadow ) {
  13196. shadowsArray.push( object );
  13197. }
  13198. } else if ( object.isSprite ) {
  13199. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  13200. spritesArray.push( object );
  13201. }
  13202. } else if ( object.isLensFlare ) {
  13203. flaresArray.push( object );
  13204. } else if ( object.isImmediateRenderObject ) {
  13205. if ( sortObjects ) {
  13206. _vector3.setFromMatrixPosition( object.matrixWorld )
  13207. .applyMatrix4( _projScreenMatrix );
  13208. }
  13209. currentRenderList.push( object, null, object.material, _vector3.z, null );
  13210. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  13211. if ( object.isSkinnedMesh ) {
  13212. object.skeleton.update();
  13213. }
  13214. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  13215. if ( sortObjects ) {
  13216. _vector3.setFromMatrixPosition( object.matrixWorld )
  13217. .applyMatrix4( _projScreenMatrix );
  13218. }
  13219. var geometry = objects.update( object );
  13220. var material = object.material;
  13221. if ( Array.isArray( material ) ) {
  13222. var groups = geometry.groups;
  13223. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13224. var group = groups[ i ];
  13225. var groupMaterial = material[ group.materialIndex ];
  13226. if ( groupMaterial && groupMaterial.visible ) {
  13227. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  13228. }
  13229. }
  13230. } else if ( material.visible ) {
  13231. currentRenderList.push( object, geometry, material, _vector3.z, null );
  13232. }
  13233. }
  13234. }
  13235. }
  13236. var children = object.children;
  13237. for ( var i = 0, l = children.length; i < l; i ++ ) {
  13238. projectObject( children[ i ], camera, sortObjects );
  13239. }
  13240. }
  13241. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  13242. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  13243. var renderItem = renderList[ i ];
  13244. var object = renderItem.object;
  13245. var geometry = renderItem.geometry;
  13246. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  13247. var group = renderItem.group;
  13248. if ( camera.isArrayCamera ) {
  13249. _currentArrayCamera = camera;
  13250. var cameras = camera.cameras;
  13251. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  13252. var camera2 = cameras[ j ];
  13253. if ( object.layers.test( camera2.layers ) ) {
  13254. var bounds = camera2.bounds;
  13255. var x = bounds.x * _width;
  13256. var y = bounds.y * _height;
  13257. var width = bounds.z * _width;
  13258. var height = bounds.w * _height;
  13259. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13260. renderObject( object, scene, camera2, geometry, material, group );
  13261. }
  13262. }
  13263. } else {
  13264. _currentArrayCamera = null;
  13265. renderObject( object, scene, camera, geometry, material, group );
  13266. }
  13267. }
  13268. }
  13269. function renderObject( object, scene, camera, geometry, material, group ) {
  13270. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  13271. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13272. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  13273. if ( object.isImmediateRenderObject ) {
  13274. state.setMaterial( material );
  13275. var program = setProgram( camera, scene.fog, material, object );
  13276. _currentGeometryProgram = '';
  13277. renderObjectImmediate( object, program, material );
  13278. } else {
  13279. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  13280. }
  13281. object.onAfterRender( _this, scene, camera, geometry, material, group );
  13282. }
  13283. function initMaterial( material, fog, object ) {
  13284. var materialProperties = properties.get( material );
  13285. var parameters = programCache.getParameters(
  13286. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  13287. var code = programCache.getProgramCode( material, parameters );
  13288. var program = materialProperties.program;
  13289. var programChange = true;
  13290. if ( program === undefined ) {
  13291. // new material
  13292. material.addEventListener( 'dispose', onMaterialDispose );
  13293. } else if ( program.code !== code ) {
  13294. // changed glsl or parameters
  13295. releaseMaterialProgramReference( material );
  13296. } else if ( parameters.shaderID !== undefined ) {
  13297. // same glsl and uniform list
  13298. return;
  13299. } else {
  13300. // only rebuild uniform list
  13301. programChange = false;
  13302. }
  13303. if ( programChange ) {
  13304. if ( parameters.shaderID ) {
  13305. var shader = ShaderLib[ parameters.shaderID ];
  13306. materialProperties.shader = {
  13307. name: material.type,
  13308. uniforms: UniformsUtils.clone( shader.uniforms ),
  13309. vertexShader: shader.vertexShader,
  13310. fragmentShader: shader.fragmentShader
  13311. };
  13312. } else {
  13313. materialProperties.shader = {
  13314. name: material.type,
  13315. uniforms: material.uniforms,
  13316. vertexShader: material.vertexShader,
  13317. fragmentShader: material.fragmentShader
  13318. };
  13319. }
  13320. material.onBeforeCompile( materialProperties.shader );
  13321. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  13322. materialProperties.program = program;
  13323. material.program = program;
  13324. }
  13325. var programAttributes = program.getAttributes();
  13326. if ( material.morphTargets ) {
  13327. material.numSupportedMorphTargets = 0;
  13328. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13329. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  13330. material.numSupportedMorphTargets ++;
  13331. }
  13332. }
  13333. }
  13334. if ( material.morphNormals ) {
  13335. material.numSupportedMorphNormals = 0;
  13336. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  13337. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  13338. material.numSupportedMorphNormals ++;
  13339. }
  13340. }
  13341. }
  13342. var uniforms = materialProperties.shader.uniforms;
  13343. if ( ! material.isShaderMaterial &&
  13344. ! material.isRawShaderMaterial ||
  13345. material.clipping === true ) {
  13346. materialProperties.numClippingPlanes = _clipping.numPlanes;
  13347. materialProperties.numIntersection = _clipping.numIntersection;
  13348. uniforms.clippingPlanes = _clipping.uniform;
  13349. }
  13350. materialProperties.fog = fog;
  13351. // store the light setup it was created for
  13352. materialProperties.lightsHash = lights.state.hash;
  13353. if ( material.lights ) {
  13354. // wire up the material to this renderer's lighting state
  13355. uniforms.ambientLightColor.value = lights.state.ambient;
  13356. uniforms.directionalLights.value = lights.state.directional;
  13357. uniforms.spotLights.value = lights.state.spot;
  13358. uniforms.rectAreaLights.value = lights.state.rectArea;
  13359. uniforms.pointLights.value = lights.state.point;
  13360. uniforms.hemisphereLights.value = lights.state.hemi;
  13361. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  13362. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  13363. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  13364. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  13365. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  13366. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  13367. // TODO (abelnation): add area lights shadow info to uniforms
  13368. }
  13369. var progUniforms = materialProperties.program.getUniforms(),
  13370. uniformsList =
  13371. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  13372. materialProperties.uniformsList = uniformsList;
  13373. }
  13374. function setProgram( camera, fog, material, object ) {
  13375. _usedTextureUnits = 0;
  13376. var materialProperties = properties.get( material );
  13377. if ( _clippingEnabled ) {
  13378. if ( _localClippingEnabled || camera !== _currentCamera ) {
  13379. var useCache =
  13380. camera === _currentCamera &&
  13381. material.id === _currentMaterialId;
  13382. // we might want to call this function with some ClippingGroup
  13383. // object instead of the material, once it becomes feasible
  13384. // (#8465, #8379)
  13385. _clipping.setState(
  13386. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  13387. camera, materialProperties, useCache );
  13388. }
  13389. }
  13390. if ( material.needsUpdate === false ) {
  13391. if ( materialProperties.program === undefined ) {
  13392. material.needsUpdate = true;
  13393. } else if ( material.fog && materialProperties.fog !== fog ) {
  13394. material.needsUpdate = true;
  13395. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  13396. material.needsUpdate = true;
  13397. } else if ( materialProperties.numClippingPlanes !== undefined &&
  13398. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  13399. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  13400. material.needsUpdate = true;
  13401. }
  13402. }
  13403. if ( material.needsUpdate ) {
  13404. initMaterial( material, fog, object );
  13405. material.needsUpdate = false;
  13406. }
  13407. var refreshProgram = false;
  13408. var refreshMaterial = false;
  13409. var refreshLights = false;
  13410. var program = materialProperties.program,
  13411. p_uniforms = program.getUniforms(),
  13412. m_uniforms = materialProperties.shader.uniforms;
  13413. if ( state.useProgram( program.program ) ) {
  13414. refreshProgram = true;
  13415. refreshMaterial = true;
  13416. refreshLights = true;
  13417. }
  13418. if ( material.id !== _currentMaterialId ) {
  13419. _currentMaterialId = material.id;
  13420. refreshMaterial = true;
  13421. }
  13422. if ( refreshProgram || camera !== _currentCamera ) {
  13423. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  13424. if ( capabilities.logarithmicDepthBuffer ) {
  13425. p_uniforms.setValue( _gl, 'logDepthBufFC',
  13426. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13427. }
  13428. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  13429. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  13430. _currentCamera = ( _currentArrayCamera || camera );
  13431. // lighting uniforms depend on the camera so enforce an update
  13432. // now, in case this material supports lights - or later, when
  13433. // the next material that does gets activated:
  13434. refreshMaterial = true; // set to true on material change
  13435. refreshLights = true; // remains set until update done
  13436. }
  13437. // load material specific uniforms
  13438. // (shader material also gets them for the sake of genericity)
  13439. if ( material.isShaderMaterial ||
  13440. material.isMeshPhongMaterial ||
  13441. material.isMeshStandardMaterial ||
  13442. material.envMap ) {
  13443. var uCamPos = p_uniforms.map.cameraPosition;
  13444. if ( uCamPos !== undefined ) {
  13445. uCamPos.setValue( _gl,
  13446. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  13447. }
  13448. }
  13449. if ( material.isMeshPhongMaterial ||
  13450. material.isMeshLambertMaterial ||
  13451. material.isMeshBasicMaterial ||
  13452. material.isMeshStandardMaterial ||
  13453. material.isShaderMaterial ||
  13454. material.skinning ) {
  13455. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  13456. }
  13457. }
  13458. // skinning uniforms must be set even if material didn't change
  13459. // auto-setting of texture unit for bone texture must go before other textures
  13460. // not sure why, but otherwise weird things happen
  13461. if ( material.skinning ) {
  13462. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  13463. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  13464. var skeleton = object.skeleton;
  13465. if ( skeleton ) {
  13466. var bones = skeleton.bones;
  13467. if ( capabilities.floatVertexTextures ) {
  13468. if ( skeleton.boneTexture === undefined ) {
  13469. // layout (1 matrix = 4 pixels)
  13470. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13471. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13472. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13473. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13474. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13475. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  13476. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13477. size = Math.max( size, 4 );
  13478. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  13479. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  13480. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  13481. skeleton.boneMatrices = boneMatrices;
  13482. skeleton.boneTexture = boneTexture;
  13483. skeleton.boneTextureSize = size;
  13484. }
  13485. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  13486. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  13487. } else {
  13488. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  13489. }
  13490. }
  13491. }
  13492. if ( refreshMaterial ) {
  13493. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  13494. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  13495. if ( material.lights ) {
  13496. // the current material requires lighting info
  13497. // note: all lighting uniforms are always set correctly
  13498. // they simply reference the renderer's state for their
  13499. // values
  13500. //
  13501. // use the current material's .needsUpdate flags to set
  13502. // the GL state when required
  13503. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  13504. }
  13505. // refresh uniforms common to several materials
  13506. if ( fog && material.fog ) {
  13507. refreshUniformsFog( m_uniforms, fog );
  13508. }
  13509. if ( material.isMeshBasicMaterial ) {
  13510. refreshUniformsCommon( m_uniforms, material );
  13511. } else if ( material.isMeshLambertMaterial ) {
  13512. refreshUniformsCommon( m_uniforms, material );
  13513. refreshUniformsLambert( m_uniforms, material );
  13514. } else if ( material.isMeshPhongMaterial ) {
  13515. refreshUniformsCommon( m_uniforms, material );
  13516. if ( material.isMeshToonMaterial ) {
  13517. refreshUniformsToon( m_uniforms, material );
  13518. } else {
  13519. refreshUniformsPhong( m_uniforms, material );
  13520. }
  13521. } else if ( material.isMeshStandardMaterial ) {
  13522. refreshUniformsCommon( m_uniforms, material );
  13523. if ( material.isMeshPhysicalMaterial ) {
  13524. refreshUniformsPhysical( m_uniforms, material );
  13525. } else {
  13526. refreshUniformsStandard( m_uniforms, material );
  13527. }
  13528. } else if ( material.isMeshDepthMaterial ) {
  13529. refreshUniformsCommon( m_uniforms, material );
  13530. refreshUniformsDepth( m_uniforms, material );
  13531. } else if ( material.isMeshDistanceMaterial ) {
  13532. refreshUniformsCommon( m_uniforms, material );
  13533. refreshUniformsDistance( m_uniforms, material );
  13534. } else if ( material.isMeshNormalMaterial ) {
  13535. refreshUniformsCommon( m_uniforms, material );
  13536. refreshUniformsNormal( m_uniforms, material );
  13537. } else if ( material.isLineBasicMaterial ) {
  13538. refreshUniformsLine( m_uniforms, material );
  13539. if ( material.isLineDashedMaterial ) {
  13540. refreshUniformsDash( m_uniforms, material );
  13541. }
  13542. } else if ( material.isPointsMaterial ) {
  13543. refreshUniformsPoints( m_uniforms, material );
  13544. } else if ( material.isShadowMaterial ) {
  13545. m_uniforms.color.value = material.color;
  13546. m_uniforms.opacity.value = material.opacity;
  13547. }
  13548. // RectAreaLight Texture
  13549. // TODO (mrdoob): Find a nicer implementation
  13550. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  13551. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  13552. WebGLUniforms.upload(
  13553. _gl, materialProperties.uniformsList, m_uniforms, _this );
  13554. }
  13555. // common matrices
  13556. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  13557. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  13558. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  13559. return program;
  13560. }
  13561. // Uniforms (refresh uniforms objects)
  13562. function refreshUniformsCommon( uniforms, material ) {
  13563. uniforms.opacity.value = material.opacity;
  13564. if ( material.color ) {
  13565. uniforms.diffuse.value = material.color;
  13566. }
  13567. if ( material.emissive ) {
  13568. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13569. }
  13570. if ( material.map ) {
  13571. uniforms.map.value = material.map;
  13572. }
  13573. if ( material.alphaMap ) {
  13574. uniforms.alphaMap.value = material.alphaMap;
  13575. }
  13576. if ( material.specularMap ) {
  13577. uniforms.specularMap.value = material.specularMap;
  13578. }
  13579. if ( material.envMap ) {
  13580. uniforms.envMap.value = material.envMap;
  13581. // don't flip CubeTexture envMaps, flip everything else:
  13582. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13583. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13584. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13585. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13586. uniforms.reflectivity.value = material.reflectivity;
  13587. uniforms.refractionRatio.value = material.refractionRatio;
  13588. }
  13589. if ( material.lightMap ) {
  13590. uniforms.lightMap.value = material.lightMap;
  13591. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13592. }
  13593. if ( material.aoMap ) {
  13594. uniforms.aoMap.value = material.aoMap;
  13595. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13596. }
  13597. // uv repeat and offset setting priorities
  13598. // 1. color map
  13599. // 2. specular map
  13600. // 3. normal map
  13601. // 4. bump map
  13602. // 5. alpha map
  13603. // 6. emissive map
  13604. var uvScaleMap;
  13605. if ( material.map ) {
  13606. uvScaleMap = material.map;
  13607. } else if ( material.specularMap ) {
  13608. uvScaleMap = material.specularMap;
  13609. } else if ( material.displacementMap ) {
  13610. uvScaleMap = material.displacementMap;
  13611. } else if ( material.normalMap ) {
  13612. uvScaleMap = material.normalMap;
  13613. } else if ( material.bumpMap ) {
  13614. uvScaleMap = material.bumpMap;
  13615. } else if ( material.roughnessMap ) {
  13616. uvScaleMap = material.roughnessMap;
  13617. } else if ( material.metalnessMap ) {
  13618. uvScaleMap = material.metalnessMap;
  13619. } else if ( material.alphaMap ) {
  13620. uvScaleMap = material.alphaMap;
  13621. } else if ( material.emissiveMap ) {
  13622. uvScaleMap = material.emissiveMap;
  13623. }
  13624. if ( uvScaleMap !== undefined ) {
  13625. // backwards compatibility
  13626. if ( uvScaleMap.isWebGLRenderTarget ) {
  13627. uvScaleMap = uvScaleMap.texture;
  13628. }
  13629. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13630. var offset = uvScaleMap.offset;
  13631. var repeat = uvScaleMap.repeat;
  13632. var rotation = uvScaleMap.rotation;
  13633. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, 0.5, 0.5 );
  13634. }
  13635. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13636. }
  13637. }
  13638. function refreshUniformsLine( uniforms, material ) {
  13639. uniforms.diffuse.value = material.color;
  13640. uniforms.opacity.value = material.opacity;
  13641. }
  13642. function refreshUniformsDash( uniforms, material ) {
  13643. uniforms.dashSize.value = material.dashSize;
  13644. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13645. uniforms.scale.value = material.scale;
  13646. }
  13647. function refreshUniformsPoints( uniforms, material ) {
  13648. uniforms.diffuse.value = material.color;
  13649. uniforms.opacity.value = material.opacity;
  13650. uniforms.size.value = material.size * _pixelRatio;
  13651. uniforms.scale.value = _height * 0.5;
  13652. uniforms.map.value = material.map;
  13653. if ( material.map !== null ) {
  13654. if ( material.map.matrixAutoUpdate === true ) {
  13655. var offset = material.map.offset;
  13656. var repeat = material.map.repeat;
  13657. var rotation = material.map.rotation;
  13658. material.map.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, 0.5, 0.5 );
  13659. }
  13660. uniforms.uvTransform.value.copy( material.map.matrix );
  13661. }
  13662. }
  13663. function refreshUniformsFog( uniforms, fog ) {
  13664. uniforms.fogColor.value = fog.color;
  13665. if ( fog.isFog ) {
  13666. uniforms.fogNear.value = fog.near;
  13667. uniforms.fogFar.value = fog.far;
  13668. } else if ( fog.isFogExp2 ) {
  13669. uniforms.fogDensity.value = fog.density;
  13670. }
  13671. }
  13672. function refreshUniformsLambert( uniforms, material ) {
  13673. if ( material.emissiveMap ) {
  13674. uniforms.emissiveMap.value = material.emissiveMap;
  13675. }
  13676. }
  13677. function refreshUniformsPhong( uniforms, material ) {
  13678. uniforms.specular.value = material.specular;
  13679. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13680. if ( material.emissiveMap ) {
  13681. uniforms.emissiveMap.value = material.emissiveMap;
  13682. }
  13683. if ( material.bumpMap ) {
  13684. uniforms.bumpMap.value = material.bumpMap;
  13685. uniforms.bumpScale.value = material.bumpScale;
  13686. }
  13687. if ( material.normalMap ) {
  13688. uniforms.normalMap.value = material.normalMap;
  13689. uniforms.normalScale.value.copy( material.normalScale );
  13690. }
  13691. if ( material.displacementMap ) {
  13692. uniforms.displacementMap.value = material.displacementMap;
  13693. uniforms.displacementScale.value = material.displacementScale;
  13694. uniforms.displacementBias.value = material.displacementBias;
  13695. }
  13696. }
  13697. function refreshUniformsToon( uniforms, material ) {
  13698. refreshUniformsPhong( uniforms, material );
  13699. if ( material.gradientMap ) {
  13700. uniforms.gradientMap.value = material.gradientMap;
  13701. }
  13702. }
  13703. function refreshUniformsStandard( uniforms, material ) {
  13704. uniforms.roughness.value = material.roughness;
  13705. uniforms.metalness.value = material.metalness;
  13706. if ( material.roughnessMap ) {
  13707. uniforms.roughnessMap.value = material.roughnessMap;
  13708. }
  13709. if ( material.metalnessMap ) {
  13710. uniforms.metalnessMap.value = material.metalnessMap;
  13711. }
  13712. if ( material.emissiveMap ) {
  13713. uniforms.emissiveMap.value = material.emissiveMap;
  13714. }
  13715. if ( material.bumpMap ) {
  13716. uniforms.bumpMap.value = material.bumpMap;
  13717. uniforms.bumpScale.value = material.bumpScale;
  13718. }
  13719. if ( material.normalMap ) {
  13720. uniforms.normalMap.value = material.normalMap;
  13721. uniforms.normalScale.value.copy( material.normalScale );
  13722. }
  13723. if ( material.displacementMap ) {
  13724. uniforms.displacementMap.value = material.displacementMap;
  13725. uniforms.displacementScale.value = material.displacementScale;
  13726. uniforms.displacementBias.value = material.displacementBias;
  13727. }
  13728. if ( material.envMap ) {
  13729. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13730. uniforms.envMapIntensity.value = material.envMapIntensity;
  13731. }
  13732. }
  13733. function refreshUniformsPhysical( uniforms, material ) {
  13734. uniforms.clearCoat.value = material.clearCoat;
  13735. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13736. refreshUniformsStandard( uniforms, material );
  13737. }
  13738. function refreshUniformsDepth( uniforms, material ) {
  13739. if ( material.displacementMap ) {
  13740. uniforms.displacementMap.value = material.displacementMap;
  13741. uniforms.displacementScale.value = material.displacementScale;
  13742. uniforms.displacementBias.value = material.displacementBias;
  13743. }
  13744. }
  13745. function refreshUniformsDistance( uniforms, material ) {
  13746. if ( material.displacementMap ) {
  13747. uniforms.displacementMap.value = material.displacementMap;
  13748. uniforms.displacementScale.value = material.displacementScale;
  13749. uniforms.displacementBias.value = material.displacementBias;
  13750. }
  13751. uniforms.referencePosition.value.copy( material.referencePosition );
  13752. uniforms.nearDistance.value = material.nearDistance;
  13753. uniforms.farDistance.value = material.farDistance;
  13754. }
  13755. function refreshUniformsNormal( uniforms, material ) {
  13756. if ( material.bumpMap ) {
  13757. uniforms.bumpMap.value = material.bumpMap;
  13758. uniforms.bumpScale.value = material.bumpScale;
  13759. }
  13760. if ( material.normalMap ) {
  13761. uniforms.normalMap.value = material.normalMap;
  13762. uniforms.normalScale.value.copy( material.normalScale );
  13763. }
  13764. if ( material.displacementMap ) {
  13765. uniforms.displacementMap.value = material.displacementMap;
  13766. uniforms.displacementScale.value = material.displacementScale;
  13767. uniforms.displacementBias.value = material.displacementBias;
  13768. }
  13769. }
  13770. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13771. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13772. uniforms.ambientLightColor.needsUpdate = value;
  13773. uniforms.directionalLights.needsUpdate = value;
  13774. uniforms.pointLights.needsUpdate = value;
  13775. uniforms.spotLights.needsUpdate = value;
  13776. uniforms.rectAreaLights.needsUpdate = value;
  13777. uniforms.hemisphereLights.needsUpdate = value;
  13778. }
  13779. // GL state setting
  13780. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13781. state.setCullFace( cullFace );
  13782. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13783. };
  13784. // Textures
  13785. function allocTextureUnit() {
  13786. var textureUnit = _usedTextureUnits;
  13787. if ( textureUnit >= capabilities.maxTextures ) {
  13788. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13789. }
  13790. _usedTextureUnits += 1;
  13791. return textureUnit;
  13792. }
  13793. this.allocTextureUnit = allocTextureUnit;
  13794. // this.setTexture2D = setTexture2D;
  13795. this.setTexture2D = ( function () {
  13796. var warned = false;
  13797. // backwards compatibility: peel texture.texture
  13798. return function setTexture2D( texture, slot ) {
  13799. if ( texture && texture.isWebGLRenderTarget ) {
  13800. if ( ! warned ) {
  13801. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13802. warned = true;
  13803. }
  13804. texture = texture.texture;
  13805. }
  13806. textures.setTexture2D( texture, slot );
  13807. };
  13808. }() );
  13809. this.setTexture = ( function () {
  13810. var warned = false;
  13811. return function setTexture( texture, slot ) {
  13812. if ( ! warned ) {
  13813. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13814. warned = true;
  13815. }
  13816. textures.setTexture2D( texture, slot );
  13817. };
  13818. }() );
  13819. this.setTextureCube = ( function () {
  13820. var warned = false;
  13821. return function setTextureCube( texture, slot ) {
  13822. // backwards compatibility: peel texture.texture
  13823. if ( texture && texture.isWebGLRenderTargetCube ) {
  13824. if ( ! warned ) {
  13825. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13826. warned = true;
  13827. }
  13828. texture = texture.texture;
  13829. }
  13830. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13831. // TODO: unify these code paths
  13832. if ( ( texture && texture.isCubeTexture ) ||
  13833. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13834. // CompressedTexture can have Array in image :/
  13835. // this function alone should take care of cube textures
  13836. textures.setTextureCube( texture, slot );
  13837. } else {
  13838. // assumed: texture property of THREE.WebGLRenderTargetCube
  13839. textures.setTextureCubeDynamic( texture, slot );
  13840. }
  13841. };
  13842. }() );
  13843. this.getRenderTarget = function () {
  13844. return _currentRenderTarget;
  13845. };
  13846. this.setRenderTarget = function ( renderTarget ) {
  13847. _currentRenderTarget = renderTarget;
  13848. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13849. textures.setupRenderTarget( renderTarget );
  13850. }
  13851. var framebuffer = null;
  13852. var isCube = false;
  13853. if ( renderTarget ) {
  13854. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13855. if ( renderTarget.isWebGLRenderTargetCube ) {
  13856. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  13857. isCube = true;
  13858. } else {
  13859. framebuffer = __webglFramebuffer;
  13860. }
  13861. _currentViewport.copy( renderTarget.viewport );
  13862. _currentScissor.copy( renderTarget.scissor );
  13863. _currentScissorTest = renderTarget.scissorTest;
  13864. } else {
  13865. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13866. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13867. _currentScissorTest = _scissorTest;
  13868. }
  13869. if ( _currentFramebuffer !== framebuffer ) {
  13870. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13871. _currentFramebuffer = framebuffer;
  13872. }
  13873. state.viewport( _currentViewport );
  13874. state.scissor( _currentScissor );
  13875. state.setScissorTest( _currentScissorTest );
  13876. if ( isCube ) {
  13877. var textureProperties = properties.get( renderTarget.texture );
  13878. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13879. }
  13880. };
  13881. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13882. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  13883. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13884. return;
  13885. }
  13886. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13887. if ( framebuffer ) {
  13888. var restore = false;
  13889. if ( framebuffer !== _currentFramebuffer ) {
  13890. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13891. restore = true;
  13892. }
  13893. try {
  13894. var texture = renderTarget.texture;
  13895. var textureFormat = texture.format;
  13896. var textureType = texture.type;
  13897. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13898. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13899. return;
  13900. }
  13901. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13902. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13903. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13904. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13905. return;
  13906. }
  13907. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13908. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13909. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13910. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  13911. }
  13912. } else {
  13913. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13914. }
  13915. } finally {
  13916. if ( restore ) {
  13917. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13918. }
  13919. }
  13920. }
  13921. };
  13922. }
  13923. /**
  13924. * @author mrdoob / http://mrdoob.com/
  13925. * @author alteredq / http://alteredqualia.com/
  13926. */
  13927. function FogExp2 ( color, density ) {
  13928. this.name = '';
  13929. this.color = new Color( color );
  13930. this.density = ( density !== undefined ) ? density : 0.00025;
  13931. }
  13932. FogExp2.prototype.isFogExp2 = true;
  13933. FogExp2.prototype.clone = function () {
  13934. return new FogExp2( this.color.getHex(), this.density );
  13935. };
  13936. FogExp2.prototype.toJSON = function ( meta ) {
  13937. return {
  13938. type: 'FogExp2',
  13939. color: this.color.getHex(),
  13940. density: this.density
  13941. };
  13942. };
  13943. /**
  13944. * @author mrdoob / http://mrdoob.com/
  13945. * @author alteredq / http://alteredqualia.com/
  13946. */
  13947. function Fog ( color, near, far ) {
  13948. this.name = '';
  13949. this.color = new Color( color );
  13950. this.near = ( near !== undefined ) ? near : 1;
  13951. this.far = ( far !== undefined ) ? far : 1000;
  13952. }
  13953. Fog.prototype.isFog = true;
  13954. Fog.prototype.clone = function () {
  13955. return new Fog( this.color.getHex(), this.near, this.far );
  13956. };
  13957. Fog.prototype.toJSON = function ( meta ) {
  13958. return {
  13959. type: 'Fog',
  13960. color: this.color.getHex(),
  13961. near: this.near,
  13962. far: this.far
  13963. };
  13964. };
  13965. /**
  13966. * @author mrdoob / http://mrdoob.com/
  13967. */
  13968. function Scene () {
  13969. Object3D.call( this );
  13970. this.type = 'Scene';
  13971. this.background = null;
  13972. this.fog = null;
  13973. this.overrideMaterial = null;
  13974. this.autoUpdate = true; // checked by the renderer
  13975. }
  13976. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13977. constructor: Scene,
  13978. copy: function ( source, recursive ) {
  13979. Object3D.prototype.copy.call( this, source, recursive );
  13980. if ( source.background !== null ) this.background = source.background.clone();
  13981. if ( source.fog !== null ) this.fog = source.fog.clone();
  13982. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13983. this.autoUpdate = source.autoUpdate;
  13984. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13985. return this;
  13986. },
  13987. toJSON: function ( meta ) {
  13988. var data = Object3D.prototype.toJSON.call( this, meta );
  13989. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13990. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13991. return data;
  13992. }
  13993. } );
  13994. /**
  13995. * @author mikael emtinger / http://gomo.se/
  13996. * @author alteredq / http://alteredqualia.com/
  13997. */
  13998. function LensFlare( texture, size, distance, blending, color ) {
  13999. Object3D.call( this );
  14000. this.lensFlares = [];
  14001. this.positionScreen = new Vector3();
  14002. this.customUpdateCallback = undefined;
  14003. if ( texture !== undefined ) {
  14004. this.add( texture, size, distance, blending, color );
  14005. }
  14006. }
  14007. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14008. constructor: LensFlare,
  14009. isLensFlare: true,
  14010. copy: function ( source ) {
  14011. Object3D.prototype.copy.call( this, source );
  14012. this.positionScreen.copy( source.positionScreen );
  14013. this.customUpdateCallback = source.customUpdateCallback;
  14014. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  14015. this.lensFlares.push( source.lensFlares[ i ] );
  14016. }
  14017. return this;
  14018. },
  14019. add: function ( texture, size, distance, blending, color, opacity ) {
  14020. if ( size === undefined ) size = - 1;
  14021. if ( distance === undefined ) distance = 0;
  14022. if ( opacity === undefined ) opacity = 1;
  14023. if ( color === undefined ) color = new Color( 0xffffff );
  14024. if ( blending === undefined ) blending = NormalBlending;
  14025. distance = Math.min( distance, Math.max( 0, distance ) );
  14026. this.lensFlares.push( {
  14027. texture: texture, // THREE.Texture
  14028. size: size, // size in pixels (-1 = use texture.width)
  14029. distance: distance, // distance (0-1) from light source (0=at light source)
  14030. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  14031. scale: 1, // scale
  14032. rotation: 0, // rotation
  14033. opacity: opacity, // opacity
  14034. color: color, // color
  14035. blending: blending // blending
  14036. } );
  14037. },
  14038. /*
  14039. * Update lens flares update positions on all flares based on the screen position
  14040. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  14041. */
  14042. updateLensFlares: function () {
  14043. var f, fl = this.lensFlares.length;
  14044. var flare;
  14045. var vecX = - this.positionScreen.x * 2;
  14046. var vecY = - this.positionScreen.y * 2;
  14047. for ( f = 0; f < fl; f ++ ) {
  14048. flare = this.lensFlares[ f ];
  14049. flare.x = this.positionScreen.x + vecX * flare.distance;
  14050. flare.y = this.positionScreen.y + vecY * flare.distance;
  14051. flare.wantedRotation = flare.x * Math.PI * 0.25;
  14052. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  14053. }
  14054. }
  14055. } );
  14056. /**
  14057. * @author alteredq / http://alteredqualia.com/
  14058. *
  14059. * parameters = {
  14060. * color: <hex>,
  14061. * opacity: <float>,
  14062. * map: new THREE.Texture( <Image> ),
  14063. *
  14064. * uvOffset: new THREE.Vector2(),
  14065. * uvScale: new THREE.Vector2()
  14066. * }
  14067. */
  14068. function SpriteMaterial( parameters ) {
  14069. Material.call( this );
  14070. this.type = 'SpriteMaterial';
  14071. this.color = new Color( 0xffffff );
  14072. this.map = null;
  14073. this.rotation = 0;
  14074. this.fog = false;
  14075. this.lights = false;
  14076. this.setValues( parameters );
  14077. }
  14078. SpriteMaterial.prototype = Object.create( Material.prototype );
  14079. SpriteMaterial.prototype.constructor = SpriteMaterial;
  14080. SpriteMaterial.prototype.isSpriteMaterial = true;
  14081. SpriteMaterial.prototype.copy = function ( source ) {
  14082. Material.prototype.copy.call( this, source );
  14083. this.color.copy( source.color );
  14084. this.map = source.map;
  14085. this.rotation = source.rotation;
  14086. return this;
  14087. };
  14088. /**
  14089. * @author mikael emtinger / http://gomo.se/
  14090. * @author alteredq / http://alteredqualia.com/
  14091. */
  14092. function Sprite( material ) {
  14093. Object3D.call( this );
  14094. this.type = 'Sprite';
  14095. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  14096. }
  14097. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14098. constructor: Sprite,
  14099. isSprite: true,
  14100. raycast: ( function () {
  14101. var intersectPoint = new Vector3();
  14102. var worldPosition = new Vector3();
  14103. var worldScale = new Vector3();
  14104. return function raycast( raycaster, intersects ) {
  14105. worldPosition.setFromMatrixPosition( this.matrixWorld );
  14106. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  14107. worldScale.setFromMatrixScale( this.matrixWorld );
  14108. var guessSizeSq = worldScale.x * worldScale.y / 4;
  14109. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  14110. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14111. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14112. intersects.push( {
  14113. distance: distance,
  14114. point: intersectPoint.clone(),
  14115. face: null,
  14116. object: this
  14117. } );
  14118. };
  14119. }() ),
  14120. clone: function () {
  14121. return new this.constructor( this.material ).copy( this );
  14122. }
  14123. } );
  14124. /**
  14125. * @author mikael emtinger / http://gomo.se/
  14126. * @author alteredq / http://alteredqualia.com/
  14127. * @author mrdoob / http://mrdoob.com/
  14128. */
  14129. function LOD() {
  14130. Object3D.call( this );
  14131. this.type = 'LOD';
  14132. Object.defineProperties( this, {
  14133. levels: {
  14134. enumerable: true,
  14135. value: []
  14136. }
  14137. } );
  14138. }
  14139. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14140. constructor: LOD,
  14141. copy: function ( source ) {
  14142. Object3D.prototype.copy.call( this, source, false );
  14143. var levels = source.levels;
  14144. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14145. var level = levels[ i ];
  14146. this.addLevel( level.object.clone(), level.distance );
  14147. }
  14148. return this;
  14149. },
  14150. addLevel: function ( object, distance ) {
  14151. if ( distance === undefined ) distance = 0;
  14152. distance = Math.abs( distance );
  14153. var levels = this.levels;
  14154. for ( var l = 0; l < levels.length; l ++ ) {
  14155. if ( distance < levels[ l ].distance ) {
  14156. break;
  14157. }
  14158. }
  14159. levels.splice( l, 0, { distance: distance, object: object } );
  14160. this.add( object );
  14161. },
  14162. getObjectForDistance: function ( distance ) {
  14163. var levels = this.levels;
  14164. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14165. if ( distance < levels[ i ].distance ) {
  14166. break;
  14167. }
  14168. }
  14169. return levels[ i - 1 ].object;
  14170. },
  14171. raycast: ( function () {
  14172. var matrixPosition = new Vector3();
  14173. return function raycast( raycaster, intersects ) {
  14174. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  14175. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  14176. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14177. };
  14178. }() ),
  14179. update: function () {
  14180. var v1 = new Vector3();
  14181. var v2 = new Vector3();
  14182. return function update( camera ) {
  14183. var levels = this.levels;
  14184. if ( levels.length > 1 ) {
  14185. v1.setFromMatrixPosition( camera.matrixWorld );
  14186. v2.setFromMatrixPosition( this.matrixWorld );
  14187. var distance = v1.distanceTo( v2 );
  14188. levels[ 0 ].object.visible = true;
  14189. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14190. if ( distance >= levels[ i ].distance ) {
  14191. levels[ i - 1 ].object.visible = false;
  14192. levels[ i ].object.visible = true;
  14193. } else {
  14194. break;
  14195. }
  14196. }
  14197. for ( ; i < l; i ++ ) {
  14198. levels[ i ].object.visible = false;
  14199. }
  14200. }
  14201. };
  14202. }(),
  14203. toJSON: function ( meta ) {
  14204. var data = Object3D.prototype.toJSON.call( this, meta );
  14205. data.object.levels = [];
  14206. var levels = this.levels;
  14207. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14208. var level = levels[ i ];
  14209. data.object.levels.push( {
  14210. object: level.object.uuid,
  14211. distance: level.distance
  14212. } );
  14213. }
  14214. return data;
  14215. }
  14216. } );
  14217. /**
  14218. * @author mikael emtinger / http://gomo.se/
  14219. * @author alteredq / http://alteredqualia.com/
  14220. * @author michael guerrero / http://realitymeltdown.com
  14221. * @author ikerr / http://verold.com
  14222. */
  14223. function Skeleton( bones, boneInverses ) {
  14224. // copy the bone array
  14225. bones = bones || [];
  14226. this.bones = bones.slice( 0 );
  14227. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  14228. // use the supplied bone inverses or calculate the inverses
  14229. if ( boneInverses === undefined ) {
  14230. this.calculateInverses();
  14231. } else {
  14232. if ( this.bones.length === boneInverses.length ) {
  14233. this.boneInverses = boneInverses.slice( 0 );
  14234. } else {
  14235. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  14236. this.boneInverses = [];
  14237. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14238. this.boneInverses.push( new Matrix4() );
  14239. }
  14240. }
  14241. }
  14242. }
  14243. Object.assign( Skeleton.prototype, {
  14244. calculateInverses: function () {
  14245. this.boneInverses = [];
  14246. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14247. var inverse = new Matrix4();
  14248. if ( this.bones[ i ] ) {
  14249. inverse.getInverse( this.bones[ i ].matrixWorld );
  14250. }
  14251. this.boneInverses.push( inverse );
  14252. }
  14253. },
  14254. pose: function () {
  14255. var bone, i, il;
  14256. // recover the bind-time world matrices
  14257. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14258. bone = this.bones[ i ];
  14259. if ( bone ) {
  14260. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  14261. }
  14262. }
  14263. // compute the local matrices, positions, rotations and scales
  14264. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14265. bone = this.bones[ i ];
  14266. if ( bone ) {
  14267. if ( bone.parent && bone.parent.isBone ) {
  14268. bone.matrix.getInverse( bone.parent.matrixWorld );
  14269. bone.matrix.multiply( bone.matrixWorld );
  14270. } else {
  14271. bone.matrix.copy( bone.matrixWorld );
  14272. }
  14273. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14274. }
  14275. }
  14276. },
  14277. update: ( function () {
  14278. var offsetMatrix = new Matrix4();
  14279. var identityMatrix = new Matrix4();
  14280. return function update() {
  14281. var bones = this.bones;
  14282. var boneInverses = this.boneInverses;
  14283. var boneMatrices = this.boneMatrices;
  14284. var boneTexture = this.boneTexture;
  14285. // flatten bone matrices to array
  14286. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  14287. // compute the offset between the current and the original transform
  14288. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  14289. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14290. offsetMatrix.toArray( boneMatrices, i * 16 );
  14291. }
  14292. if ( boneTexture !== undefined ) {
  14293. boneTexture.needsUpdate = true;
  14294. }
  14295. };
  14296. } )(),
  14297. clone: function () {
  14298. return new Skeleton( this.bones, this.boneInverses );
  14299. }
  14300. } );
  14301. /**
  14302. * @author mikael emtinger / http://gomo.se/
  14303. * @author alteredq / http://alteredqualia.com/
  14304. * @author ikerr / http://verold.com
  14305. */
  14306. function Bone() {
  14307. Object3D.call( this );
  14308. this.type = 'Bone';
  14309. }
  14310. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14311. constructor: Bone,
  14312. isBone: true
  14313. } );
  14314. /**
  14315. * @author mikael emtinger / http://gomo.se/
  14316. * @author alteredq / http://alteredqualia.com/
  14317. * @author ikerr / http://verold.com
  14318. */
  14319. function SkinnedMesh( geometry, material ) {
  14320. Mesh.call( this, geometry, material );
  14321. this.type = 'SkinnedMesh';
  14322. this.bindMode = 'attached';
  14323. this.bindMatrix = new Matrix4();
  14324. this.bindMatrixInverse = new Matrix4();
  14325. var bones = this.initBones();
  14326. var skeleton = new Skeleton( bones );
  14327. this.bind( skeleton, this.matrixWorld );
  14328. this.normalizeSkinWeights();
  14329. }
  14330. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  14331. constructor: SkinnedMesh,
  14332. isSkinnedMesh: true,
  14333. initBones: function () {
  14334. var bones = [], bone, gbone;
  14335. var i, il;
  14336. if ( this.geometry && this.geometry.bones !== undefined ) {
  14337. // first, create array of 'Bone' objects from geometry data
  14338. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14339. gbone = this.geometry.bones[ i ];
  14340. // create new 'Bone' object
  14341. bone = new Bone();
  14342. bones.push( bone );
  14343. // apply values
  14344. bone.name = gbone.name;
  14345. bone.position.fromArray( gbone.pos );
  14346. bone.quaternion.fromArray( gbone.rotq );
  14347. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  14348. }
  14349. // second, create bone hierarchy
  14350. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14351. gbone = this.geometry.bones[ i ];
  14352. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  14353. // subsequent bones in the hierarchy
  14354. bones[ gbone.parent ].add( bones[ i ] );
  14355. } else {
  14356. // topmost bone, immediate child of the skinned mesh
  14357. this.add( bones[ i ] );
  14358. }
  14359. }
  14360. }
  14361. // now the bones are part of the scene graph and children of the skinned mesh.
  14362. // let's update the corresponding matrices
  14363. this.updateMatrixWorld( true );
  14364. return bones;
  14365. },
  14366. bind: function ( skeleton, bindMatrix ) {
  14367. this.skeleton = skeleton;
  14368. if ( bindMatrix === undefined ) {
  14369. this.updateMatrixWorld( true );
  14370. this.skeleton.calculateInverses();
  14371. bindMatrix = this.matrixWorld;
  14372. }
  14373. this.bindMatrix.copy( bindMatrix );
  14374. this.bindMatrixInverse.getInverse( bindMatrix );
  14375. },
  14376. pose: function () {
  14377. this.skeleton.pose();
  14378. },
  14379. normalizeSkinWeights: function () {
  14380. var scale, i;
  14381. if ( this.geometry && this.geometry.isGeometry ) {
  14382. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  14383. var sw = this.geometry.skinWeights[ i ];
  14384. scale = 1.0 / sw.lengthManhattan();
  14385. if ( scale !== Infinity ) {
  14386. sw.multiplyScalar( scale );
  14387. } else {
  14388. sw.set( 1, 0, 0, 0 ); // do something reasonable
  14389. }
  14390. }
  14391. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  14392. var vec = new Vector4();
  14393. var skinWeight = this.geometry.attributes.skinWeight;
  14394. for ( i = 0; i < skinWeight.count; i ++ ) {
  14395. vec.x = skinWeight.getX( i );
  14396. vec.y = skinWeight.getY( i );
  14397. vec.z = skinWeight.getZ( i );
  14398. vec.w = skinWeight.getW( i );
  14399. scale = 1.0 / vec.lengthManhattan();
  14400. if ( scale !== Infinity ) {
  14401. vec.multiplyScalar( scale );
  14402. } else {
  14403. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14404. }
  14405. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14406. }
  14407. }
  14408. },
  14409. updateMatrixWorld: function ( force ) {
  14410. Mesh.prototype.updateMatrixWorld.call( this, force );
  14411. if ( this.bindMode === 'attached' ) {
  14412. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14413. } else if ( this.bindMode === 'detached' ) {
  14414. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14415. } else {
  14416. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14417. }
  14418. },
  14419. clone: function () {
  14420. return new this.constructor( this.geometry, this.material ).copy( this );
  14421. }
  14422. } );
  14423. /**
  14424. * @author mrdoob / http://mrdoob.com/
  14425. * @author alteredq / http://alteredqualia.com/
  14426. *
  14427. * parameters = {
  14428. * color: <hex>,
  14429. * opacity: <float>,
  14430. *
  14431. * linewidth: <float>,
  14432. * linecap: "round",
  14433. * linejoin: "round"
  14434. * }
  14435. */
  14436. function LineBasicMaterial( parameters ) {
  14437. Material.call( this );
  14438. this.type = 'LineBasicMaterial';
  14439. this.color = new Color( 0xffffff );
  14440. this.linewidth = 1;
  14441. this.linecap = 'round';
  14442. this.linejoin = 'round';
  14443. this.lights = false;
  14444. this.setValues( parameters );
  14445. }
  14446. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14447. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14448. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14449. LineBasicMaterial.prototype.copy = function ( source ) {
  14450. Material.prototype.copy.call( this, source );
  14451. this.color.copy( source.color );
  14452. this.linewidth = source.linewidth;
  14453. this.linecap = source.linecap;
  14454. this.linejoin = source.linejoin;
  14455. return this;
  14456. };
  14457. /**
  14458. * @author mrdoob / http://mrdoob.com/
  14459. */
  14460. function Line( geometry, material, mode ) {
  14461. if ( mode === 1 ) {
  14462. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14463. return new LineSegments( geometry, material );
  14464. }
  14465. Object3D.call( this );
  14466. this.type = 'Line';
  14467. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14468. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14469. }
  14470. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14471. constructor: Line,
  14472. isLine: true,
  14473. raycast: ( function () {
  14474. var inverseMatrix = new Matrix4();
  14475. var ray = new Ray();
  14476. var sphere = new Sphere();
  14477. return function raycast( raycaster, intersects ) {
  14478. var precision = raycaster.linePrecision;
  14479. var precisionSq = precision * precision;
  14480. var geometry = this.geometry;
  14481. var matrixWorld = this.matrixWorld;
  14482. // Checking boundingSphere distance to ray
  14483. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14484. sphere.copy( geometry.boundingSphere );
  14485. sphere.applyMatrix4( matrixWorld );
  14486. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14487. //
  14488. inverseMatrix.getInverse( matrixWorld );
  14489. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14490. var vStart = new Vector3();
  14491. var vEnd = new Vector3();
  14492. var interSegment = new Vector3();
  14493. var interRay = new Vector3();
  14494. var step = (this && this.isLineSegments) ? 2 : 1;
  14495. if ( geometry.isBufferGeometry ) {
  14496. var index = geometry.index;
  14497. var attributes = geometry.attributes;
  14498. var positions = attributes.position.array;
  14499. if ( index !== null ) {
  14500. var indices = index.array;
  14501. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14502. var a = indices[ i ];
  14503. var b = indices[ i + 1 ];
  14504. vStart.fromArray( positions, a * 3 );
  14505. vEnd.fromArray( positions, b * 3 );
  14506. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14507. if ( distSq > precisionSq ) continue;
  14508. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14509. var distance = raycaster.ray.origin.distanceTo( interRay );
  14510. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14511. intersects.push( {
  14512. distance: distance,
  14513. // What do we want? intersection point on the ray or on the segment??
  14514. // point: raycaster.ray.at( distance ),
  14515. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14516. index: i,
  14517. face: null,
  14518. faceIndex: null,
  14519. object: this
  14520. } );
  14521. }
  14522. } else {
  14523. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14524. vStart.fromArray( positions, 3 * i );
  14525. vEnd.fromArray( positions, 3 * i + 3 );
  14526. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14527. if ( distSq > precisionSq ) continue;
  14528. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14529. var distance = raycaster.ray.origin.distanceTo( interRay );
  14530. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14531. intersects.push( {
  14532. distance: distance,
  14533. // What do we want? intersection point on the ray or on the segment??
  14534. // point: raycaster.ray.at( distance ),
  14535. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14536. index: i,
  14537. face: null,
  14538. faceIndex: null,
  14539. object: this
  14540. } );
  14541. }
  14542. }
  14543. } else if ( geometry.isGeometry ) {
  14544. var vertices = geometry.vertices;
  14545. var nbVertices = vertices.length;
  14546. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14547. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14548. if ( distSq > precisionSq ) continue;
  14549. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14550. var distance = raycaster.ray.origin.distanceTo( interRay );
  14551. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14552. intersects.push( {
  14553. distance: distance,
  14554. // What do we want? intersection point on the ray or on the segment??
  14555. // point: raycaster.ray.at( distance ),
  14556. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14557. index: i,
  14558. face: null,
  14559. faceIndex: null,
  14560. object: this
  14561. } );
  14562. }
  14563. }
  14564. };
  14565. }() ),
  14566. clone: function () {
  14567. return new this.constructor( this.geometry, this.material ).copy( this );
  14568. }
  14569. } );
  14570. /**
  14571. * @author mrdoob / http://mrdoob.com/
  14572. */
  14573. function LineSegments( geometry, material ) {
  14574. Line.call( this, geometry, material );
  14575. this.type = 'LineSegments';
  14576. }
  14577. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14578. constructor: LineSegments,
  14579. isLineSegments: true
  14580. } );
  14581. /**
  14582. * @author mgreter / http://github.com/mgreter
  14583. */
  14584. function LineLoop( geometry, material ) {
  14585. Line.call( this, geometry, material );
  14586. this.type = 'LineLoop';
  14587. }
  14588. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14589. constructor: LineLoop,
  14590. isLineLoop: true,
  14591. } );
  14592. /**
  14593. * @author mrdoob / http://mrdoob.com/
  14594. * @author alteredq / http://alteredqualia.com/
  14595. *
  14596. * parameters = {
  14597. * color: <hex>,
  14598. * opacity: <float>,
  14599. * map: new THREE.Texture( <Image> ),
  14600. *
  14601. * size: <float>,
  14602. * sizeAttenuation: <bool>
  14603. * }
  14604. */
  14605. function PointsMaterial( parameters ) {
  14606. Material.call( this );
  14607. this.type = 'PointsMaterial';
  14608. this.color = new Color( 0xffffff );
  14609. this.map = null;
  14610. this.size = 1;
  14611. this.sizeAttenuation = true;
  14612. this.lights = false;
  14613. this.setValues( parameters );
  14614. }
  14615. PointsMaterial.prototype = Object.create( Material.prototype );
  14616. PointsMaterial.prototype.constructor = PointsMaterial;
  14617. PointsMaterial.prototype.isPointsMaterial = true;
  14618. PointsMaterial.prototype.copy = function ( source ) {
  14619. Material.prototype.copy.call( this, source );
  14620. this.color.copy( source.color );
  14621. this.map = source.map;
  14622. this.size = source.size;
  14623. this.sizeAttenuation = source.sizeAttenuation;
  14624. return this;
  14625. };
  14626. /**
  14627. * @author alteredq / http://alteredqualia.com/
  14628. */
  14629. function Points( geometry, material ) {
  14630. Object3D.call( this );
  14631. this.type = 'Points';
  14632. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14633. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14634. }
  14635. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14636. constructor: Points,
  14637. isPoints: true,
  14638. raycast: ( function () {
  14639. var inverseMatrix = new Matrix4();
  14640. var ray = new Ray();
  14641. var sphere = new Sphere();
  14642. return function raycast( raycaster, intersects ) {
  14643. var object = this;
  14644. var geometry = this.geometry;
  14645. var matrixWorld = this.matrixWorld;
  14646. var threshold = raycaster.params.Points.threshold;
  14647. // Checking boundingSphere distance to ray
  14648. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14649. sphere.copy( geometry.boundingSphere );
  14650. sphere.applyMatrix4( matrixWorld );
  14651. sphere.radius += threshold;
  14652. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14653. //
  14654. inverseMatrix.getInverse( matrixWorld );
  14655. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14656. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14657. var localThresholdSq = localThreshold * localThreshold;
  14658. var position = new Vector3();
  14659. function testPoint( point, index ) {
  14660. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14661. if ( rayPointDistanceSq < localThresholdSq ) {
  14662. var intersectPoint = ray.closestPointToPoint( point );
  14663. intersectPoint.applyMatrix4( matrixWorld );
  14664. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14665. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14666. intersects.push( {
  14667. distance: distance,
  14668. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14669. point: intersectPoint.clone(),
  14670. index: index,
  14671. face: null,
  14672. object: object
  14673. } );
  14674. }
  14675. }
  14676. if ( geometry.isBufferGeometry ) {
  14677. var index = geometry.index;
  14678. var attributes = geometry.attributes;
  14679. var positions = attributes.position.array;
  14680. if ( index !== null ) {
  14681. var indices = index.array;
  14682. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14683. var a = indices[ i ];
  14684. position.fromArray( positions, a * 3 );
  14685. testPoint( position, a );
  14686. }
  14687. } else {
  14688. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14689. position.fromArray( positions, i * 3 );
  14690. testPoint( position, i );
  14691. }
  14692. }
  14693. } else {
  14694. var vertices = geometry.vertices;
  14695. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14696. testPoint( vertices[ i ], i );
  14697. }
  14698. }
  14699. };
  14700. }() ),
  14701. clone: function () {
  14702. return new this.constructor( this.geometry, this.material ).copy( this );
  14703. }
  14704. } );
  14705. /**
  14706. * @author mrdoob / http://mrdoob.com/
  14707. */
  14708. function Group() {
  14709. Object3D.call( this );
  14710. this.type = 'Group';
  14711. }
  14712. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14713. constructor: Group
  14714. } );
  14715. /**
  14716. * @author mrdoob / http://mrdoob.com/
  14717. */
  14718. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14719. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14720. this.generateMipmaps = false;
  14721. var scope = this;
  14722. function update() {
  14723. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14724. scope.needsUpdate = true;
  14725. }
  14726. requestAnimationFrame( update );
  14727. }
  14728. requestAnimationFrame( update );
  14729. }
  14730. VideoTexture.prototype = Object.create( Texture.prototype );
  14731. VideoTexture.prototype.constructor = VideoTexture;
  14732. /**
  14733. * @author alteredq / http://alteredqualia.com/
  14734. */
  14735. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14736. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14737. this.image = { width: width, height: height };
  14738. this.mipmaps = mipmaps;
  14739. // no flipping for cube textures
  14740. // (also flipping doesn't work for compressed textures )
  14741. this.flipY = false;
  14742. // can't generate mipmaps for compressed textures
  14743. // mips must be embedded in DDS files
  14744. this.generateMipmaps = false;
  14745. }
  14746. CompressedTexture.prototype = Object.create( Texture.prototype );
  14747. CompressedTexture.prototype.constructor = CompressedTexture;
  14748. CompressedTexture.prototype.isCompressedTexture = true;
  14749. /**
  14750. * @author Matt DesLauriers / @mattdesl
  14751. * @author atix / arthursilber.de
  14752. */
  14753. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14754. format = format !== undefined ? format : DepthFormat;
  14755. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14756. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14757. }
  14758. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14759. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14760. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14761. this.image = { width: width, height: height };
  14762. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14763. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14764. this.flipY = false;
  14765. this.generateMipmaps = false;
  14766. }
  14767. DepthTexture.prototype = Object.create( Texture.prototype );
  14768. DepthTexture.prototype.constructor = DepthTexture;
  14769. DepthTexture.prototype.isDepthTexture = true;
  14770. /**
  14771. * @author mrdoob / http://mrdoob.com/
  14772. * @author Mugen87 / https://github.com/Mugen87
  14773. */
  14774. function WireframeGeometry( geometry ) {
  14775. BufferGeometry.call( this );
  14776. this.type = 'WireframeGeometry';
  14777. // buffer
  14778. var vertices = [];
  14779. // helper variables
  14780. var i, j, l, o, ol;
  14781. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14782. var key, keys = [ 'a', 'b', 'c' ];
  14783. var vertex;
  14784. // different logic for Geometry and BufferGeometry
  14785. if ( geometry && geometry.isGeometry ) {
  14786. // create a data structure that contains all edges without duplicates
  14787. var faces = geometry.faces;
  14788. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14789. var face = faces[ i ];
  14790. for ( j = 0; j < 3; j ++ ) {
  14791. edge1 = face[ keys[ j ] ];
  14792. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14793. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14794. edge[ 1 ] = Math.max( edge1, edge2 );
  14795. key = edge[ 0 ] + ',' + edge[ 1 ];
  14796. if ( edges[ key ] === undefined ) {
  14797. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14798. }
  14799. }
  14800. }
  14801. // generate vertices
  14802. for ( key in edges ) {
  14803. e = edges[ key ];
  14804. vertex = geometry.vertices[ e.index1 ];
  14805. vertices.push( vertex.x, vertex.y, vertex.z );
  14806. vertex = geometry.vertices[ e.index2 ];
  14807. vertices.push( vertex.x, vertex.y, vertex.z );
  14808. }
  14809. } else if ( geometry && geometry.isBufferGeometry ) {
  14810. var position, indices, groups;
  14811. var group, start, count;
  14812. var index1, index2;
  14813. vertex = new Vector3();
  14814. if ( geometry.index !== null ) {
  14815. // indexed BufferGeometry
  14816. position = geometry.attributes.position;
  14817. indices = geometry.index;
  14818. groups = geometry.groups;
  14819. if ( groups.length === 0 ) {
  14820. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14821. }
  14822. // create a data structure that contains all eges without duplicates
  14823. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14824. group = groups[ o ];
  14825. start = group.start;
  14826. count = group.count;
  14827. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14828. for ( j = 0; j < 3; j ++ ) {
  14829. edge1 = indices.getX( i + j );
  14830. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14831. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14832. edge[ 1 ] = Math.max( edge1, edge2 );
  14833. key = edge[ 0 ] + ',' + edge[ 1 ];
  14834. if ( edges[ key ] === undefined ) {
  14835. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14836. }
  14837. }
  14838. }
  14839. }
  14840. // generate vertices
  14841. for ( key in edges ) {
  14842. e = edges[ key ];
  14843. vertex.fromBufferAttribute( position, e.index1 );
  14844. vertices.push( vertex.x, vertex.y, vertex.z );
  14845. vertex.fromBufferAttribute( position, e.index2 );
  14846. vertices.push( vertex.x, vertex.y, vertex.z );
  14847. }
  14848. } else {
  14849. // non-indexed BufferGeometry
  14850. position = geometry.attributes.position;
  14851. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14852. for ( j = 0; j < 3; j ++ ) {
  14853. // three edges per triangle, an edge is represented as (index1, index2)
  14854. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14855. index1 = 3 * i + j;
  14856. vertex.fromBufferAttribute( position, index1 );
  14857. vertices.push( vertex.x, vertex.y, vertex.z );
  14858. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14859. vertex.fromBufferAttribute( position, index2 );
  14860. vertices.push( vertex.x, vertex.y, vertex.z );
  14861. }
  14862. }
  14863. }
  14864. }
  14865. // build geometry
  14866. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14867. }
  14868. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14869. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14870. /**
  14871. * @author zz85 / https://github.com/zz85
  14872. * @author Mugen87 / https://github.com/Mugen87
  14873. *
  14874. * Parametric Surfaces Geometry
  14875. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14876. */
  14877. // ParametricGeometry
  14878. function ParametricGeometry( func, slices, stacks ) {
  14879. Geometry.call( this );
  14880. this.type = 'ParametricGeometry';
  14881. this.parameters = {
  14882. func: func,
  14883. slices: slices,
  14884. stacks: stacks
  14885. };
  14886. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14887. this.mergeVertices();
  14888. }
  14889. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14890. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14891. // ParametricBufferGeometry
  14892. function ParametricBufferGeometry( func, slices, stacks ) {
  14893. BufferGeometry.call( this );
  14894. this.type = 'ParametricBufferGeometry';
  14895. this.parameters = {
  14896. func: func,
  14897. slices: slices,
  14898. stacks: stacks
  14899. };
  14900. // buffers
  14901. var indices = [];
  14902. var vertices = [];
  14903. var normals = [];
  14904. var uvs = [];
  14905. var EPS = 0.00001;
  14906. var normal = new Vector3();
  14907. var p0 = new Vector3(), p1 = new Vector3();
  14908. var pu = new Vector3(), pv = new Vector3();
  14909. var i, j;
  14910. // generate vertices, normals and uvs
  14911. var sliceCount = slices + 1;
  14912. for ( i = 0; i <= stacks; i ++ ) {
  14913. var v = i / stacks;
  14914. for ( j = 0; j <= slices; j ++ ) {
  14915. var u = j / slices;
  14916. // vertex
  14917. p0 = func( u, v, p0 );
  14918. vertices.push( p0.x, p0.y, p0.z );
  14919. // normal
  14920. // approximate tangent vectors via finite differences
  14921. if ( u - EPS >= 0 ) {
  14922. p1 = func( u - EPS, v, p1 );
  14923. pu.subVectors( p0, p1 );
  14924. } else {
  14925. p1 = func( u + EPS, v, p1 );
  14926. pu.subVectors( p1, p0 );
  14927. }
  14928. if ( v - EPS >= 0 ) {
  14929. p1 = func( u, v - EPS, p1 );
  14930. pv.subVectors( p0, p1 );
  14931. } else {
  14932. p1 = func( u, v + EPS, p1 );
  14933. pv.subVectors( p1, p0 );
  14934. }
  14935. // cross product of tangent vectors returns surface normal
  14936. normal.crossVectors( pu, pv ).normalize();
  14937. normals.push( normal.x, normal.y, normal.z );
  14938. // uv
  14939. uvs.push( u, v );
  14940. }
  14941. }
  14942. // generate indices
  14943. for ( i = 0; i < stacks; i ++ ) {
  14944. for ( j = 0; j < slices; j ++ ) {
  14945. var a = i * sliceCount + j;
  14946. var b = i * sliceCount + j + 1;
  14947. var c = ( i + 1 ) * sliceCount + j + 1;
  14948. var d = ( i + 1 ) * sliceCount + j;
  14949. // faces one and two
  14950. indices.push( a, b, d );
  14951. indices.push( b, c, d );
  14952. }
  14953. }
  14954. // build geometry
  14955. this.setIndex( indices );
  14956. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14957. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14958. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14959. }
  14960. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14961. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14962. /**
  14963. * @author clockworkgeek / https://github.com/clockworkgeek
  14964. * @author timothypratley / https://github.com/timothypratley
  14965. * @author WestLangley / http://github.com/WestLangley
  14966. * @author Mugen87 / https://github.com/Mugen87
  14967. */
  14968. // PolyhedronGeometry
  14969. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14970. Geometry.call( this );
  14971. this.type = 'PolyhedronGeometry';
  14972. this.parameters = {
  14973. vertices: vertices,
  14974. indices: indices,
  14975. radius: radius,
  14976. detail: detail
  14977. };
  14978. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14979. this.mergeVertices();
  14980. }
  14981. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14982. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14983. // PolyhedronBufferGeometry
  14984. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14985. BufferGeometry.call( this );
  14986. this.type = 'PolyhedronBufferGeometry';
  14987. this.parameters = {
  14988. vertices: vertices,
  14989. indices: indices,
  14990. radius: radius,
  14991. detail: detail
  14992. };
  14993. radius = radius || 1;
  14994. detail = detail || 0;
  14995. // default buffer data
  14996. var vertexBuffer = [];
  14997. var uvBuffer = [];
  14998. // the subdivision creates the vertex buffer data
  14999. subdivide( detail );
  15000. // all vertices should lie on a conceptual sphere with a given radius
  15001. appplyRadius( radius );
  15002. // finally, create the uv data
  15003. generateUVs();
  15004. // build non-indexed geometry
  15005. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  15006. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  15007. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  15008. if ( detail === 0 ) {
  15009. this.computeVertexNormals(); // flat normals
  15010. } else {
  15011. this.normalizeNormals(); // smooth normals
  15012. }
  15013. // helper functions
  15014. function subdivide( detail ) {
  15015. var a = new Vector3();
  15016. var b = new Vector3();
  15017. var c = new Vector3();
  15018. // iterate over all faces and apply a subdivison with the given detail value
  15019. for ( var i = 0; i < indices.length; i += 3 ) {
  15020. // get the vertices of the face
  15021. getVertexByIndex( indices[ i + 0 ], a );
  15022. getVertexByIndex( indices[ i + 1 ], b );
  15023. getVertexByIndex( indices[ i + 2 ], c );
  15024. // perform subdivision
  15025. subdivideFace( a, b, c, detail );
  15026. }
  15027. }
  15028. function subdivideFace( a, b, c, detail ) {
  15029. var cols = Math.pow( 2, detail );
  15030. // we use this multidimensional array as a data structure for creating the subdivision
  15031. var v = [];
  15032. var i, j;
  15033. // construct all of the vertices for this subdivision
  15034. for ( i = 0; i <= cols; i ++ ) {
  15035. v[ i ] = [];
  15036. var aj = a.clone().lerp( c, i / cols );
  15037. var bj = b.clone().lerp( c, i / cols );
  15038. var rows = cols - i;
  15039. for ( j = 0; j <= rows; j ++ ) {
  15040. if ( j === 0 && i === cols ) {
  15041. v[ i ][ j ] = aj;
  15042. } else {
  15043. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  15044. }
  15045. }
  15046. }
  15047. // construct all of the faces
  15048. for ( i = 0; i < cols; i ++ ) {
  15049. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  15050. var k = Math.floor( j / 2 );
  15051. if ( j % 2 === 0 ) {
  15052. pushVertex( v[ i ][ k + 1 ] );
  15053. pushVertex( v[ i + 1 ][ k ] );
  15054. pushVertex( v[ i ][ k ] );
  15055. } else {
  15056. pushVertex( v[ i ][ k + 1 ] );
  15057. pushVertex( v[ i + 1 ][ k + 1 ] );
  15058. pushVertex( v[ i + 1 ][ k ] );
  15059. }
  15060. }
  15061. }
  15062. }
  15063. function appplyRadius( radius ) {
  15064. var vertex = new Vector3();
  15065. // iterate over the entire buffer and apply the radius to each vertex
  15066. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  15067. vertex.x = vertexBuffer[ i + 0 ];
  15068. vertex.y = vertexBuffer[ i + 1 ];
  15069. vertex.z = vertexBuffer[ i + 2 ];
  15070. vertex.normalize().multiplyScalar( radius );
  15071. vertexBuffer[ i + 0 ] = vertex.x;
  15072. vertexBuffer[ i + 1 ] = vertex.y;
  15073. vertexBuffer[ i + 2 ] = vertex.z;
  15074. }
  15075. }
  15076. function generateUVs() {
  15077. var vertex = new Vector3();
  15078. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  15079. vertex.x = vertexBuffer[ i + 0 ];
  15080. vertex.y = vertexBuffer[ i + 1 ];
  15081. vertex.z = vertexBuffer[ i + 2 ];
  15082. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  15083. var v = inclination( vertex ) / Math.PI + 0.5;
  15084. uvBuffer.push( u, 1 - v );
  15085. }
  15086. correctUVs();
  15087. correctSeam();
  15088. }
  15089. function correctSeam() {
  15090. // handle case when face straddles the seam, see #3269
  15091. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  15092. // uv data of a single face
  15093. var x0 = uvBuffer[ i + 0 ];
  15094. var x1 = uvBuffer[ i + 2 ];
  15095. var x2 = uvBuffer[ i + 4 ];
  15096. var max = Math.max( x0, x1, x2 );
  15097. var min = Math.min( x0, x1, x2 );
  15098. // 0.9 is somewhat arbitrary
  15099. if ( max > 0.9 && min < 0.1 ) {
  15100. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  15101. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  15102. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  15103. }
  15104. }
  15105. }
  15106. function pushVertex( vertex ) {
  15107. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  15108. }
  15109. function getVertexByIndex( index, vertex ) {
  15110. var stride = index * 3;
  15111. vertex.x = vertices[ stride + 0 ];
  15112. vertex.y = vertices[ stride + 1 ];
  15113. vertex.z = vertices[ stride + 2 ];
  15114. }
  15115. function correctUVs() {
  15116. var a = new Vector3();
  15117. var b = new Vector3();
  15118. var c = new Vector3();
  15119. var centroid = new Vector3();
  15120. var uvA = new Vector2();
  15121. var uvB = new Vector2();
  15122. var uvC = new Vector2();
  15123. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  15124. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  15125. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  15126. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  15127. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  15128. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  15129. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  15130. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  15131. var azi = azimuth( centroid );
  15132. correctUV( uvA, j + 0, a, azi );
  15133. correctUV( uvB, j + 2, b, azi );
  15134. correctUV( uvC, j + 4, c, azi );
  15135. }
  15136. }
  15137. function correctUV( uv, stride, vector, azimuth ) {
  15138. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  15139. uvBuffer[ stride ] = uv.x - 1;
  15140. }
  15141. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  15142. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  15143. }
  15144. }
  15145. // Angle around the Y axis, counter-clockwise when looking from above.
  15146. function azimuth( vector ) {
  15147. return Math.atan2( vector.z, - vector.x );
  15148. }
  15149. // Angle above the XZ plane.
  15150. function inclination( vector ) {
  15151. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15152. }
  15153. }
  15154. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15155. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  15156. /**
  15157. * @author timothypratley / https://github.com/timothypratley
  15158. * @author Mugen87 / https://github.com/Mugen87
  15159. */
  15160. // TetrahedronGeometry
  15161. function TetrahedronGeometry( radius, detail ) {
  15162. Geometry.call( this );
  15163. this.type = 'TetrahedronGeometry';
  15164. this.parameters = {
  15165. radius: radius,
  15166. detail: detail
  15167. };
  15168. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  15169. this.mergeVertices();
  15170. }
  15171. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  15172. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  15173. // TetrahedronBufferGeometry
  15174. function TetrahedronBufferGeometry( radius, detail ) {
  15175. var vertices = [
  15176. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  15177. ];
  15178. var indices = [
  15179. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15180. ];
  15181. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15182. this.type = 'TetrahedronBufferGeometry';
  15183. this.parameters = {
  15184. radius: radius,
  15185. detail: detail
  15186. };
  15187. }
  15188. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15189. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  15190. /**
  15191. * @author timothypratley / https://github.com/timothypratley
  15192. * @author Mugen87 / https://github.com/Mugen87
  15193. */
  15194. // OctahedronGeometry
  15195. function OctahedronGeometry( radius, detail ) {
  15196. Geometry.call( this );
  15197. this.type = 'OctahedronGeometry';
  15198. this.parameters = {
  15199. radius: radius,
  15200. detail: detail
  15201. };
  15202. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  15203. this.mergeVertices();
  15204. }
  15205. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  15206. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  15207. // OctahedronBufferGeometry
  15208. function OctahedronBufferGeometry( radius, detail ) {
  15209. var vertices = [
  15210. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  15211. ];
  15212. var indices = [
  15213. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  15214. ];
  15215. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15216. this.type = 'OctahedronBufferGeometry';
  15217. this.parameters = {
  15218. radius: radius,
  15219. detail: detail
  15220. };
  15221. }
  15222. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15223. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  15224. /**
  15225. * @author timothypratley / https://github.com/timothypratley
  15226. * @author Mugen87 / https://github.com/Mugen87
  15227. */
  15228. // IcosahedronGeometry
  15229. function IcosahedronGeometry( radius, detail ) {
  15230. Geometry.call( this );
  15231. this.type = 'IcosahedronGeometry';
  15232. this.parameters = {
  15233. radius: radius,
  15234. detail: detail
  15235. };
  15236. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  15237. this.mergeVertices();
  15238. }
  15239. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  15240. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  15241. // IcosahedronBufferGeometry
  15242. function IcosahedronBufferGeometry( radius, detail ) {
  15243. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15244. var vertices = [
  15245. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  15246. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  15247. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  15248. ];
  15249. var indices = [
  15250. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15251. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15252. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15253. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15254. ];
  15255. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15256. this.type = 'IcosahedronBufferGeometry';
  15257. this.parameters = {
  15258. radius: radius,
  15259. detail: detail
  15260. };
  15261. }
  15262. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15263. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  15264. /**
  15265. * @author Abe Pazos / https://hamoid.com
  15266. * @author Mugen87 / https://github.com/Mugen87
  15267. */
  15268. // DodecahedronGeometry
  15269. function DodecahedronGeometry( radius, detail ) {
  15270. Geometry.call( this );
  15271. this.type = 'DodecahedronGeometry';
  15272. this.parameters = {
  15273. radius: radius,
  15274. detail: detail
  15275. };
  15276. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  15277. this.mergeVertices();
  15278. }
  15279. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  15280. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  15281. // DodecahedronBufferGeometry
  15282. function DodecahedronBufferGeometry( radius, detail ) {
  15283. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15284. var r = 1 / t;
  15285. var vertices = [
  15286. // (±1, ±1, ±1)
  15287. - 1, - 1, - 1, - 1, - 1, 1,
  15288. - 1, 1, - 1, - 1, 1, 1,
  15289. 1, - 1, - 1, 1, - 1, 1,
  15290. 1, 1, - 1, 1, 1, 1,
  15291. // (0, ±1/φ, ±φ)
  15292. 0, - r, - t, 0, - r, t,
  15293. 0, r, - t, 0, r, t,
  15294. // (±1/φ, ±φ, 0)
  15295. - r, - t, 0, - r, t, 0,
  15296. r, - t, 0, r, t, 0,
  15297. // (±φ, 0, ±1/φ)
  15298. - t, 0, - r, t, 0, - r,
  15299. - t, 0, r, t, 0, r
  15300. ];
  15301. var indices = [
  15302. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  15303. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  15304. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  15305. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  15306. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  15307. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  15308. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  15309. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  15310. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  15311. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  15312. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  15313. 1, 12, 14, 1, 14, 5, 1, 5, 9
  15314. ];
  15315. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15316. this.type = 'DodecahedronBufferGeometry';
  15317. this.parameters = {
  15318. radius: radius,
  15319. detail: detail
  15320. };
  15321. }
  15322. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15323. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  15324. /**
  15325. * @author oosmoxiecode / https://github.com/oosmoxiecode
  15326. * @author WestLangley / https://github.com/WestLangley
  15327. * @author zz85 / https://github.com/zz85
  15328. * @author miningold / https://github.com/miningold
  15329. * @author jonobr1 / https://github.com/jonobr1
  15330. * @author Mugen87 / https://github.com/Mugen87
  15331. *
  15332. */
  15333. // TubeGeometry
  15334. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  15335. Geometry.call( this );
  15336. this.type = 'TubeGeometry';
  15337. this.parameters = {
  15338. path: path,
  15339. tubularSegments: tubularSegments,
  15340. radius: radius,
  15341. radialSegments: radialSegments,
  15342. closed: closed
  15343. };
  15344. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  15345. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  15346. // expose internals
  15347. this.tangents = bufferGeometry.tangents;
  15348. this.normals = bufferGeometry.normals;
  15349. this.binormals = bufferGeometry.binormals;
  15350. // create geometry
  15351. this.fromBufferGeometry( bufferGeometry );
  15352. this.mergeVertices();
  15353. }
  15354. TubeGeometry.prototype = Object.create( Geometry.prototype );
  15355. TubeGeometry.prototype.constructor = TubeGeometry;
  15356. // TubeBufferGeometry
  15357. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  15358. BufferGeometry.call( this );
  15359. this.type = 'TubeBufferGeometry';
  15360. this.parameters = {
  15361. path: path,
  15362. tubularSegments: tubularSegments,
  15363. radius: radius,
  15364. radialSegments: radialSegments,
  15365. closed: closed
  15366. };
  15367. tubularSegments = tubularSegments || 64;
  15368. radius = radius || 1;
  15369. radialSegments = radialSegments || 8;
  15370. closed = closed || false;
  15371. var frames = path.computeFrenetFrames( tubularSegments, closed );
  15372. // expose internals
  15373. this.tangents = frames.tangents;
  15374. this.normals = frames.normals;
  15375. this.binormals = frames.binormals;
  15376. // helper variables
  15377. var vertex = new Vector3();
  15378. var normal = new Vector3();
  15379. var uv = new Vector2();
  15380. var i, j;
  15381. // buffer
  15382. var vertices = [];
  15383. var normals = [];
  15384. var uvs = [];
  15385. var indices = [];
  15386. // create buffer data
  15387. generateBufferData();
  15388. // build geometry
  15389. this.setIndex( indices );
  15390. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15391. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15392. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15393. // functions
  15394. function generateBufferData() {
  15395. for ( i = 0; i < tubularSegments; i ++ ) {
  15396. generateSegment( i );
  15397. }
  15398. // if the geometry is not closed, generate the last row of vertices and normals
  15399. // at the regular position on the given path
  15400. //
  15401. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15402. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15403. // uvs are generated in a separate function.
  15404. // this makes it easy compute correct values for closed geometries
  15405. generateUVs();
  15406. // finally create faces
  15407. generateIndices();
  15408. }
  15409. function generateSegment( i ) {
  15410. // we use getPointAt to sample evenly distributed points from the given path
  15411. var P = path.getPointAt( i / tubularSegments );
  15412. // retrieve corresponding normal and binormal
  15413. var N = frames.normals[ i ];
  15414. var B = frames.binormals[ i ];
  15415. // generate normals and vertices for the current segment
  15416. for ( j = 0; j <= radialSegments; j ++ ) {
  15417. var v = j / radialSegments * Math.PI * 2;
  15418. var sin = Math.sin( v );
  15419. var cos = - Math.cos( v );
  15420. // normal
  15421. normal.x = ( cos * N.x + sin * B.x );
  15422. normal.y = ( cos * N.y + sin * B.y );
  15423. normal.z = ( cos * N.z + sin * B.z );
  15424. normal.normalize();
  15425. normals.push( normal.x, normal.y, normal.z );
  15426. // vertex
  15427. vertex.x = P.x + radius * normal.x;
  15428. vertex.y = P.y + radius * normal.y;
  15429. vertex.z = P.z + radius * normal.z;
  15430. vertices.push( vertex.x, vertex.y, vertex.z );
  15431. }
  15432. }
  15433. function generateIndices() {
  15434. for ( j = 1; j <= tubularSegments; j ++ ) {
  15435. for ( i = 1; i <= radialSegments; i ++ ) {
  15436. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15437. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15438. var c = ( radialSegments + 1 ) * j + i;
  15439. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15440. // faces
  15441. indices.push( a, b, d );
  15442. indices.push( b, c, d );
  15443. }
  15444. }
  15445. }
  15446. function generateUVs() {
  15447. for ( i = 0; i <= tubularSegments; i ++ ) {
  15448. for ( j = 0; j <= radialSegments; j ++ ) {
  15449. uv.x = i / tubularSegments;
  15450. uv.y = j / radialSegments;
  15451. uvs.push( uv.x, uv.y );
  15452. }
  15453. }
  15454. }
  15455. }
  15456. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15457. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15458. /**
  15459. * @author oosmoxiecode
  15460. * @author Mugen87 / https://github.com/Mugen87
  15461. *
  15462. * based on http://www.blackpawn.com/texts/pqtorus/
  15463. */
  15464. // TorusKnotGeometry
  15465. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15466. Geometry.call( this );
  15467. this.type = 'TorusKnotGeometry';
  15468. this.parameters = {
  15469. radius: radius,
  15470. tube: tube,
  15471. tubularSegments: tubularSegments,
  15472. radialSegments: radialSegments,
  15473. p: p,
  15474. q: q
  15475. };
  15476. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15477. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15478. this.mergeVertices();
  15479. }
  15480. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15481. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15482. // TorusKnotBufferGeometry
  15483. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15484. BufferGeometry.call( this );
  15485. this.type = 'TorusKnotBufferGeometry';
  15486. this.parameters = {
  15487. radius: radius,
  15488. tube: tube,
  15489. tubularSegments: tubularSegments,
  15490. radialSegments: radialSegments,
  15491. p: p,
  15492. q: q
  15493. };
  15494. radius = radius || 100;
  15495. tube = tube || 40;
  15496. tubularSegments = Math.floor( tubularSegments ) || 64;
  15497. radialSegments = Math.floor( radialSegments ) || 8;
  15498. p = p || 2;
  15499. q = q || 3;
  15500. // buffers
  15501. var indices = [];
  15502. var vertices = [];
  15503. var normals = [];
  15504. var uvs = [];
  15505. // helper variables
  15506. var i, j;
  15507. var vertex = new Vector3();
  15508. var normal = new Vector3();
  15509. var P1 = new Vector3();
  15510. var P2 = new Vector3();
  15511. var B = new Vector3();
  15512. var T = new Vector3();
  15513. var N = new Vector3();
  15514. // generate vertices, normals and uvs
  15515. for ( i = 0; i <= tubularSegments; ++ i ) {
  15516. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15517. var u = i / tubularSegments * p * Math.PI * 2;
  15518. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15519. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15520. calculatePositionOnCurve( u, p, q, radius, P1 );
  15521. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15522. // calculate orthonormal basis
  15523. T.subVectors( P2, P1 );
  15524. N.addVectors( P2, P1 );
  15525. B.crossVectors( T, N );
  15526. N.crossVectors( B, T );
  15527. // normalize B, N. T can be ignored, we don't use it
  15528. B.normalize();
  15529. N.normalize();
  15530. for ( j = 0; j <= radialSegments; ++ j ) {
  15531. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15532. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15533. var v = j / radialSegments * Math.PI * 2;
  15534. var cx = - tube * Math.cos( v );
  15535. var cy = tube * Math.sin( v );
  15536. // now calculate the final vertex position.
  15537. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15538. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15539. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15540. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15541. vertices.push( vertex.x, vertex.y, vertex.z );
  15542. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15543. normal.subVectors( vertex, P1 ).normalize();
  15544. normals.push( normal.x, normal.y, normal.z );
  15545. // uv
  15546. uvs.push( i / tubularSegments );
  15547. uvs.push( j / radialSegments );
  15548. }
  15549. }
  15550. // generate indices
  15551. for ( j = 1; j <= tubularSegments; j ++ ) {
  15552. for ( i = 1; i <= radialSegments; i ++ ) {
  15553. // indices
  15554. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15555. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15556. var c = ( radialSegments + 1 ) * j + i;
  15557. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15558. // faces
  15559. indices.push( a, b, d );
  15560. indices.push( b, c, d );
  15561. }
  15562. }
  15563. // build geometry
  15564. this.setIndex( indices );
  15565. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15566. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15567. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15568. // this function calculates the current position on the torus curve
  15569. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15570. var cu = Math.cos( u );
  15571. var su = Math.sin( u );
  15572. var quOverP = q / p * u;
  15573. var cs = Math.cos( quOverP );
  15574. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15575. position.y = radius * ( 2 + cs ) * su * 0.5;
  15576. position.z = radius * Math.sin( quOverP ) * 0.5;
  15577. }
  15578. }
  15579. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15580. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15581. /**
  15582. * @author oosmoxiecode
  15583. * @author mrdoob / http://mrdoob.com/
  15584. * @author Mugen87 / https://github.com/Mugen87
  15585. */
  15586. // TorusGeometry
  15587. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15588. Geometry.call( this );
  15589. this.type = 'TorusGeometry';
  15590. this.parameters = {
  15591. radius: radius,
  15592. tube: tube,
  15593. radialSegments: radialSegments,
  15594. tubularSegments: tubularSegments,
  15595. arc: arc
  15596. };
  15597. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15598. this.mergeVertices();
  15599. }
  15600. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15601. TorusGeometry.prototype.constructor = TorusGeometry;
  15602. // TorusBufferGeometry
  15603. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15604. BufferGeometry.call( this );
  15605. this.type = 'TorusBufferGeometry';
  15606. this.parameters = {
  15607. radius: radius,
  15608. tube: tube,
  15609. radialSegments: radialSegments,
  15610. tubularSegments: tubularSegments,
  15611. arc: arc
  15612. };
  15613. radius = radius || 100;
  15614. tube = tube || 40;
  15615. radialSegments = Math.floor( radialSegments ) || 8;
  15616. tubularSegments = Math.floor( tubularSegments ) || 6;
  15617. arc = arc || Math.PI * 2;
  15618. // buffers
  15619. var indices = [];
  15620. var vertices = [];
  15621. var normals = [];
  15622. var uvs = [];
  15623. // helper variables
  15624. var center = new Vector3();
  15625. var vertex = new Vector3();
  15626. var normal = new Vector3();
  15627. var j, i;
  15628. // generate vertices, normals and uvs
  15629. for ( j = 0; j <= radialSegments; j ++ ) {
  15630. for ( i = 0; i <= tubularSegments; i ++ ) {
  15631. var u = i / tubularSegments * arc;
  15632. var v = j / radialSegments * Math.PI * 2;
  15633. // vertex
  15634. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15635. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15636. vertex.z = tube * Math.sin( v );
  15637. vertices.push( vertex.x, vertex.y, vertex.z );
  15638. // normal
  15639. center.x = radius * Math.cos( u );
  15640. center.y = radius * Math.sin( u );
  15641. normal.subVectors( vertex, center ).normalize();
  15642. normals.push( normal.x, normal.y, normal.z );
  15643. // uv
  15644. uvs.push( i / tubularSegments );
  15645. uvs.push( j / radialSegments );
  15646. }
  15647. }
  15648. // generate indices
  15649. for ( j = 1; j <= radialSegments; j ++ ) {
  15650. for ( i = 1; i <= tubularSegments; i ++ ) {
  15651. // indices
  15652. var a = ( tubularSegments + 1 ) * j + i - 1;
  15653. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15654. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15655. var d = ( tubularSegments + 1 ) * j + i;
  15656. // faces
  15657. indices.push( a, b, d );
  15658. indices.push( b, c, d );
  15659. }
  15660. }
  15661. // build geometry
  15662. this.setIndex( indices );
  15663. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15664. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15665. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15666. }
  15667. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15668. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15669. /**
  15670. * @author zz85 / http://www.lab4games.net/zz85/blog
  15671. */
  15672. var ShapeUtils = {
  15673. // calculate area of the contour polygon
  15674. area: function ( contour ) {
  15675. var n = contour.length;
  15676. var a = 0.0;
  15677. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15678. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15679. }
  15680. return a * 0.5;
  15681. },
  15682. triangulate: ( function () {
  15683. /**
  15684. * This code is a quick port of code written in C++ which was submitted to
  15685. * flipcode.com by John W. Ratcliff // July 22, 2000
  15686. * See original code and more information here:
  15687. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15688. *
  15689. * ported to actionscript by Zevan Rosser
  15690. * www.actionsnippet.com
  15691. *
  15692. * ported to javascript by Joshua Koo
  15693. * http://www.lab4games.net/zz85/blog
  15694. *
  15695. */
  15696. function snip( contour, u, v, w, n, verts ) {
  15697. var p;
  15698. var ax, ay, bx, by;
  15699. var cx, cy, px, py;
  15700. ax = contour[ verts[ u ] ].x;
  15701. ay = contour[ verts[ u ] ].y;
  15702. bx = contour[ verts[ v ] ].x;
  15703. by = contour[ verts[ v ] ].y;
  15704. cx = contour[ verts[ w ] ].x;
  15705. cy = contour[ verts[ w ] ].y;
  15706. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15707. var aX, aY, bX, bY, cX, cY;
  15708. var apx, apy, bpx, bpy, cpx, cpy;
  15709. var cCROSSap, bCROSScp, aCROSSbp;
  15710. aX = cx - bx; aY = cy - by;
  15711. bX = ax - cx; bY = ay - cy;
  15712. cX = bx - ax; cY = by - ay;
  15713. for ( p = 0; p < n; p ++ ) {
  15714. px = contour[ verts[ p ] ].x;
  15715. py = contour[ verts[ p ] ].y;
  15716. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15717. ( ( px === bx ) && ( py === by ) ) ||
  15718. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15719. apx = px - ax; apy = py - ay;
  15720. bpx = px - bx; bpy = py - by;
  15721. cpx = px - cx; cpy = py - cy;
  15722. // see if p is inside triangle abc
  15723. aCROSSbp = aX * bpy - aY * bpx;
  15724. cCROSSap = cX * apy - cY * apx;
  15725. bCROSScp = bX * cpy - bY * cpx;
  15726. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15727. }
  15728. return true;
  15729. }
  15730. // takes in an contour array and returns
  15731. return function triangulate( contour, indices ) {
  15732. var n = contour.length;
  15733. if ( n < 3 ) return null;
  15734. var result = [],
  15735. verts = [],
  15736. vertIndices = [];
  15737. /* we want a counter-clockwise polygon in verts */
  15738. var u, v, w;
  15739. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15740. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15741. } else {
  15742. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15743. }
  15744. var nv = n;
  15745. /* remove nv - 2 vertices, creating 1 triangle every time */
  15746. var count = 2 * nv; /* error detection */
  15747. for ( v = nv - 1; nv > 2; ) {
  15748. /* if we loop, it is probably a non-simple polygon */
  15749. if ( ( count -- ) <= 0 ) {
  15750. //** Triangulate: ERROR - probable bad polygon!
  15751. //throw ( "Warning, unable to triangulate polygon!" );
  15752. //return null;
  15753. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15754. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15755. if ( indices ) return vertIndices;
  15756. return result;
  15757. }
  15758. /* three consecutive vertices in current polygon, <u,v,w> */
  15759. u = v; if ( nv <= u ) u = 0; /* previous */
  15760. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15761. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15762. if ( snip( contour, u, v, w, nv, verts ) ) {
  15763. var a, b, c, s, t;
  15764. /* true names of the vertices */
  15765. a = verts[ u ];
  15766. b = verts[ v ];
  15767. c = verts[ w ];
  15768. /* output Triangle */
  15769. result.push( [ contour[ a ],
  15770. contour[ b ],
  15771. contour[ c ] ] );
  15772. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15773. /* remove v from the remaining polygon */
  15774. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15775. verts[ s ] = verts[ t ];
  15776. }
  15777. nv --;
  15778. /* reset error detection counter */
  15779. count = 2 * nv;
  15780. }
  15781. }
  15782. if ( indices ) return vertIndices;
  15783. return result;
  15784. };
  15785. } )(),
  15786. triangulateShape: function ( contour, holes ) {
  15787. function removeDupEndPts(points) {
  15788. var l = points.length;
  15789. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15790. points.pop();
  15791. }
  15792. }
  15793. removeDupEndPts( contour );
  15794. holes.forEach( removeDupEndPts );
  15795. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15796. // inOtherPt needs to be collinear to the inSegment
  15797. if ( inSegPt1.x !== inSegPt2.x ) {
  15798. if ( inSegPt1.x < inSegPt2.x ) {
  15799. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15800. } else {
  15801. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15802. }
  15803. } else {
  15804. if ( inSegPt1.y < inSegPt2.y ) {
  15805. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15806. } else {
  15807. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15808. }
  15809. }
  15810. }
  15811. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15812. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15813. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15814. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15815. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15816. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15817. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15818. if ( Math.abs( limit ) > Number.EPSILON ) {
  15819. // not parallel
  15820. var perpSeg2;
  15821. if ( limit > 0 ) {
  15822. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15823. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15824. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15825. } else {
  15826. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15827. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15828. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15829. }
  15830. // i.e. to reduce rounding errors
  15831. // intersection at endpoint of segment#1?
  15832. if ( perpSeg2 === 0 ) {
  15833. if ( ( inExcludeAdjacentSegs ) &&
  15834. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15835. return [ inSeg1Pt1 ];
  15836. }
  15837. if ( perpSeg2 === limit ) {
  15838. if ( ( inExcludeAdjacentSegs ) &&
  15839. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15840. return [ inSeg1Pt2 ];
  15841. }
  15842. // intersection at endpoint of segment#2?
  15843. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15844. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15845. // return real intersection point
  15846. var factorSeg1 = perpSeg2 / limit;
  15847. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15848. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15849. } else {
  15850. // parallel or collinear
  15851. if ( ( perpSeg1 !== 0 ) ||
  15852. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15853. // they are collinear or degenerate
  15854. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15855. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15856. // both segments are points
  15857. if ( seg1Pt && seg2Pt ) {
  15858. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15859. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15860. return [ inSeg1Pt1 ]; // they are the same point
  15861. }
  15862. // segment#1 is a single point
  15863. if ( seg1Pt ) {
  15864. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15865. return [ inSeg1Pt1 ];
  15866. }
  15867. // segment#2 is a single point
  15868. if ( seg2Pt ) {
  15869. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15870. return [ inSeg2Pt1 ];
  15871. }
  15872. // they are collinear segments, which might overlap
  15873. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15874. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15875. if ( seg1dx !== 0 ) {
  15876. // the segments are NOT on a vertical line
  15877. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15878. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15879. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15880. } else {
  15881. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15882. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15883. }
  15884. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15885. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15886. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15887. } else {
  15888. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15889. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15890. }
  15891. } else {
  15892. // the segments are on a vertical line
  15893. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15894. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15895. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15896. } else {
  15897. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15898. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15899. }
  15900. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15901. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15902. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15903. } else {
  15904. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15905. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15906. }
  15907. }
  15908. if ( seg1minVal <= seg2minVal ) {
  15909. if ( seg1maxVal < seg2minVal ) return [];
  15910. if ( seg1maxVal === seg2minVal ) {
  15911. if ( inExcludeAdjacentSegs ) return [];
  15912. return [ seg2min ];
  15913. }
  15914. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15915. return [ seg2min, seg2max ];
  15916. } else {
  15917. if ( seg1minVal > seg2maxVal ) return [];
  15918. if ( seg1minVal === seg2maxVal ) {
  15919. if ( inExcludeAdjacentSegs ) return [];
  15920. return [ seg1min ];
  15921. }
  15922. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15923. return [ seg1min, seg2max ];
  15924. }
  15925. }
  15926. }
  15927. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15928. // The order of legs is important
  15929. // translation of all points, so that Vertex is at (0,0)
  15930. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15931. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15932. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15933. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15934. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15935. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15936. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15937. // angle != 180 deg.
  15938. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15939. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15940. if ( from2toAngle > 0 ) {
  15941. // main angle < 180 deg.
  15942. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15943. } else {
  15944. // main angle > 180 deg.
  15945. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15946. }
  15947. } else {
  15948. // angle == 180 deg.
  15949. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15950. return ( from2otherAngle > 0 );
  15951. }
  15952. }
  15953. function removeHoles( contour, holes ) {
  15954. var shape = contour.concat(); // work on this shape
  15955. var hole;
  15956. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15957. // Check if hole point lies within angle around shape point
  15958. var lastShapeIdx = shape.length - 1;
  15959. var prevShapeIdx = inShapeIdx - 1;
  15960. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15961. var nextShapeIdx = inShapeIdx + 1;
  15962. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15963. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15964. if ( ! insideAngle ) {
  15965. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15966. return false;
  15967. }
  15968. // Check if shape point lies within angle around hole point
  15969. var lastHoleIdx = hole.length - 1;
  15970. var prevHoleIdx = inHoleIdx - 1;
  15971. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15972. var nextHoleIdx = inHoleIdx + 1;
  15973. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15974. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15975. if ( ! insideAngle ) {
  15976. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15977. return false;
  15978. }
  15979. return true;
  15980. }
  15981. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15982. // checks for intersections with shape edges
  15983. var sIdx, nextIdx, intersection;
  15984. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15985. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15986. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15987. if ( intersection.length > 0 ) return true;
  15988. }
  15989. return false;
  15990. }
  15991. var indepHoles = [];
  15992. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15993. // checks for intersections with hole edges
  15994. var ihIdx, chkHole,
  15995. hIdx, nextIdx, intersection;
  15996. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15997. chkHole = holes[ indepHoles[ ihIdx ] ];
  15998. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15999. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  16000. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  16001. if ( intersection.length > 0 ) return true;
  16002. }
  16003. }
  16004. return false;
  16005. }
  16006. var holeIndex, shapeIndex,
  16007. shapePt, holePt,
  16008. holeIdx, cutKey, failedCuts = [],
  16009. tmpShape1, tmpShape2,
  16010. tmpHole1, tmpHole2;
  16011. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  16012. indepHoles.push( h );
  16013. }
  16014. var minShapeIndex = 0;
  16015. var counter = indepHoles.length * 2;
  16016. while ( indepHoles.length > 0 ) {
  16017. counter --;
  16018. if ( counter < 0 ) {
  16019. console.log( 'THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!' );
  16020. break;
  16021. }
  16022. // search for shape-vertex and hole-vertex,
  16023. // which can be connected without intersections
  16024. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  16025. shapePt = shape[ shapeIndex ];
  16026. holeIndex = - 1;
  16027. // search for hole which can be reached without intersections
  16028. for ( var h = 0; h < indepHoles.length; h ++ ) {
  16029. holeIdx = indepHoles[ h ];
  16030. // prevent multiple checks
  16031. cutKey = shapePt.x + ':' + shapePt.y + ':' + holeIdx;
  16032. if ( failedCuts[ cutKey ] !== undefined ) continue;
  16033. hole = holes[ holeIdx ];
  16034. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  16035. holePt = hole[ h2 ];
  16036. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  16037. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  16038. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  16039. holeIndex = h2;
  16040. indepHoles.splice( h, 1 );
  16041. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  16042. tmpShape2 = shape.slice( shapeIndex );
  16043. tmpHole1 = hole.slice( holeIndex );
  16044. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  16045. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16046. minShapeIndex = shapeIndex;
  16047. // Debug only, to show the selected cuts
  16048. // glob_CutLines.push( [ shapePt, holePt ] );
  16049. break;
  16050. }
  16051. if ( holeIndex >= 0 ) break; // hole-vertex found
  16052. failedCuts[ cutKey ] = true; // remember failure
  16053. }
  16054. if ( holeIndex >= 0 ) break; // hole-vertex found
  16055. }
  16056. }
  16057. return shape; /* shape with no holes */
  16058. }
  16059. var i, il, f, face,
  16060. key, index,
  16061. allPointsMap = {};
  16062. // 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.
  16063. var allpoints = contour.concat();
  16064. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  16065. Array.prototype.push.apply( allpoints, holes[ h ] );
  16066. }
  16067. //console.log( "allpoints",allpoints, allpoints.length );
  16068. // prepare all points map
  16069. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16070. key = allpoints[ i ].x + ':' + allpoints[ i ].y;
  16071. if ( allPointsMap[ key ] !== undefined ) {
  16072. console.warn( 'THREE.ShapeUtils: Duplicate point', key, i );
  16073. }
  16074. allPointsMap[ key ] = i;
  16075. }
  16076. // remove holes by cutting paths to holes and adding them to the shape
  16077. var shapeWithoutHoles = removeHoles( contour, holes );
  16078. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  16079. //console.log( "triangles",triangles, triangles.length );
  16080. // check all face vertices against all points map
  16081. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16082. face = triangles[ i ];
  16083. for ( f = 0; f < 3; f ++ ) {
  16084. key = face[ f ].x + ':' + face[ f ].y;
  16085. index = allPointsMap[ key ];
  16086. if ( index !== undefined ) {
  16087. face[ f ] = index;
  16088. }
  16089. }
  16090. }
  16091. return triangles.concat();
  16092. },
  16093. isClockWise: function ( pts ) {
  16094. return ShapeUtils.area( pts ) < 0;
  16095. }
  16096. };
  16097. /**
  16098. * @author zz85 / http://www.lab4games.net/zz85/blog
  16099. *
  16100. * Creates extruded geometry from a path shape.
  16101. *
  16102. * parameters = {
  16103. *
  16104. * curveSegments: <int>, // number of points on the curves
  16105. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  16106. * amount: <int>, // Depth to extrude the shape
  16107. *
  16108. * bevelEnabled: <bool>, // turn on bevel
  16109. * bevelThickness: <float>, // how deep into the original shape bevel goes
  16110. * bevelSize: <float>, // how far from shape outline is bevel
  16111. * bevelSegments: <int>, // number of bevel layers
  16112. *
  16113. * extrudePath: <THREE.Curve> // curve to extrude shape along
  16114. * frames: <Object> // containing arrays of tangents, normals, binormals
  16115. *
  16116. * UVGenerator: <Object> // object that provides UV generator functions
  16117. *
  16118. * }
  16119. */
  16120. // ExtrudeGeometry
  16121. function ExtrudeGeometry( shapes, options ) {
  16122. Geometry.call( this );
  16123. this.type = 'ExtrudeGeometry';
  16124. this.parameters = {
  16125. shapes: shapes,
  16126. options: options
  16127. };
  16128. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  16129. this.mergeVertices();
  16130. }
  16131. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  16132. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  16133. // ExtrudeBufferGeometry
  16134. function ExtrudeBufferGeometry( shapes, options ) {
  16135. if ( typeof ( shapes ) === "undefined" ) {
  16136. return;
  16137. }
  16138. BufferGeometry.call( this );
  16139. this.type = 'ExtrudeBufferGeometry';
  16140. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  16141. this.addShapeList( shapes, options );
  16142. this.computeVertexNormals();
  16143. // can't really use automatic vertex normals
  16144. // as then front and back sides get smoothed too
  16145. // should do separate smoothing just for sides
  16146. //this.computeVertexNormals();
  16147. //console.log( "took", ( Date.now() - startTime ) );
  16148. }
  16149. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16150. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  16151. ExtrudeBufferGeometry.prototype.getArrays = function () {
  16152. var positionAttribute = this.getAttribute( "position" );
  16153. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  16154. var uvAttribute = this.getAttribute( "uv" );
  16155. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  16156. var IndexAttribute = this.index;
  16157. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  16158. return {
  16159. position: verticesArray,
  16160. uv: uvArray,
  16161. index: indicesArray
  16162. };
  16163. };
  16164. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  16165. var sl = shapes.length;
  16166. options.arrays = this.getArrays();
  16167. for ( var s = 0; s < sl; s ++ ) {
  16168. var shape = shapes[ s ];
  16169. this.addShape( shape, options );
  16170. }
  16171. this.setIndex( options.arrays.index );
  16172. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  16173. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16174. };
  16175. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  16176. var arrays = options.arrays ? options.arrays : this.getArrays();
  16177. var verticesArray = arrays.position;
  16178. var indicesArray = arrays.index;
  16179. var uvArray = arrays.uv;
  16180. var placeholder = [];
  16181. var amount = options.amount !== undefined ? options.amount : 100;
  16182. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  16183. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  16184. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  16185. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  16186. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  16187. var steps = options.steps !== undefined ? options.steps : 1;
  16188. var extrudePath = options.extrudePath;
  16189. var extrudePts, extrudeByPath = false;
  16190. // Use default WorldUVGenerator if no UV generators are specified.
  16191. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  16192. var splineTube, binormal, normal, position2;
  16193. if ( extrudePath ) {
  16194. extrudePts = extrudePath.getSpacedPoints( steps );
  16195. extrudeByPath = true;
  16196. bevelEnabled = false; // bevels not supported for path extrusion
  16197. // SETUP TNB variables
  16198. // TODO1 - have a .isClosed in spline?
  16199. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  16200. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  16201. binormal = new Vector3();
  16202. normal = new Vector3();
  16203. position2 = new Vector3();
  16204. }
  16205. // Safeguards if bevels are not enabled
  16206. if ( ! bevelEnabled ) {
  16207. bevelSegments = 0;
  16208. bevelThickness = 0;
  16209. bevelSize = 0;
  16210. }
  16211. // Variables initialization
  16212. var ahole, h, hl; // looping of holes
  16213. var scope = this;
  16214. var shapePoints = shape.extractPoints( curveSegments );
  16215. var vertices = shapePoints.shape;
  16216. var holes = shapePoints.holes;
  16217. var reverse = ! ShapeUtils.isClockWise( vertices );
  16218. if ( reverse ) {
  16219. vertices = vertices.reverse();
  16220. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  16221. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16222. ahole = holes[ h ];
  16223. if ( ShapeUtils.isClockWise( ahole ) ) {
  16224. holes[ h ] = ahole.reverse();
  16225. }
  16226. }
  16227. }
  16228. var faces = ShapeUtils.triangulateShape( vertices, holes );
  16229. /* Vertices */
  16230. var contour = vertices; // vertices has all points but contour has only points of circumference
  16231. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16232. ahole = holes[ h ];
  16233. vertices = vertices.concat( ahole );
  16234. }
  16235. function scalePt2( pt, vec, size ) {
  16236. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  16237. return vec.clone().multiplyScalar( size ).add( pt );
  16238. }
  16239. var b, bs, t, z,
  16240. vert, vlen = vertices.length,
  16241. face, flen = faces.length;
  16242. // Find directions for point movement
  16243. function getBevelVec( inPt, inPrev, inNext ) {
  16244. // computes for inPt the corresponding point inPt' on a new contour
  16245. // shifted by 1 unit (length of normalized vector) to the left
  16246. // if we walk along contour clockwise, this new contour is outside the old one
  16247. //
  16248. // inPt' is the intersection of the two lines parallel to the two
  16249. // adjacent edges of inPt at a distance of 1 unit on the left side.
  16250. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  16251. // good reading for geometry algorithms (here: line-line intersection)
  16252. // http://geomalgorithms.com/a05-_intersect-1.html
  16253. var v_prev_x = inPt.x - inPrev.x,
  16254. v_prev_y = inPt.y - inPrev.y;
  16255. var v_next_x = inNext.x - inPt.x,
  16256. v_next_y = inNext.y - inPt.y;
  16257. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  16258. // check for collinear edges
  16259. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16260. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  16261. // not collinear
  16262. // length of vectors for normalizing
  16263. var v_prev_len = Math.sqrt( v_prev_lensq );
  16264. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  16265. // shift adjacent points by unit vectors to the left
  16266. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  16267. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  16268. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  16269. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  16270. // scaling factor for v_prev to intersection point
  16271. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  16272. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  16273. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16274. // vector from inPt to intersection point
  16275. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  16276. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  16277. // Don't normalize!, otherwise sharp corners become ugly
  16278. // but prevent crazy spikes
  16279. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  16280. if ( v_trans_lensq <= 2 ) {
  16281. return new Vector2( v_trans_x, v_trans_y );
  16282. } else {
  16283. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  16284. }
  16285. } else {
  16286. // handle special case of collinear edges
  16287. var direction_eq = false; // assumes: opposite
  16288. if ( v_prev_x > Number.EPSILON ) {
  16289. if ( v_next_x > Number.EPSILON ) {
  16290. direction_eq = true;
  16291. }
  16292. } else {
  16293. if ( v_prev_x < - Number.EPSILON ) {
  16294. if ( v_next_x < - Number.EPSILON ) {
  16295. direction_eq = true;
  16296. }
  16297. } else {
  16298. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  16299. direction_eq = true;
  16300. }
  16301. }
  16302. }
  16303. if ( direction_eq ) {
  16304. // console.log("Warning: lines are a straight sequence");
  16305. v_trans_x = - v_prev_y;
  16306. v_trans_y = v_prev_x;
  16307. shrink_by = Math.sqrt( v_prev_lensq );
  16308. } else {
  16309. // console.log("Warning: lines are a straight spike");
  16310. v_trans_x = v_prev_x;
  16311. v_trans_y = v_prev_y;
  16312. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  16313. }
  16314. }
  16315. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  16316. }
  16317. var contourMovements = [];
  16318. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16319. if ( j === il ) j = 0;
  16320. if ( k === il ) k = 0;
  16321. // (j)---(i)---(k)
  16322. // console.log('i,j,k', i, j , k)
  16323. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  16324. }
  16325. var holesMovements = [],
  16326. oneHoleMovements, verticesMovements = contourMovements.concat();
  16327. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16328. ahole = holes[ h ];
  16329. oneHoleMovements = [];
  16330. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16331. if ( j === il ) j = 0;
  16332. if ( k === il ) k = 0;
  16333. // (j)---(i)---(k)
  16334. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  16335. }
  16336. holesMovements.push( oneHoleMovements );
  16337. verticesMovements = verticesMovements.concat( oneHoleMovements );
  16338. }
  16339. // Loop bevelSegments, 1 for the front, 1 for the back
  16340. for ( b = 0; b < bevelSegments; b ++ ) {
  16341. //for ( b = bevelSegments; b > 0; b -- ) {
  16342. t = b / bevelSegments;
  16343. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16344. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16345. // contract shape
  16346. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16347. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16348. v( vert.x, vert.y, - z );
  16349. }
  16350. // expand holes
  16351. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16352. ahole = holes[ h ];
  16353. oneHoleMovements = holesMovements[ h ];
  16354. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16355. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16356. v( vert.x, vert.y, - z );
  16357. }
  16358. }
  16359. }
  16360. bs = bevelSize;
  16361. // Back facing vertices
  16362. for ( i = 0; i < vlen; i ++ ) {
  16363. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16364. if ( ! extrudeByPath ) {
  16365. v( vert.x, vert.y, 0 );
  16366. } else {
  16367. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  16368. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  16369. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  16370. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  16371. v( position2.x, position2.y, position2.z );
  16372. }
  16373. }
  16374. // Add stepped vertices...
  16375. // Including front facing vertices
  16376. var s;
  16377. for ( s = 1; s <= steps; s ++ ) {
  16378. for ( i = 0; i < vlen; i ++ ) {
  16379. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16380. if ( ! extrudeByPath ) {
  16381. v( vert.x, vert.y, amount / steps * s );
  16382. } else {
  16383. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  16384. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  16385. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  16386. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  16387. v( position2.x, position2.y, position2.z );
  16388. }
  16389. }
  16390. }
  16391. // Add bevel segments planes
  16392. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16393. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16394. t = b / bevelSegments;
  16395. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16396. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16397. // contract shape
  16398. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16399. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16400. v( vert.x, vert.y, amount + z );
  16401. }
  16402. // expand holes
  16403. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16404. ahole = holes[ h ];
  16405. oneHoleMovements = holesMovements[ h ];
  16406. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16407. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16408. if ( ! extrudeByPath ) {
  16409. v( vert.x, vert.y, amount + z );
  16410. } else {
  16411. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16412. }
  16413. }
  16414. }
  16415. }
  16416. /* Faces */
  16417. // Top and bottom faces
  16418. buildLidFaces();
  16419. // Sides faces
  16420. buildSideFaces();
  16421. ///// Internal functions
  16422. function buildLidFaces() {
  16423. var start = verticesArray.length/3;
  16424. if ( bevelEnabled ) {
  16425. var layer = 0; // steps + 1
  16426. var offset = vlen * layer;
  16427. // Bottom faces
  16428. for ( i = 0; i < flen; i ++ ) {
  16429. face = faces[ i ];
  16430. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16431. }
  16432. layer = steps + bevelSegments * 2;
  16433. offset = vlen * layer;
  16434. // Top faces
  16435. for ( i = 0; i < flen; i ++ ) {
  16436. face = faces[ i ];
  16437. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16438. }
  16439. } else {
  16440. // Bottom faces
  16441. for ( i = 0; i < flen; i ++ ) {
  16442. face = faces[ i ];
  16443. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16444. }
  16445. // Top faces
  16446. for ( i = 0; i < flen; i ++ ) {
  16447. face = faces[ i ];
  16448. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16449. }
  16450. }
  16451. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16452. }
  16453. // Create faces for the z-sides of the shape
  16454. function buildSideFaces() {
  16455. var start = verticesArray.length/3;
  16456. var layeroffset = 0;
  16457. sidewalls( contour, layeroffset );
  16458. layeroffset += contour.length;
  16459. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16460. ahole = holes[ h ];
  16461. sidewalls( ahole, layeroffset );
  16462. //, true
  16463. layeroffset += ahole.length;
  16464. }
  16465. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16466. }
  16467. function sidewalls( contour, layeroffset ) {
  16468. var j, k;
  16469. i = contour.length;
  16470. while ( -- i >= 0 ) {
  16471. j = i;
  16472. k = i - 1;
  16473. if ( k < 0 ) k = contour.length - 1;
  16474. //console.log('b', i,j, i-1, k,vertices.length);
  16475. var s = 0,
  16476. sl = steps + bevelSegments * 2;
  16477. for ( s = 0; s < sl; s ++ ) {
  16478. var slen1 = vlen * s;
  16479. var slen2 = vlen * ( s + 1 );
  16480. var a = layeroffset + j + slen1,
  16481. b = layeroffset + k + slen1,
  16482. c = layeroffset + k + slen2,
  16483. d = layeroffset + j + slen2;
  16484. f4( a, b, c, d, contour, s, sl, j, k );
  16485. }
  16486. }
  16487. }
  16488. function v( x, y, z ) {
  16489. placeholder.push( x );
  16490. placeholder.push( y );
  16491. placeholder.push( z );
  16492. }
  16493. function f3( a, b, c ) {
  16494. addVertex( a );
  16495. addVertex( b );
  16496. addVertex( c );
  16497. var nextIndex = verticesArray.length / 3;
  16498. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16499. addUV( uvs[ 0 ] );
  16500. addUV( uvs[ 1 ] );
  16501. addUV( uvs[ 2 ] );
  16502. }
  16503. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16504. addVertex( a );
  16505. addVertex( b );
  16506. addVertex( d );
  16507. addVertex( b );
  16508. addVertex( c );
  16509. addVertex( d );
  16510. var nextIndex = verticesArray.length / 3;
  16511. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16512. addUV( uvs[ 0 ] );
  16513. addUV( uvs[ 1 ] );
  16514. addUV( uvs[ 3 ] );
  16515. addUV( uvs[ 1 ] );
  16516. addUV( uvs[ 2 ] );
  16517. addUV( uvs[ 3 ] );
  16518. }
  16519. function addVertex( index ) {
  16520. indicesArray.push( verticesArray.length / 3 );
  16521. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16522. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16523. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16524. }
  16525. function addUV( vector2 ) {
  16526. uvArray.push( vector2.x );
  16527. uvArray.push( vector2.y );
  16528. }
  16529. if ( ! options.arrays ) {
  16530. this.setIndex( indicesArray );
  16531. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16532. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16533. }
  16534. };
  16535. ExtrudeGeometry.WorldUVGenerator = {
  16536. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16537. var a_x = vertices[ indexA * 3 ];
  16538. var a_y = vertices[ indexA * 3 + 1 ];
  16539. var b_x = vertices[ indexB * 3 ];
  16540. var b_y = vertices[ indexB * 3 + 1 ];
  16541. var c_x = vertices[ indexC * 3 ];
  16542. var c_y = vertices[ indexC * 3 + 1 ];
  16543. return [
  16544. new Vector2( a_x, a_y ),
  16545. new Vector2( b_x, b_y ),
  16546. new Vector2( c_x, c_y )
  16547. ];
  16548. },
  16549. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16550. var a_x = vertices[ indexA * 3 ];
  16551. var a_y = vertices[ indexA * 3 + 1 ];
  16552. var a_z = vertices[ indexA * 3 + 2 ];
  16553. var b_x = vertices[ indexB * 3 ];
  16554. var b_y = vertices[ indexB * 3 + 1 ];
  16555. var b_z = vertices[ indexB * 3 + 2 ];
  16556. var c_x = vertices[ indexC * 3 ];
  16557. var c_y = vertices[ indexC * 3 + 1 ];
  16558. var c_z = vertices[ indexC * 3 + 2 ];
  16559. var d_x = vertices[ indexD * 3 ];
  16560. var d_y = vertices[ indexD * 3 + 1 ];
  16561. var d_z = vertices[ indexD * 3 + 2 ];
  16562. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16563. return [
  16564. new Vector2( a_x, 1 - a_z ),
  16565. new Vector2( b_x, 1 - b_z ),
  16566. new Vector2( c_x, 1 - c_z ),
  16567. new Vector2( d_x, 1 - d_z )
  16568. ];
  16569. } else {
  16570. return [
  16571. new Vector2( a_y, 1 - a_z ),
  16572. new Vector2( b_y, 1 - b_z ),
  16573. new Vector2( c_y, 1 - c_z ),
  16574. new Vector2( d_y, 1 - d_z )
  16575. ];
  16576. }
  16577. }
  16578. };
  16579. /**
  16580. * @author zz85 / http://www.lab4games.net/zz85/blog
  16581. * @author alteredq / http://alteredqualia.com/
  16582. *
  16583. * Text = 3D Text
  16584. *
  16585. * parameters = {
  16586. * font: <THREE.Font>, // font
  16587. *
  16588. * size: <float>, // size of the text
  16589. * height: <float>, // thickness to extrude text
  16590. * curveSegments: <int>, // number of points on the curves
  16591. *
  16592. * bevelEnabled: <bool>, // turn on bevel
  16593. * bevelThickness: <float>, // how deep into text bevel goes
  16594. * bevelSize: <float> // how far from text outline is bevel
  16595. * }
  16596. */
  16597. // TextGeometry
  16598. function TextGeometry( text, parameters ) {
  16599. Geometry.call( this );
  16600. this.type = 'TextGeometry';
  16601. this.parameters = {
  16602. text: text,
  16603. parameters: parameters
  16604. };
  16605. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16606. this.mergeVertices();
  16607. }
  16608. TextGeometry.prototype = Object.create( Geometry.prototype );
  16609. TextGeometry.prototype.constructor = TextGeometry;
  16610. // TextBufferGeometry
  16611. function TextBufferGeometry( text, parameters ) {
  16612. parameters = parameters || {};
  16613. var font = parameters.font;
  16614. if ( ! ( font && font.isFont ) ) {
  16615. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16616. return new Geometry();
  16617. }
  16618. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16619. // translate parameters to ExtrudeGeometry API
  16620. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16621. // defaults
  16622. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16623. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16624. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16625. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16626. this.type = 'TextBufferGeometry';
  16627. }
  16628. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16629. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16630. /**
  16631. * @author mrdoob / http://mrdoob.com/
  16632. * @author benaadams / https://twitter.com/ben_a_adams
  16633. * @author Mugen87 / https://github.com/Mugen87
  16634. */
  16635. // SphereGeometry
  16636. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16637. Geometry.call( this );
  16638. this.type = 'SphereGeometry';
  16639. this.parameters = {
  16640. radius: radius,
  16641. widthSegments: widthSegments,
  16642. heightSegments: heightSegments,
  16643. phiStart: phiStart,
  16644. phiLength: phiLength,
  16645. thetaStart: thetaStart,
  16646. thetaLength: thetaLength
  16647. };
  16648. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16649. this.mergeVertices();
  16650. }
  16651. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16652. SphereGeometry.prototype.constructor = SphereGeometry;
  16653. // SphereBufferGeometry
  16654. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16655. BufferGeometry.call( this );
  16656. this.type = 'SphereBufferGeometry';
  16657. this.parameters = {
  16658. radius: radius,
  16659. widthSegments: widthSegments,
  16660. heightSegments: heightSegments,
  16661. phiStart: phiStart,
  16662. phiLength: phiLength,
  16663. thetaStart: thetaStart,
  16664. thetaLength: thetaLength
  16665. };
  16666. radius = radius || 50;
  16667. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16668. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16669. phiStart = phiStart !== undefined ? phiStart : 0;
  16670. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16671. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16672. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16673. var thetaEnd = thetaStart + thetaLength;
  16674. var ix, iy;
  16675. var index = 0;
  16676. var grid = [];
  16677. var vertex = new Vector3();
  16678. var normal = new Vector3();
  16679. // buffers
  16680. var indices = [];
  16681. var vertices = [];
  16682. var normals = [];
  16683. var uvs = [];
  16684. // generate vertices, normals and uvs
  16685. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16686. var verticesRow = [];
  16687. var v = iy / heightSegments;
  16688. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16689. var u = ix / widthSegments;
  16690. // vertex
  16691. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16692. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16693. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16694. vertices.push( vertex.x, vertex.y, vertex.z );
  16695. // normal
  16696. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16697. normals.push( normal.x, normal.y, normal.z );
  16698. // uv
  16699. uvs.push( u, 1 - v );
  16700. verticesRow.push( index ++ );
  16701. }
  16702. grid.push( verticesRow );
  16703. }
  16704. // indices
  16705. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16706. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16707. var a = grid[ iy ][ ix + 1 ];
  16708. var b = grid[ iy ][ ix ];
  16709. var c = grid[ iy + 1 ][ ix ];
  16710. var d = grid[ iy + 1 ][ ix + 1 ];
  16711. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16712. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16713. }
  16714. }
  16715. // build geometry
  16716. this.setIndex( indices );
  16717. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16718. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16719. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16720. }
  16721. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16722. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16723. /**
  16724. * @author Kaleb Murphy
  16725. * @author Mugen87 / https://github.com/Mugen87
  16726. */
  16727. // RingGeometry
  16728. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16729. Geometry.call( this );
  16730. this.type = 'RingGeometry';
  16731. this.parameters = {
  16732. innerRadius: innerRadius,
  16733. outerRadius: outerRadius,
  16734. thetaSegments: thetaSegments,
  16735. phiSegments: phiSegments,
  16736. thetaStart: thetaStart,
  16737. thetaLength: thetaLength
  16738. };
  16739. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16740. this.mergeVertices();
  16741. }
  16742. RingGeometry.prototype = Object.create( Geometry.prototype );
  16743. RingGeometry.prototype.constructor = RingGeometry;
  16744. // RingBufferGeometry
  16745. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16746. BufferGeometry.call( this );
  16747. this.type = 'RingBufferGeometry';
  16748. this.parameters = {
  16749. innerRadius: innerRadius,
  16750. outerRadius: outerRadius,
  16751. thetaSegments: thetaSegments,
  16752. phiSegments: phiSegments,
  16753. thetaStart: thetaStart,
  16754. thetaLength: thetaLength
  16755. };
  16756. innerRadius = innerRadius || 20;
  16757. outerRadius = outerRadius || 50;
  16758. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16759. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16760. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16761. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16762. // buffers
  16763. var indices = [];
  16764. var vertices = [];
  16765. var normals = [];
  16766. var uvs = [];
  16767. // some helper variables
  16768. var segment;
  16769. var radius = innerRadius;
  16770. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16771. var vertex = new Vector3();
  16772. var uv = new Vector2();
  16773. var j, i;
  16774. // generate vertices, normals and uvs
  16775. for ( j = 0; j <= phiSegments; j ++ ) {
  16776. for ( i = 0; i <= thetaSegments; i ++ ) {
  16777. // values are generate from the inside of the ring to the outside
  16778. segment = thetaStart + i / thetaSegments * thetaLength;
  16779. // vertex
  16780. vertex.x = radius * Math.cos( segment );
  16781. vertex.y = radius * Math.sin( segment );
  16782. vertices.push( vertex.x, vertex.y, vertex.z );
  16783. // normal
  16784. normals.push( 0, 0, 1 );
  16785. // uv
  16786. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16787. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16788. uvs.push( uv.x, uv.y );
  16789. }
  16790. // increase the radius for next row of vertices
  16791. radius += radiusStep;
  16792. }
  16793. // indices
  16794. for ( j = 0; j < phiSegments; j ++ ) {
  16795. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16796. for ( i = 0; i < thetaSegments; i ++ ) {
  16797. segment = i + thetaSegmentLevel;
  16798. var a = segment;
  16799. var b = segment + thetaSegments + 1;
  16800. var c = segment + thetaSegments + 2;
  16801. var d = segment + 1;
  16802. // faces
  16803. indices.push( a, b, d );
  16804. indices.push( b, c, d );
  16805. }
  16806. }
  16807. // build geometry
  16808. this.setIndex( indices );
  16809. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16810. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16811. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16812. }
  16813. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16814. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16815. /**
  16816. * @author astrodud / http://astrodud.isgreat.org/
  16817. * @author zz85 / https://github.com/zz85
  16818. * @author bhouston / http://clara.io
  16819. * @author Mugen87 / https://github.com/Mugen87
  16820. */
  16821. // LatheGeometry
  16822. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16823. Geometry.call( this );
  16824. this.type = 'LatheGeometry';
  16825. this.parameters = {
  16826. points: points,
  16827. segments: segments,
  16828. phiStart: phiStart,
  16829. phiLength: phiLength
  16830. };
  16831. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16832. this.mergeVertices();
  16833. }
  16834. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16835. LatheGeometry.prototype.constructor = LatheGeometry;
  16836. // LatheBufferGeometry
  16837. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16838. BufferGeometry.call( this );
  16839. this.type = 'LatheBufferGeometry';
  16840. this.parameters = {
  16841. points: points,
  16842. segments: segments,
  16843. phiStart: phiStart,
  16844. phiLength: phiLength
  16845. };
  16846. segments = Math.floor( segments ) || 12;
  16847. phiStart = phiStart || 0;
  16848. phiLength = phiLength || Math.PI * 2;
  16849. // clamp phiLength so it's in range of [ 0, 2PI ]
  16850. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16851. // buffers
  16852. var indices = [];
  16853. var vertices = [];
  16854. var uvs = [];
  16855. // helper variables
  16856. var base;
  16857. var inverseSegments = 1.0 / segments;
  16858. var vertex = new Vector3();
  16859. var uv = new Vector2();
  16860. var i, j;
  16861. // generate vertices and uvs
  16862. for ( i = 0; i <= segments; i ++ ) {
  16863. var phi = phiStart + i * inverseSegments * phiLength;
  16864. var sin = Math.sin( phi );
  16865. var cos = Math.cos( phi );
  16866. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16867. // vertex
  16868. vertex.x = points[ j ].x * sin;
  16869. vertex.y = points[ j ].y;
  16870. vertex.z = points[ j ].x * cos;
  16871. vertices.push( vertex.x, vertex.y, vertex.z );
  16872. // uv
  16873. uv.x = i / segments;
  16874. uv.y = j / ( points.length - 1 );
  16875. uvs.push( uv.x, uv.y );
  16876. }
  16877. }
  16878. // indices
  16879. for ( i = 0; i < segments; i ++ ) {
  16880. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16881. base = j + i * points.length;
  16882. var a = base;
  16883. var b = base + points.length;
  16884. var c = base + points.length + 1;
  16885. var d = base + 1;
  16886. // faces
  16887. indices.push( a, b, d );
  16888. indices.push( b, c, d );
  16889. }
  16890. }
  16891. // build geometry
  16892. this.setIndex( indices );
  16893. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16894. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16895. // generate normals
  16896. this.computeVertexNormals();
  16897. // if the geometry is closed, we need to average the normals along the seam.
  16898. // because the corresponding vertices are identical (but still have different UVs).
  16899. if ( phiLength === Math.PI * 2 ) {
  16900. var normals = this.attributes.normal.array;
  16901. var n1 = new Vector3();
  16902. var n2 = new Vector3();
  16903. var n = new Vector3();
  16904. // this is the buffer offset for the last line of vertices
  16905. base = segments * points.length * 3;
  16906. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16907. // select the normal of the vertex in the first line
  16908. n1.x = normals[ j + 0 ];
  16909. n1.y = normals[ j + 1 ];
  16910. n1.z = normals[ j + 2 ];
  16911. // select the normal of the vertex in the last line
  16912. n2.x = normals[ base + j + 0 ];
  16913. n2.y = normals[ base + j + 1 ];
  16914. n2.z = normals[ base + j + 2 ];
  16915. // average normals
  16916. n.addVectors( n1, n2 ).normalize();
  16917. // assign the new values to both normals
  16918. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16919. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16920. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16921. }
  16922. }
  16923. }
  16924. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16925. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16926. /**
  16927. * @author jonobr1 / http://jonobr1.com
  16928. * @author Mugen87 / https://github.com/Mugen87
  16929. */
  16930. // ShapeGeometry
  16931. function ShapeGeometry( shapes, curveSegments ) {
  16932. Geometry.call( this );
  16933. this.type = 'ShapeGeometry';
  16934. if ( typeof curveSegments === 'object' ) {
  16935. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16936. curveSegments = curveSegments.curveSegments;
  16937. }
  16938. this.parameters = {
  16939. shapes: shapes,
  16940. curveSegments: curveSegments
  16941. };
  16942. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16943. this.mergeVertices();
  16944. }
  16945. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16946. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16947. // ShapeBufferGeometry
  16948. function ShapeBufferGeometry( shapes, curveSegments ) {
  16949. BufferGeometry.call( this );
  16950. this.type = 'ShapeBufferGeometry';
  16951. this.parameters = {
  16952. shapes: shapes,
  16953. curveSegments: curveSegments
  16954. };
  16955. curveSegments = curveSegments || 12;
  16956. // buffers
  16957. var indices = [];
  16958. var vertices = [];
  16959. var normals = [];
  16960. var uvs = [];
  16961. // helper variables
  16962. var groupStart = 0;
  16963. var groupCount = 0;
  16964. // allow single and array values for "shapes" parameter
  16965. if ( Array.isArray( shapes ) === false ) {
  16966. addShape( shapes );
  16967. } else {
  16968. for ( var i = 0; i < shapes.length; i ++ ) {
  16969. addShape( shapes[ i ] );
  16970. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16971. groupStart += groupCount;
  16972. groupCount = 0;
  16973. }
  16974. }
  16975. // build geometry
  16976. this.setIndex( indices );
  16977. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16978. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16979. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16980. // helper functions
  16981. function addShape( shape ) {
  16982. var i, l, shapeHole;
  16983. var indexOffset = vertices.length / 3;
  16984. var points = shape.extractPoints( curveSegments );
  16985. var shapeVertices = points.shape;
  16986. var shapeHoles = points.holes;
  16987. // check direction of vertices
  16988. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16989. shapeVertices = shapeVertices.reverse();
  16990. // also check if holes are in the opposite direction
  16991. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16992. shapeHole = shapeHoles[ i ];
  16993. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16994. shapeHoles[ i ] = shapeHole.reverse();
  16995. }
  16996. }
  16997. }
  16998. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16999. // join vertices of inner and outer paths to a single array
  17000. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  17001. shapeHole = shapeHoles[ i ];
  17002. shapeVertices = shapeVertices.concat( shapeHole );
  17003. }
  17004. // vertices, normals, uvs
  17005. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  17006. var vertex = shapeVertices[ i ];
  17007. vertices.push( vertex.x, vertex.y, 0 );
  17008. normals.push( 0, 0, 1 );
  17009. uvs.push( vertex.x, vertex.y ); // world uvs
  17010. }
  17011. // incides
  17012. for ( i = 0, l = faces.length; i < l; i ++ ) {
  17013. var face = faces[ i ];
  17014. var a = face[ 0 ] + indexOffset;
  17015. var b = face[ 1 ] + indexOffset;
  17016. var c = face[ 2 ] + indexOffset;
  17017. indices.push( a, b, c );
  17018. groupCount += 3;
  17019. }
  17020. }
  17021. }
  17022. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17023. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  17024. /**
  17025. * @author WestLangley / http://github.com/WestLangley
  17026. * @author Mugen87 / https://github.com/Mugen87
  17027. */
  17028. function EdgesGeometry( geometry, thresholdAngle ) {
  17029. BufferGeometry.call( this );
  17030. this.type = 'EdgesGeometry';
  17031. this.parameters = {
  17032. thresholdAngle: thresholdAngle
  17033. };
  17034. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  17035. // buffer
  17036. var vertices = [];
  17037. // helper variables
  17038. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  17039. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  17040. var key, keys = [ 'a', 'b', 'c' ];
  17041. // prepare source geometry
  17042. var geometry2;
  17043. if ( geometry.isBufferGeometry ) {
  17044. geometry2 = new Geometry();
  17045. geometry2.fromBufferGeometry( geometry );
  17046. } else {
  17047. geometry2 = geometry.clone();
  17048. }
  17049. geometry2.mergeVertices();
  17050. geometry2.computeFaceNormals();
  17051. var sourceVertices = geometry2.vertices;
  17052. var faces = geometry2.faces;
  17053. // now create a data structure where each entry represents an edge with its adjoining faces
  17054. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  17055. var face = faces[ i ];
  17056. for ( var j = 0; j < 3; j ++ ) {
  17057. edge1 = face[ keys[ j ] ];
  17058. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  17059. edge[ 0 ] = Math.min( edge1, edge2 );
  17060. edge[ 1 ] = Math.max( edge1, edge2 );
  17061. key = edge[ 0 ] + ',' + edge[ 1 ];
  17062. if ( edges[ key ] === undefined ) {
  17063. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  17064. } else {
  17065. edges[ key ].face2 = i;
  17066. }
  17067. }
  17068. }
  17069. // generate vertices
  17070. for ( key in edges ) {
  17071. var e = edges[ key ];
  17072. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  17073. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  17074. var vertex = sourceVertices[ e.index1 ];
  17075. vertices.push( vertex.x, vertex.y, vertex.z );
  17076. vertex = sourceVertices[ e.index2 ];
  17077. vertices.push( vertex.x, vertex.y, vertex.z );
  17078. }
  17079. }
  17080. // build geometry
  17081. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17082. }
  17083. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  17084. EdgesGeometry.prototype.constructor = EdgesGeometry;
  17085. /**
  17086. * @author mrdoob / http://mrdoob.com/
  17087. * @author Mugen87 / https://github.com/Mugen87
  17088. */
  17089. // CylinderGeometry
  17090. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17091. Geometry.call( this );
  17092. this.type = 'CylinderGeometry';
  17093. this.parameters = {
  17094. radiusTop: radiusTop,
  17095. radiusBottom: radiusBottom,
  17096. height: height,
  17097. radialSegments: radialSegments,
  17098. heightSegments: heightSegments,
  17099. openEnded: openEnded,
  17100. thetaStart: thetaStart,
  17101. thetaLength: thetaLength
  17102. };
  17103. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  17104. this.mergeVertices();
  17105. }
  17106. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  17107. CylinderGeometry.prototype.constructor = CylinderGeometry;
  17108. // CylinderBufferGeometry
  17109. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17110. BufferGeometry.call( this );
  17111. this.type = 'CylinderBufferGeometry';
  17112. this.parameters = {
  17113. radiusTop: radiusTop,
  17114. radiusBottom: radiusBottom,
  17115. height: height,
  17116. radialSegments: radialSegments,
  17117. heightSegments: heightSegments,
  17118. openEnded: openEnded,
  17119. thetaStart: thetaStart,
  17120. thetaLength: thetaLength
  17121. };
  17122. var scope = this;
  17123. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17124. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17125. height = height !== undefined ? height : 100;
  17126. radialSegments = Math.floor( radialSegments ) || 8;
  17127. heightSegments = Math.floor( heightSegments ) || 1;
  17128. openEnded = openEnded !== undefined ? openEnded : false;
  17129. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  17130. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  17131. // buffers
  17132. var indices = [];
  17133. var vertices = [];
  17134. var normals = [];
  17135. var uvs = [];
  17136. // helper variables
  17137. var index = 0;
  17138. var indexArray = [];
  17139. var halfHeight = height / 2;
  17140. var groupStart = 0;
  17141. // generate geometry
  17142. generateTorso();
  17143. if ( openEnded === false ) {
  17144. if ( radiusTop > 0 ) generateCap( true );
  17145. if ( radiusBottom > 0 ) generateCap( false );
  17146. }
  17147. // build geometry
  17148. this.setIndex( indices );
  17149. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17150. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17151. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17152. function generateTorso() {
  17153. var x, y;
  17154. var normal = new Vector3();
  17155. var vertex = new Vector3();
  17156. var groupCount = 0;
  17157. // this will be used to calculate the normal
  17158. var slope = ( radiusBottom - radiusTop ) / height;
  17159. // generate vertices, normals and uvs
  17160. for ( y = 0; y <= heightSegments; y ++ ) {
  17161. var indexRow = [];
  17162. var v = y / heightSegments;
  17163. // calculate the radius of the current row
  17164. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17165. for ( x = 0; x <= radialSegments; x ++ ) {
  17166. var u = x / radialSegments;
  17167. var theta = u * thetaLength + thetaStart;
  17168. var sinTheta = Math.sin( theta );
  17169. var cosTheta = Math.cos( theta );
  17170. // vertex
  17171. vertex.x = radius * sinTheta;
  17172. vertex.y = - v * height + halfHeight;
  17173. vertex.z = radius * cosTheta;
  17174. vertices.push( vertex.x, vertex.y, vertex.z );
  17175. // normal
  17176. normal.set( sinTheta, slope, cosTheta ).normalize();
  17177. normals.push( normal.x, normal.y, normal.z );
  17178. // uv
  17179. uvs.push( u, 1 - v );
  17180. // save index of vertex in respective row
  17181. indexRow.push( index ++ );
  17182. }
  17183. // now save vertices of the row in our index array
  17184. indexArray.push( indexRow );
  17185. }
  17186. // generate indices
  17187. for ( x = 0; x < radialSegments; x ++ ) {
  17188. for ( y = 0; y < heightSegments; y ++ ) {
  17189. // we use the index array to access the correct indices
  17190. var a = indexArray[ y ][ x ];
  17191. var b = indexArray[ y + 1 ][ x ];
  17192. var c = indexArray[ y + 1 ][ x + 1 ];
  17193. var d = indexArray[ y ][ x + 1 ];
  17194. // faces
  17195. indices.push( a, b, d );
  17196. indices.push( b, c, d );
  17197. // update group counter
  17198. groupCount += 6;
  17199. }
  17200. }
  17201. // add a group to the geometry. this will ensure multi material support
  17202. scope.addGroup( groupStart, groupCount, 0 );
  17203. // calculate new start value for groups
  17204. groupStart += groupCount;
  17205. }
  17206. function generateCap( top ) {
  17207. var x, centerIndexStart, centerIndexEnd;
  17208. var uv = new Vector2();
  17209. var vertex = new Vector3();
  17210. var groupCount = 0;
  17211. var radius = ( top === true ) ? radiusTop : radiusBottom;
  17212. var sign = ( top === true ) ? 1 : - 1;
  17213. // save the index of the first center vertex
  17214. centerIndexStart = index;
  17215. // first we generate the center vertex data of the cap.
  17216. // because the geometry needs one set of uvs per face,
  17217. // we must generate a center vertex per face/segment
  17218. for ( x = 1; x <= radialSegments; x ++ ) {
  17219. // vertex
  17220. vertices.push( 0, halfHeight * sign, 0 );
  17221. // normal
  17222. normals.push( 0, sign, 0 );
  17223. // uv
  17224. uvs.push( 0.5, 0.5 );
  17225. // increase index
  17226. index ++;
  17227. }
  17228. // save the index of the last center vertex
  17229. centerIndexEnd = index;
  17230. // now we generate the surrounding vertices, normals and uvs
  17231. for ( x = 0; x <= radialSegments; x ++ ) {
  17232. var u = x / radialSegments;
  17233. var theta = u * thetaLength + thetaStart;
  17234. var cosTheta = Math.cos( theta );
  17235. var sinTheta = Math.sin( theta );
  17236. // vertex
  17237. vertex.x = radius * sinTheta;
  17238. vertex.y = halfHeight * sign;
  17239. vertex.z = radius * cosTheta;
  17240. vertices.push( vertex.x, vertex.y, vertex.z );
  17241. // normal
  17242. normals.push( 0, sign, 0 );
  17243. // uv
  17244. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17245. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17246. uvs.push( uv.x, uv.y );
  17247. // increase index
  17248. index ++;
  17249. }
  17250. // generate indices
  17251. for ( x = 0; x < radialSegments; x ++ ) {
  17252. var c = centerIndexStart + x;
  17253. var i = centerIndexEnd + x;
  17254. if ( top === true ) {
  17255. // face top
  17256. indices.push( i, i + 1, c );
  17257. } else {
  17258. // face bottom
  17259. indices.push( i + 1, i, c );
  17260. }
  17261. groupCount += 3;
  17262. }
  17263. // add a group to the geometry. this will ensure multi material support
  17264. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17265. // calculate new start value for groups
  17266. groupStart += groupCount;
  17267. }
  17268. }
  17269. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17270. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  17271. /**
  17272. * @author abelnation / http://github.com/abelnation
  17273. */
  17274. // ConeGeometry
  17275. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17276. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17277. this.type = 'ConeGeometry';
  17278. this.parameters = {
  17279. radius: radius,
  17280. height: height,
  17281. radialSegments: radialSegments,
  17282. heightSegments: heightSegments,
  17283. openEnded: openEnded,
  17284. thetaStart: thetaStart,
  17285. thetaLength: thetaLength
  17286. };
  17287. }
  17288. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  17289. ConeGeometry.prototype.constructor = ConeGeometry;
  17290. // ConeBufferGeometry
  17291. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17292. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17293. this.type = 'ConeBufferGeometry';
  17294. this.parameters = {
  17295. radius: radius,
  17296. height: height,
  17297. radialSegments: radialSegments,
  17298. heightSegments: heightSegments,
  17299. openEnded: openEnded,
  17300. thetaStart: thetaStart,
  17301. thetaLength: thetaLength
  17302. };
  17303. }
  17304. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  17305. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  17306. /**
  17307. * @author benaadams / https://twitter.com/ben_a_adams
  17308. * @author Mugen87 / https://github.com/Mugen87
  17309. * @author hughes
  17310. */
  17311. // CircleGeometry
  17312. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  17313. Geometry.call( this );
  17314. this.type = 'CircleGeometry';
  17315. this.parameters = {
  17316. radius: radius,
  17317. segments: segments,
  17318. thetaStart: thetaStart,
  17319. thetaLength: thetaLength
  17320. };
  17321. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17322. this.mergeVertices();
  17323. }
  17324. CircleGeometry.prototype = Object.create( Geometry.prototype );
  17325. CircleGeometry.prototype.constructor = CircleGeometry;
  17326. // CircleBufferGeometry
  17327. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  17328. BufferGeometry.call( this );
  17329. this.type = 'CircleBufferGeometry';
  17330. this.parameters = {
  17331. radius: radius,
  17332. segments: segments,
  17333. thetaStart: thetaStart,
  17334. thetaLength: thetaLength
  17335. };
  17336. radius = radius || 50;
  17337. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17338. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17339. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17340. // buffers
  17341. var indices = [];
  17342. var vertices = [];
  17343. var normals = [];
  17344. var uvs = [];
  17345. // helper variables
  17346. var i, s;
  17347. var vertex = new Vector3();
  17348. var uv = new Vector2();
  17349. // center point
  17350. vertices.push( 0, 0, 0 );
  17351. normals.push( 0, 0, 1 );
  17352. uvs.push( 0.5, 0.5 );
  17353. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17354. var segment = thetaStart + s / segments * thetaLength;
  17355. // vertex
  17356. vertex.x = radius * Math.cos( segment );
  17357. vertex.y = radius * Math.sin( segment );
  17358. vertices.push( vertex.x, vertex.y, vertex.z );
  17359. // normal
  17360. normals.push( 0, 0, 1 );
  17361. // uvs
  17362. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17363. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17364. uvs.push( uv.x, uv.y );
  17365. }
  17366. // indices
  17367. for ( i = 1; i <= segments; i ++ ) {
  17368. indices.push( i, i + 1, 0 );
  17369. }
  17370. // build geometry
  17371. this.setIndex( indices );
  17372. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17373. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17374. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17375. }
  17376. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17377. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  17378. var Geometries = Object.freeze({
  17379. WireframeGeometry: WireframeGeometry,
  17380. ParametricGeometry: ParametricGeometry,
  17381. ParametricBufferGeometry: ParametricBufferGeometry,
  17382. TetrahedronGeometry: TetrahedronGeometry,
  17383. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  17384. OctahedronGeometry: OctahedronGeometry,
  17385. OctahedronBufferGeometry: OctahedronBufferGeometry,
  17386. IcosahedronGeometry: IcosahedronGeometry,
  17387. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  17388. DodecahedronGeometry: DodecahedronGeometry,
  17389. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17390. PolyhedronGeometry: PolyhedronGeometry,
  17391. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17392. TubeGeometry: TubeGeometry,
  17393. TubeBufferGeometry: TubeBufferGeometry,
  17394. TorusKnotGeometry: TorusKnotGeometry,
  17395. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17396. TorusGeometry: TorusGeometry,
  17397. TorusBufferGeometry: TorusBufferGeometry,
  17398. TextGeometry: TextGeometry,
  17399. TextBufferGeometry: TextBufferGeometry,
  17400. SphereGeometry: SphereGeometry,
  17401. SphereBufferGeometry: SphereBufferGeometry,
  17402. RingGeometry: RingGeometry,
  17403. RingBufferGeometry: RingBufferGeometry,
  17404. PlaneGeometry: PlaneGeometry,
  17405. PlaneBufferGeometry: PlaneBufferGeometry,
  17406. LatheGeometry: LatheGeometry,
  17407. LatheBufferGeometry: LatheBufferGeometry,
  17408. ShapeGeometry: ShapeGeometry,
  17409. ShapeBufferGeometry: ShapeBufferGeometry,
  17410. ExtrudeGeometry: ExtrudeGeometry,
  17411. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17412. EdgesGeometry: EdgesGeometry,
  17413. ConeGeometry: ConeGeometry,
  17414. ConeBufferGeometry: ConeBufferGeometry,
  17415. CylinderGeometry: CylinderGeometry,
  17416. CylinderBufferGeometry: CylinderBufferGeometry,
  17417. CircleGeometry: CircleGeometry,
  17418. CircleBufferGeometry: CircleBufferGeometry,
  17419. BoxGeometry: BoxGeometry,
  17420. BoxBufferGeometry: BoxBufferGeometry
  17421. });
  17422. /**
  17423. * @author mrdoob / http://mrdoob.com/
  17424. *
  17425. * parameters = {
  17426. * color: <THREE.Color>,
  17427. * opacity: <float>
  17428. * }
  17429. */
  17430. function ShadowMaterial( parameters ) {
  17431. Material.call( this );
  17432. this.type = 'ShadowMaterial';
  17433. this.color = new Color( 0x000000 );
  17434. this.opacity = 1.0;
  17435. this.lights = true;
  17436. this.transparent = true;
  17437. this.setValues( parameters );
  17438. }
  17439. ShadowMaterial.prototype = Object.create( Material.prototype );
  17440. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17441. ShadowMaterial.prototype.isShadowMaterial = true;
  17442. /**
  17443. * @author mrdoob / http://mrdoob.com/
  17444. */
  17445. function RawShaderMaterial( parameters ) {
  17446. ShaderMaterial.call( this, parameters );
  17447. this.type = 'RawShaderMaterial';
  17448. }
  17449. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17450. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17451. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17452. /**
  17453. * @author WestLangley / http://github.com/WestLangley
  17454. *
  17455. * parameters = {
  17456. * color: <hex>,
  17457. * roughness: <float>,
  17458. * metalness: <float>,
  17459. * opacity: <float>,
  17460. *
  17461. * map: new THREE.Texture( <Image> ),
  17462. *
  17463. * lightMap: new THREE.Texture( <Image> ),
  17464. * lightMapIntensity: <float>
  17465. *
  17466. * aoMap: new THREE.Texture( <Image> ),
  17467. * aoMapIntensity: <float>
  17468. *
  17469. * emissive: <hex>,
  17470. * emissiveIntensity: <float>
  17471. * emissiveMap: new THREE.Texture( <Image> ),
  17472. *
  17473. * bumpMap: new THREE.Texture( <Image> ),
  17474. * bumpScale: <float>,
  17475. *
  17476. * normalMap: new THREE.Texture( <Image> ),
  17477. * normalScale: <Vector2>,
  17478. *
  17479. * displacementMap: new THREE.Texture( <Image> ),
  17480. * displacementScale: <float>,
  17481. * displacementBias: <float>,
  17482. *
  17483. * roughnessMap: new THREE.Texture( <Image> ),
  17484. *
  17485. * metalnessMap: new THREE.Texture( <Image> ),
  17486. *
  17487. * alphaMap: new THREE.Texture( <Image> ),
  17488. *
  17489. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17490. * envMapIntensity: <float>
  17491. *
  17492. * refractionRatio: <float>,
  17493. *
  17494. * wireframe: <boolean>,
  17495. * wireframeLinewidth: <float>,
  17496. *
  17497. * skinning: <bool>,
  17498. * morphTargets: <bool>,
  17499. * morphNormals: <bool>
  17500. * }
  17501. */
  17502. function MeshStandardMaterial( parameters ) {
  17503. Material.call( this );
  17504. this.defines = { 'STANDARD': '' };
  17505. this.type = 'MeshStandardMaterial';
  17506. this.color = new Color( 0xffffff ); // diffuse
  17507. this.roughness = 0.5;
  17508. this.metalness = 0.5;
  17509. this.map = null;
  17510. this.lightMap = null;
  17511. this.lightMapIntensity = 1.0;
  17512. this.aoMap = null;
  17513. this.aoMapIntensity = 1.0;
  17514. this.emissive = new Color( 0x000000 );
  17515. this.emissiveIntensity = 1.0;
  17516. this.emissiveMap = null;
  17517. this.bumpMap = null;
  17518. this.bumpScale = 1;
  17519. this.normalMap = null;
  17520. this.normalScale = new Vector2( 1, 1 );
  17521. this.displacementMap = null;
  17522. this.displacementScale = 1;
  17523. this.displacementBias = 0;
  17524. this.roughnessMap = null;
  17525. this.metalnessMap = null;
  17526. this.alphaMap = null;
  17527. this.envMap = null;
  17528. this.envMapIntensity = 1.0;
  17529. this.refractionRatio = 0.98;
  17530. this.wireframe = false;
  17531. this.wireframeLinewidth = 1;
  17532. this.wireframeLinecap = 'round';
  17533. this.wireframeLinejoin = 'round';
  17534. this.skinning = false;
  17535. this.morphTargets = false;
  17536. this.morphNormals = false;
  17537. this.setValues( parameters );
  17538. }
  17539. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17540. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17541. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17542. MeshStandardMaterial.prototype.copy = function ( source ) {
  17543. Material.prototype.copy.call( this, source );
  17544. this.defines = { 'STANDARD': '' };
  17545. this.color.copy( source.color );
  17546. this.roughness = source.roughness;
  17547. this.metalness = source.metalness;
  17548. this.map = source.map;
  17549. this.lightMap = source.lightMap;
  17550. this.lightMapIntensity = source.lightMapIntensity;
  17551. this.aoMap = source.aoMap;
  17552. this.aoMapIntensity = source.aoMapIntensity;
  17553. this.emissive.copy( source.emissive );
  17554. this.emissiveMap = source.emissiveMap;
  17555. this.emissiveIntensity = source.emissiveIntensity;
  17556. this.bumpMap = source.bumpMap;
  17557. this.bumpScale = source.bumpScale;
  17558. this.normalMap = source.normalMap;
  17559. this.normalScale.copy( source.normalScale );
  17560. this.displacementMap = source.displacementMap;
  17561. this.displacementScale = source.displacementScale;
  17562. this.displacementBias = source.displacementBias;
  17563. this.roughnessMap = source.roughnessMap;
  17564. this.metalnessMap = source.metalnessMap;
  17565. this.alphaMap = source.alphaMap;
  17566. this.envMap = source.envMap;
  17567. this.envMapIntensity = source.envMapIntensity;
  17568. this.refractionRatio = source.refractionRatio;
  17569. this.wireframe = source.wireframe;
  17570. this.wireframeLinewidth = source.wireframeLinewidth;
  17571. this.wireframeLinecap = source.wireframeLinecap;
  17572. this.wireframeLinejoin = source.wireframeLinejoin;
  17573. this.skinning = source.skinning;
  17574. this.morphTargets = source.morphTargets;
  17575. this.morphNormals = source.morphNormals;
  17576. return this;
  17577. };
  17578. /**
  17579. * @author WestLangley / http://github.com/WestLangley
  17580. *
  17581. * parameters = {
  17582. * reflectivity: <float>
  17583. * }
  17584. */
  17585. function MeshPhysicalMaterial( parameters ) {
  17586. MeshStandardMaterial.call( this );
  17587. this.defines = { 'PHYSICAL': '' };
  17588. this.type = 'MeshPhysicalMaterial';
  17589. this.reflectivity = 0.5; // maps to F0 = 0.04
  17590. this.clearCoat = 0.0;
  17591. this.clearCoatRoughness = 0.0;
  17592. this.setValues( parameters );
  17593. }
  17594. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17595. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17596. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17597. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17598. MeshStandardMaterial.prototype.copy.call( this, source );
  17599. this.defines = { 'PHYSICAL': '' };
  17600. this.reflectivity = source.reflectivity;
  17601. this.clearCoat = source.clearCoat;
  17602. this.clearCoatRoughness = source.clearCoatRoughness;
  17603. return this;
  17604. };
  17605. /**
  17606. * @author mrdoob / http://mrdoob.com/
  17607. * @author alteredq / http://alteredqualia.com/
  17608. *
  17609. * parameters = {
  17610. * color: <hex>,
  17611. * specular: <hex>,
  17612. * shininess: <float>,
  17613. * opacity: <float>,
  17614. *
  17615. * map: new THREE.Texture( <Image> ),
  17616. *
  17617. * lightMap: new THREE.Texture( <Image> ),
  17618. * lightMapIntensity: <float>
  17619. *
  17620. * aoMap: new THREE.Texture( <Image> ),
  17621. * aoMapIntensity: <float>
  17622. *
  17623. * emissive: <hex>,
  17624. * emissiveIntensity: <float>
  17625. * emissiveMap: new THREE.Texture( <Image> ),
  17626. *
  17627. * bumpMap: new THREE.Texture( <Image> ),
  17628. * bumpScale: <float>,
  17629. *
  17630. * normalMap: new THREE.Texture( <Image> ),
  17631. * normalScale: <Vector2>,
  17632. *
  17633. * displacementMap: new THREE.Texture( <Image> ),
  17634. * displacementScale: <float>,
  17635. * displacementBias: <float>,
  17636. *
  17637. * specularMap: new THREE.Texture( <Image> ),
  17638. *
  17639. * alphaMap: new THREE.Texture( <Image> ),
  17640. *
  17641. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17642. * combine: THREE.Multiply,
  17643. * reflectivity: <float>,
  17644. * refractionRatio: <float>,
  17645. *
  17646. * wireframe: <boolean>,
  17647. * wireframeLinewidth: <float>,
  17648. *
  17649. * skinning: <bool>,
  17650. * morphTargets: <bool>,
  17651. * morphNormals: <bool>
  17652. * }
  17653. */
  17654. function MeshPhongMaterial( parameters ) {
  17655. Material.call( this );
  17656. this.type = 'MeshPhongMaterial';
  17657. this.color = new Color( 0xffffff ); // diffuse
  17658. this.specular = new Color( 0x111111 );
  17659. this.shininess = 30;
  17660. this.map = null;
  17661. this.lightMap = null;
  17662. this.lightMapIntensity = 1.0;
  17663. this.aoMap = null;
  17664. this.aoMapIntensity = 1.0;
  17665. this.emissive = new Color( 0x000000 );
  17666. this.emissiveIntensity = 1.0;
  17667. this.emissiveMap = null;
  17668. this.bumpMap = null;
  17669. this.bumpScale = 1;
  17670. this.normalMap = null;
  17671. this.normalScale = new Vector2( 1, 1 );
  17672. this.displacementMap = null;
  17673. this.displacementScale = 1;
  17674. this.displacementBias = 0;
  17675. this.specularMap = null;
  17676. this.alphaMap = null;
  17677. this.envMap = null;
  17678. this.combine = MultiplyOperation;
  17679. this.reflectivity = 1;
  17680. this.refractionRatio = 0.98;
  17681. this.wireframe = false;
  17682. this.wireframeLinewidth = 1;
  17683. this.wireframeLinecap = 'round';
  17684. this.wireframeLinejoin = 'round';
  17685. this.skinning = false;
  17686. this.morphTargets = false;
  17687. this.morphNormals = false;
  17688. this.setValues( parameters );
  17689. }
  17690. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17691. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17692. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17693. MeshPhongMaterial.prototype.copy = function ( source ) {
  17694. Material.prototype.copy.call( this, source );
  17695. this.color.copy( source.color );
  17696. this.specular.copy( source.specular );
  17697. this.shininess = source.shininess;
  17698. this.map = source.map;
  17699. this.lightMap = source.lightMap;
  17700. this.lightMapIntensity = source.lightMapIntensity;
  17701. this.aoMap = source.aoMap;
  17702. this.aoMapIntensity = source.aoMapIntensity;
  17703. this.emissive.copy( source.emissive );
  17704. this.emissiveMap = source.emissiveMap;
  17705. this.emissiveIntensity = source.emissiveIntensity;
  17706. this.bumpMap = source.bumpMap;
  17707. this.bumpScale = source.bumpScale;
  17708. this.normalMap = source.normalMap;
  17709. this.normalScale.copy( source.normalScale );
  17710. this.displacementMap = source.displacementMap;
  17711. this.displacementScale = source.displacementScale;
  17712. this.displacementBias = source.displacementBias;
  17713. this.specularMap = source.specularMap;
  17714. this.alphaMap = source.alphaMap;
  17715. this.envMap = source.envMap;
  17716. this.combine = source.combine;
  17717. this.reflectivity = source.reflectivity;
  17718. this.refractionRatio = source.refractionRatio;
  17719. this.wireframe = source.wireframe;
  17720. this.wireframeLinewidth = source.wireframeLinewidth;
  17721. this.wireframeLinecap = source.wireframeLinecap;
  17722. this.wireframeLinejoin = source.wireframeLinejoin;
  17723. this.skinning = source.skinning;
  17724. this.morphTargets = source.morphTargets;
  17725. this.morphNormals = source.morphNormals;
  17726. return this;
  17727. };
  17728. /**
  17729. * @author takahirox / http://github.com/takahirox
  17730. *
  17731. * parameters = {
  17732. * gradientMap: new THREE.Texture( <Image> )
  17733. * }
  17734. */
  17735. function MeshToonMaterial( parameters ) {
  17736. MeshPhongMaterial.call( this );
  17737. this.defines = { 'TOON': '' };
  17738. this.type = 'MeshToonMaterial';
  17739. this.gradientMap = null;
  17740. this.setValues( parameters );
  17741. }
  17742. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17743. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17744. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17745. MeshToonMaterial.prototype.copy = function ( source ) {
  17746. MeshPhongMaterial.prototype.copy.call( this, source );
  17747. this.gradientMap = source.gradientMap;
  17748. return this;
  17749. };
  17750. /**
  17751. * @author mrdoob / http://mrdoob.com/
  17752. * @author WestLangley / http://github.com/WestLangley
  17753. *
  17754. * parameters = {
  17755. * opacity: <float>,
  17756. *
  17757. * bumpMap: new THREE.Texture( <Image> ),
  17758. * bumpScale: <float>,
  17759. *
  17760. * normalMap: new THREE.Texture( <Image> ),
  17761. * normalScale: <Vector2>,
  17762. *
  17763. * displacementMap: new THREE.Texture( <Image> ),
  17764. * displacementScale: <float>,
  17765. * displacementBias: <float>,
  17766. *
  17767. * wireframe: <boolean>,
  17768. * wireframeLinewidth: <float>
  17769. *
  17770. * skinning: <bool>,
  17771. * morphTargets: <bool>,
  17772. * morphNormals: <bool>
  17773. * }
  17774. */
  17775. function MeshNormalMaterial( parameters ) {
  17776. Material.call( this );
  17777. this.type = 'MeshNormalMaterial';
  17778. this.bumpMap = null;
  17779. this.bumpScale = 1;
  17780. this.normalMap = null;
  17781. this.normalScale = new Vector2( 1, 1 );
  17782. this.displacementMap = null;
  17783. this.displacementScale = 1;
  17784. this.displacementBias = 0;
  17785. this.wireframe = false;
  17786. this.wireframeLinewidth = 1;
  17787. this.fog = false;
  17788. this.lights = false;
  17789. this.skinning = false;
  17790. this.morphTargets = false;
  17791. this.morphNormals = false;
  17792. this.setValues( parameters );
  17793. }
  17794. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17795. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17796. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17797. MeshNormalMaterial.prototype.copy = function ( source ) {
  17798. Material.prototype.copy.call( this, source );
  17799. this.bumpMap = source.bumpMap;
  17800. this.bumpScale = source.bumpScale;
  17801. this.normalMap = source.normalMap;
  17802. this.normalScale.copy( source.normalScale );
  17803. this.displacementMap = source.displacementMap;
  17804. this.displacementScale = source.displacementScale;
  17805. this.displacementBias = source.displacementBias;
  17806. this.wireframe = source.wireframe;
  17807. this.wireframeLinewidth = source.wireframeLinewidth;
  17808. this.skinning = source.skinning;
  17809. this.morphTargets = source.morphTargets;
  17810. this.morphNormals = source.morphNormals;
  17811. return this;
  17812. };
  17813. /**
  17814. * @author mrdoob / http://mrdoob.com/
  17815. * @author alteredq / http://alteredqualia.com/
  17816. *
  17817. * parameters = {
  17818. * color: <hex>,
  17819. * opacity: <float>,
  17820. *
  17821. * map: new THREE.Texture( <Image> ),
  17822. *
  17823. * lightMap: new THREE.Texture( <Image> ),
  17824. * lightMapIntensity: <float>
  17825. *
  17826. * aoMap: new THREE.Texture( <Image> ),
  17827. * aoMapIntensity: <float>
  17828. *
  17829. * emissive: <hex>,
  17830. * emissiveIntensity: <float>
  17831. * emissiveMap: new THREE.Texture( <Image> ),
  17832. *
  17833. * specularMap: new THREE.Texture( <Image> ),
  17834. *
  17835. * alphaMap: new THREE.Texture( <Image> ),
  17836. *
  17837. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17838. * combine: THREE.Multiply,
  17839. * reflectivity: <float>,
  17840. * refractionRatio: <float>,
  17841. *
  17842. * wireframe: <boolean>,
  17843. * wireframeLinewidth: <float>,
  17844. *
  17845. * skinning: <bool>,
  17846. * morphTargets: <bool>,
  17847. * morphNormals: <bool>
  17848. * }
  17849. */
  17850. function MeshLambertMaterial( parameters ) {
  17851. Material.call( this );
  17852. this.type = 'MeshLambertMaterial';
  17853. this.color = new Color( 0xffffff ); // diffuse
  17854. this.map = null;
  17855. this.lightMap = null;
  17856. this.lightMapIntensity = 1.0;
  17857. this.aoMap = null;
  17858. this.aoMapIntensity = 1.0;
  17859. this.emissive = new Color( 0x000000 );
  17860. this.emissiveIntensity = 1.0;
  17861. this.emissiveMap = null;
  17862. this.specularMap = null;
  17863. this.alphaMap = null;
  17864. this.envMap = null;
  17865. this.combine = MultiplyOperation;
  17866. this.reflectivity = 1;
  17867. this.refractionRatio = 0.98;
  17868. this.wireframe = false;
  17869. this.wireframeLinewidth = 1;
  17870. this.wireframeLinecap = 'round';
  17871. this.wireframeLinejoin = 'round';
  17872. this.skinning = false;
  17873. this.morphTargets = false;
  17874. this.morphNormals = false;
  17875. this.setValues( parameters );
  17876. }
  17877. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17878. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17879. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17880. MeshLambertMaterial.prototype.copy = function ( source ) {
  17881. Material.prototype.copy.call( this, source );
  17882. this.color.copy( source.color );
  17883. this.map = source.map;
  17884. this.lightMap = source.lightMap;
  17885. this.lightMapIntensity = source.lightMapIntensity;
  17886. this.aoMap = source.aoMap;
  17887. this.aoMapIntensity = source.aoMapIntensity;
  17888. this.emissive.copy( source.emissive );
  17889. this.emissiveMap = source.emissiveMap;
  17890. this.emissiveIntensity = source.emissiveIntensity;
  17891. this.specularMap = source.specularMap;
  17892. this.alphaMap = source.alphaMap;
  17893. this.envMap = source.envMap;
  17894. this.combine = source.combine;
  17895. this.reflectivity = source.reflectivity;
  17896. this.refractionRatio = source.refractionRatio;
  17897. this.wireframe = source.wireframe;
  17898. this.wireframeLinewidth = source.wireframeLinewidth;
  17899. this.wireframeLinecap = source.wireframeLinecap;
  17900. this.wireframeLinejoin = source.wireframeLinejoin;
  17901. this.skinning = source.skinning;
  17902. this.morphTargets = source.morphTargets;
  17903. this.morphNormals = source.morphNormals;
  17904. return this;
  17905. };
  17906. /**
  17907. * @author alteredq / http://alteredqualia.com/
  17908. *
  17909. * parameters = {
  17910. * color: <hex>,
  17911. * opacity: <float>,
  17912. *
  17913. * linewidth: <float>,
  17914. *
  17915. * scale: <float>,
  17916. * dashSize: <float>,
  17917. * gapSize: <float>
  17918. * }
  17919. */
  17920. function LineDashedMaterial( parameters ) {
  17921. LineBasicMaterial.call( this );
  17922. this.type = 'LineDashedMaterial';
  17923. this.scale = 1;
  17924. this.dashSize = 3;
  17925. this.gapSize = 1;
  17926. this.setValues( parameters );
  17927. }
  17928. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  17929. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17930. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17931. LineDashedMaterial.prototype.copy = function ( source ) {
  17932. LineBasicMaterial.prototype.copy.call( this, source );
  17933. this.scale = source.scale;
  17934. this.dashSize = source.dashSize;
  17935. this.gapSize = source.gapSize;
  17936. return this;
  17937. };
  17938. var Materials = Object.freeze({
  17939. ShadowMaterial: ShadowMaterial,
  17940. SpriteMaterial: SpriteMaterial,
  17941. RawShaderMaterial: RawShaderMaterial,
  17942. ShaderMaterial: ShaderMaterial,
  17943. PointsMaterial: PointsMaterial,
  17944. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17945. MeshStandardMaterial: MeshStandardMaterial,
  17946. MeshPhongMaterial: MeshPhongMaterial,
  17947. MeshToonMaterial: MeshToonMaterial,
  17948. MeshNormalMaterial: MeshNormalMaterial,
  17949. MeshLambertMaterial: MeshLambertMaterial,
  17950. MeshDepthMaterial: MeshDepthMaterial,
  17951. MeshDistanceMaterial: MeshDistanceMaterial,
  17952. MeshBasicMaterial: MeshBasicMaterial,
  17953. LineDashedMaterial: LineDashedMaterial,
  17954. LineBasicMaterial: LineBasicMaterial,
  17955. Material: Material
  17956. });
  17957. /**
  17958. * @author mrdoob / http://mrdoob.com/
  17959. */
  17960. var Cache = {
  17961. enabled: false,
  17962. files: {},
  17963. add: function ( key, file ) {
  17964. if ( this.enabled === false ) return;
  17965. // console.log( 'THREE.Cache', 'Adding key:', key );
  17966. this.files[ key ] = file;
  17967. },
  17968. get: function ( key ) {
  17969. if ( this.enabled === false ) return;
  17970. // console.log( 'THREE.Cache', 'Checking key:', key );
  17971. return this.files[ key ];
  17972. },
  17973. remove: function ( key ) {
  17974. delete this.files[ key ];
  17975. },
  17976. clear: function () {
  17977. this.files = {};
  17978. }
  17979. };
  17980. /**
  17981. * @author mrdoob / http://mrdoob.com/
  17982. */
  17983. function LoadingManager( onLoad, onProgress, onError ) {
  17984. var scope = this;
  17985. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17986. this.onStart = undefined;
  17987. this.onLoad = onLoad;
  17988. this.onProgress = onProgress;
  17989. this.onError = onError;
  17990. this.itemStart = function ( url ) {
  17991. itemsTotal ++;
  17992. if ( isLoading === false ) {
  17993. if ( scope.onStart !== undefined ) {
  17994. scope.onStart( url, itemsLoaded, itemsTotal );
  17995. }
  17996. }
  17997. isLoading = true;
  17998. };
  17999. this.itemEnd = function ( url ) {
  18000. itemsLoaded ++;
  18001. if ( scope.onProgress !== undefined ) {
  18002. scope.onProgress( url, itemsLoaded, itemsTotal );
  18003. }
  18004. if ( itemsLoaded === itemsTotal ) {
  18005. isLoading = false;
  18006. if ( scope.onLoad !== undefined ) {
  18007. scope.onLoad();
  18008. }
  18009. }
  18010. };
  18011. this.itemError = function ( url ) {
  18012. if ( scope.onError !== undefined ) {
  18013. scope.onError( url );
  18014. }
  18015. };
  18016. }
  18017. var DefaultLoadingManager = new LoadingManager();
  18018. /**
  18019. * @author mrdoob / http://mrdoob.com/
  18020. */
  18021. function FileLoader( manager ) {
  18022. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18023. }
  18024. Object.assign( FileLoader.prototype, {
  18025. load: function ( url, onLoad, onProgress, onError ) {
  18026. if ( url === undefined ) url = '';
  18027. if ( this.path !== undefined ) url = this.path + url;
  18028. var scope = this;
  18029. var cached = Cache.get( url );
  18030. if ( cached !== undefined ) {
  18031. scope.manager.itemStart( url );
  18032. setTimeout( function () {
  18033. if ( onLoad ) onLoad( cached );
  18034. scope.manager.itemEnd( url );
  18035. }, 0 );
  18036. return cached;
  18037. }
  18038. // Check for data: URI
  18039. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  18040. var dataUriRegexResult = url.match( dataUriRegex );
  18041. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  18042. if ( dataUriRegexResult ) {
  18043. var mimeType = dataUriRegexResult[ 1 ];
  18044. var isBase64 = !! dataUriRegexResult[ 2 ];
  18045. var data = dataUriRegexResult[ 3 ];
  18046. data = window.decodeURIComponent( data );
  18047. if ( isBase64 ) data = window.atob( data );
  18048. try {
  18049. var response;
  18050. var responseType = ( this.responseType || '' ).toLowerCase();
  18051. switch ( responseType ) {
  18052. case 'arraybuffer':
  18053. case 'blob':
  18054. response = new ArrayBuffer( data.length );
  18055. var view = new Uint8Array( response );
  18056. for ( var i = 0; i < data.length; i ++ ) {
  18057. view[ i ] = data.charCodeAt( i );
  18058. }
  18059. if ( responseType === 'blob' ) {
  18060. response = new Blob( [ response ], { type: mimeType } );
  18061. }
  18062. break;
  18063. case 'document':
  18064. var parser = new DOMParser();
  18065. response = parser.parseFromString( data, mimeType );
  18066. break;
  18067. case 'json':
  18068. response = JSON.parse( data );
  18069. break;
  18070. default: // 'text' or other
  18071. response = data;
  18072. break;
  18073. }
  18074. // Wait for next browser tick
  18075. window.setTimeout( function () {
  18076. if ( onLoad ) onLoad( response );
  18077. scope.manager.itemEnd( url );
  18078. }, 0 );
  18079. } catch ( error ) {
  18080. // Wait for next browser tick
  18081. window.setTimeout( function () {
  18082. if ( onError ) onError( error );
  18083. scope.manager.itemEnd( url );
  18084. scope.manager.itemError( url );
  18085. }, 0 );
  18086. }
  18087. } else {
  18088. var request = new XMLHttpRequest();
  18089. request.open( 'GET', url, true );
  18090. request.addEventListener( 'load', function ( event ) {
  18091. var response = event.target.response;
  18092. Cache.add( url, response );
  18093. if ( this.status === 200 ) {
  18094. if ( onLoad ) onLoad( response );
  18095. scope.manager.itemEnd( url );
  18096. } else if ( this.status === 0 ) {
  18097. // Some browsers return HTTP Status 0 when using non-http protocol
  18098. // e.g. 'file://' or 'data://'. Handle as success.
  18099. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  18100. if ( onLoad ) onLoad( response );
  18101. scope.manager.itemEnd( url );
  18102. } else {
  18103. if ( onError ) onError( event );
  18104. scope.manager.itemEnd( url );
  18105. scope.manager.itemError( url );
  18106. }
  18107. }, false );
  18108. if ( onProgress !== undefined ) {
  18109. request.addEventListener( 'progress', function ( event ) {
  18110. onProgress( event );
  18111. }, false );
  18112. }
  18113. request.addEventListener( 'error', function ( event ) {
  18114. if ( onError ) onError( event );
  18115. scope.manager.itemEnd( url );
  18116. scope.manager.itemError( url );
  18117. }, false );
  18118. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  18119. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  18120. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  18121. for ( var header in this.requestHeader ) {
  18122. request.setRequestHeader( header, this.requestHeader[ header ] );
  18123. }
  18124. request.send( null );
  18125. }
  18126. scope.manager.itemStart( url );
  18127. return request;
  18128. },
  18129. setPath: function ( value ) {
  18130. this.path = value;
  18131. return this;
  18132. },
  18133. setResponseType: function ( value ) {
  18134. this.responseType = value;
  18135. return this;
  18136. },
  18137. setWithCredentials: function ( value ) {
  18138. this.withCredentials = value;
  18139. return this;
  18140. },
  18141. setMimeType: function ( value ) {
  18142. this.mimeType = value;
  18143. return this;
  18144. },
  18145. setRequestHeader: function ( value ) {
  18146. this.requestHeader = value;
  18147. return this;
  18148. }
  18149. } );
  18150. /**
  18151. * @author mrdoob / http://mrdoob.com/
  18152. *
  18153. * Abstract Base class to block based textures loader (dds, pvr, ...)
  18154. */
  18155. function CompressedTextureLoader( manager ) {
  18156. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18157. // override in sub classes
  18158. this._parser = null;
  18159. }
  18160. Object.assign( CompressedTextureLoader.prototype, {
  18161. load: function ( url, onLoad, onProgress, onError ) {
  18162. var scope = this;
  18163. var images = [];
  18164. var texture = new CompressedTexture();
  18165. texture.image = images;
  18166. var loader = new FileLoader( this.manager );
  18167. loader.setPath( this.path );
  18168. loader.setResponseType( 'arraybuffer' );
  18169. function loadTexture( i ) {
  18170. loader.load( url[ i ], function ( buffer ) {
  18171. var texDatas = scope._parser( buffer, true );
  18172. images[ i ] = {
  18173. width: texDatas.width,
  18174. height: texDatas.height,
  18175. format: texDatas.format,
  18176. mipmaps: texDatas.mipmaps
  18177. };
  18178. loaded += 1;
  18179. if ( loaded === 6 ) {
  18180. if ( texDatas.mipmapCount === 1 )
  18181. texture.minFilter = LinearFilter;
  18182. texture.format = texDatas.format;
  18183. texture.needsUpdate = true;
  18184. if ( onLoad ) onLoad( texture );
  18185. }
  18186. }, onProgress, onError );
  18187. }
  18188. if ( Array.isArray( url ) ) {
  18189. var loaded = 0;
  18190. for ( var i = 0, il = url.length; i < il; ++ i ) {
  18191. loadTexture( i );
  18192. }
  18193. } else {
  18194. // compressed cubemap texture stored in a single DDS file
  18195. loader.load( url, function ( buffer ) {
  18196. var texDatas = scope._parser( buffer, true );
  18197. if ( texDatas.isCubemap ) {
  18198. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  18199. for ( var f = 0; f < faces; f ++ ) {
  18200. images[ f ] = { mipmaps : [] };
  18201. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  18202. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  18203. images[ f ].format = texDatas.format;
  18204. images[ f ].width = texDatas.width;
  18205. images[ f ].height = texDatas.height;
  18206. }
  18207. }
  18208. } else {
  18209. texture.image.width = texDatas.width;
  18210. texture.image.height = texDatas.height;
  18211. texture.mipmaps = texDatas.mipmaps;
  18212. }
  18213. if ( texDatas.mipmapCount === 1 ) {
  18214. texture.minFilter = LinearFilter;
  18215. }
  18216. texture.format = texDatas.format;
  18217. texture.needsUpdate = true;
  18218. if ( onLoad ) onLoad( texture );
  18219. }, onProgress, onError );
  18220. }
  18221. return texture;
  18222. },
  18223. setPath: function ( value ) {
  18224. this.path = value;
  18225. return this;
  18226. }
  18227. } );
  18228. /**
  18229. * @author Nikos M. / https://github.com/foo123/
  18230. *
  18231. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18232. */
  18233. function DataTextureLoader( manager ) {
  18234. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18235. // override in sub classes
  18236. this._parser = null;
  18237. }
  18238. Object.assign( DataTextureLoader.prototype, {
  18239. load: function ( url, onLoad, onProgress, onError ) {
  18240. var scope = this;
  18241. var texture = new DataTexture();
  18242. var loader = new FileLoader( this.manager );
  18243. loader.setResponseType( 'arraybuffer' );
  18244. loader.load( url, function ( buffer ) {
  18245. var texData = scope._parser( buffer );
  18246. if ( ! texData ) return;
  18247. if ( undefined !== texData.image ) {
  18248. texture.image = texData.image;
  18249. } else if ( undefined !== texData.data ) {
  18250. texture.image.width = texData.width;
  18251. texture.image.height = texData.height;
  18252. texture.image.data = texData.data;
  18253. }
  18254. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  18255. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  18256. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  18257. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  18258. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  18259. if ( undefined !== texData.format ) {
  18260. texture.format = texData.format;
  18261. }
  18262. if ( undefined !== texData.type ) {
  18263. texture.type = texData.type;
  18264. }
  18265. if ( undefined !== texData.mipmaps ) {
  18266. texture.mipmaps = texData.mipmaps;
  18267. }
  18268. if ( 1 === texData.mipmapCount ) {
  18269. texture.minFilter = LinearFilter;
  18270. }
  18271. texture.needsUpdate = true;
  18272. if ( onLoad ) onLoad( texture, texData );
  18273. }, onProgress, onError );
  18274. return texture;
  18275. }
  18276. } );
  18277. /**
  18278. * @author mrdoob / http://mrdoob.com/
  18279. */
  18280. function ImageLoader( manager ) {
  18281. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18282. }
  18283. Object.assign( ImageLoader.prototype, {
  18284. crossOrigin: 'Anonymous',
  18285. load: function ( url, onLoad, onProgress, onError ) {
  18286. if ( url === undefined ) url = '';
  18287. if ( this.path !== undefined ) url = this.path + url;
  18288. var scope = this;
  18289. var cached = Cache.get( url );
  18290. if ( cached !== undefined ) {
  18291. scope.manager.itemStart( url );
  18292. setTimeout( function () {
  18293. if ( onLoad ) onLoad( cached );
  18294. scope.manager.itemEnd( url );
  18295. }, 0 );
  18296. return cached;
  18297. }
  18298. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  18299. image.addEventListener( 'load', function () {
  18300. Cache.add( url, this );
  18301. if ( onLoad ) onLoad( this );
  18302. scope.manager.itemEnd( url );
  18303. }, false );
  18304. /*
  18305. image.addEventListener( 'progress', function ( event ) {
  18306. if ( onProgress ) onProgress( event );
  18307. }, false );
  18308. */
  18309. image.addEventListener( 'error', function ( event ) {
  18310. if ( onError ) onError( event );
  18311. scope.manager.itemEnd( url );
  18312. scope.manager.itemError( url );
  18313. }, false );
  18314. if ( url.substr( 0, 5 ) !== 'data:' ) {
  18315. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18316. }
  18317. scope.manager.itemStart( url );
  18318. image.src = url;
  18319. return image;
  18320. },
  18321. setCrossOrigin: function ( value ) {
  18322. this.crossOrigin = value;
  18323. return this;
  18324. },
  18325. setPath: function ( value ) {
  18326. this.path = value;
  18327. return this;
  18328. }
  18329. } );
  18330. /**
  18331. * @author mrdoob / http://mrdoob.com/
  18332. */
  18333. function CubeTextureLoader( manager ) {
  18334. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18335. }
  18336. Object.assign( CubeTextureLoader.prototype, {
  18337. crossOrigin: 'Anonymous',
  18338. load: function ( urls, onLoad, onProgress, onError ) {
  18339. var texture = new CubeTexture();
  18340. var loader = new ImageLoader( this.manager );
  18341. loader.setCrossOrigin( this.crossOrigin );
  18342. loader.setPath( this.path );
  18343. var loaded = 0;
  18344. function loadTexture( i ) {
  18345. loader.load( urls[ i ], function ( image ) {
  18346. texture.images[ i ] = image;
  18347. loaded ++;
  18348. if ( loaded === 6 ) {
  18349. texture.needsUpdate = true;
  18350. if ( onLoad ) onLoad( texture );
  18351. }
  18352. }, undefined, onError );
  18353. }
  18354. for ( var i = 0; i < urls.length; ++ i ) {
  18355. loadTexture( i );
  18356. }
  18357. return texture;
  18358. },
  18359. setCrossOrigin: function ( value ) {
  18360. this.crossOrigin = value;
  18361. return this;
  18362. },
  18363. setPath: function ( value ) {
  18364. this.path = value;
  18365. return this;
  18366. }
  18367. } );
  18368. /**
  18369. * @author mrdoob / http://mrdoob.com/
  18370. */
  18371. function TextureLoader( manager ) {
  18372. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18373. }
  18374. Object.assign( TextureLoader.prototype, {
  18375. crossOrigin: 'Anonymous',
  18376. load: function ( url, onLoad, onProgress, onError ) {
  18377. var loader = new ImageLoader( this.manager );
  18378. loader.setCrossOrigin( this.crossOrigin );
  18379. loader.setPath( this.path );
  18380. var texture = new Texture();
  18381. texture.image = loader.load( url, function () {
  18382. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18383. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18384. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18385. texture.needsUpdate = true;
  18386. if ( onLoad !== undefined ) {
  18387. onLoad( texture );
  18388. }
  18389. }, onProgress, onError );
  18390. return texture;
  18391. },
  18392. setCrossOrigin: function ( value ) {
  18393. this.crossOrigin = value;
  18394. return this;
  18395. },
  18396. setPath: function ( value ) {
  18397. this.path = value;
  18398. return this;
  18399. }
  18400. } );
  18401. /**
  18402. * @author mrdoob / http://mrdoob.com/
  18403. * @author alteredq / http://alteredqualia.com/
  18404. */
  18405. function Light( color, intensity ) {
  18406. Object3D.call( this );
  18407. this.type = 'Light';
  18408. this.color = new Color( color );
  18409. this.intensity = intensity !== undefined ? intensity : 1;
  18410. this.receiveShadow = undefined;
  18411. }
  18412. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18413. constructor: Light,
  18414. isLight: true,
  18415. copy: function ( source ) {
  18416. Object3D.prototype.copy.call( this, source );
  18417. this.color.copy( source.color );
  18418. this.intensity = source.intensity;
  18419. return this;
  18420. },
  18421. toJSON: function ( meta ) {
  18422. var data = Object3D.prototype.toJSON.call( this, meta );
  18423. data.object.color = this.color.getHex();
  18424. data.object.intensity = this.intensity;
  18425. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18426. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18427. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18428. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18429. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18430. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18431. return data;
  18432. }
  18433. } );
  18434. /**
  18435. * @author alteredq / http://alteredqualia.com/
  18436. */
  18437. function HemisphereLight( skyColor, groundColor, intensity ) {
  18438. Light.call( this, skyColor, intensity );
  18439. this.type = 'HemisphereLight';
  18440. this.castShadow = undefined;
  18441. this.position.copy( Object3D.DefaultUp );
  18442. this.updateMatrix();
  18443. this.groundColor = new Color( groundColor );
  18444. }
  18445. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18446. constructor: HemisphereLight,
  18447. isHemisphereLight: true,
  18448. copy: function ( source ) {
  18449. Light.prototype.copy.call( this, source );
  18450. this.groundColor.copy( source.groundColor );
  18451. return this;
  18452. }
  18453. } );
  18454. /**
  18455. * @author mrdoob / http://mrdoob.com/
  18456. */
  18457. function LightShadow( camera ) {
  18458. this.camera = camera;
  18459. this.bias = 0;
  18460. this.radius = 1;
  18461. this.mapSize = new Vector2( 512, 512 );
  18462. this.map = null;
  18463. this.matrix = new Matrix4();
  18464. }
  18465. Object.assign( LightShadow.prototype, {
  18466. copy: function ( source ) {
  18467. this.camera = source.camera.clone();
  18468. this.bias = source.bias;
  18469. this.radius = source.radius;
  18470. this.mapSize.copy( source.mapSize );
  18471. return this;
  18472. },
  18473. clone: function () {
  18474. return new this.constructor().copy( this );
  18475. },
  18476. toJSON: function () {
  18477. var object = {};
  18478. if ( this.bias !== 0 ) object.bias = this.bias;
  18479. if ( this.radius !== 1 ) object.radius = this.radius;
  18480. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18481. object.camera = this.camera.toJSON( false ).object;
  18482. delete object.camera.matrix;
  18483. return object;
  18484. }
  18485. } );
  18486. /**
  18487. * @author mrdoob / http://mrdoob.com/
  18488. */
  18489. function SpotLightShadow() {
  18490. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18491. }
  18492. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18493. constructor: SpotLightShadow,
  18494. isSpotLightShadow: true,
  18495. update: function ( light ) {
  18496. var camera = this.camera;
  18497. var fov = _Math.RAD2DEG * 2 * light.angle;
  18498. var aspect = this.mapSize.width / this.mapSize.height;
  18499. var far = light.distance || camera.far;
  18500. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18501. camera.fov = fov;
  18502. camera.aspect = aspect;
  18503. camera.far = far;
  18504. camera.updateProjectionMatrix();
  18505. }
  18506. }
  18507. } );
  18508. /**
  18509. * @author alteredq / http://alteredqualia.com/
  18510. */
  18511. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18512. Light.call( this, color, intensity );
  18513. this.type = 'SpotLight';
  18514. this.position.copy( Object3D.DefaultUp );
  18515. this.updateMatrix();
  18516. this.target = new Object3D();
  18517. Object.defineProperty( this, 'power', {
  18518. get: function () {
  18519. // intensity = power per solid angle.
  18520. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18521. return this.intensity * Math.PI;
  18522. },
  18523. set: function ( power ) {
  18524. // intensity = power per solid angle.
  18525. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18526. this.intensity = power / Math.PI;
  18527. }
  18528. } );
  18529. this.distance = ( distance !== undefined ) ? distance : 0;
  18530. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18531. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18532. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18533. this.shadow = new SpotLightShadow();
  18534. }
  18535. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18536. constructor: SpotLight,
  18537. isSpotLight: true,
  18538. copy: function ( source ) {
  18539. Light.prototype.copy.call( this, source );
  18540. this.distance = source.distance;
  18541. this.angle = source.angle;
  18542. this.penumbra = source.penumbra;
  18543. this.decay = source.decay;
  18544. this.target = source.target.clone();
  18545. this.shadow = source.shadow.clone();
  18546. return this;
  18547. }
  18548. } );
  18549. /**
  18550. * @author mrdoob / http://mrdoob.com/
  18551. */
  18552. function PointLight( color, intensity, distance, decay ) {
  18553. Light.call( this, color, intensity );
  18554. this.type = 'PointLight';
  18555. Object.defineProperty( this, 'power', {
  18556. get: function () {
  18557. // intensity = power per solid angle.
  18558. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18559. return this.intensity * 4 * Math.PI;
  18560. },
  18561. set: function ( power ) {
  18562. // intensity = power per solid angle.
  18563. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18564. this.intensity = power / ( 4 * Math.PI );
  18565. }
  18566. } );
  18567. this.distance = ( distance !== undefined ) ? distance : 0;
  18568. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18569. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18570. }
  18571. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18572. constructor: PointLight,
  18573. isPointLight: true,
  18574. copy: function ( source ) {
  18575. Light.prototype.copy.call( this, source );
  18576. this.distance = source.distance;
  18577. this.decay = source.decay;
  18578. this.shadow = source.shadow.clone();
  18579. return this;
  18580. }
  18581. } );
  18582. /**
  18583. * @author mrdoob / http://mrdoob.com/
  18584. */
  18585. function DirectionalLightShadow( ) {
  18586. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18587. }
  18588. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18589. constructor: DirectionalLightShadow
  18590. } );
  18591. /**
  18592. * @author mrdoob / http://mrdoob.com/
  18593. * @author alteredq / http://alteredqualia.com/
  18594. */
  18595. function DirectionalLight( color, intensity ) {
  18596. Light.call( this, color, intensity );
  18597. this.type = 'DirectionalLight';
  18598. this.position.copy( Object3D.DefaultUp );
  18599. this.updateMatrix();
  18600. this.target = new Object3D();
  18601. this.shadow = new DirectionalLightShadow();
  18602. }
  18603. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18604. constructor: DirectionalLight,
  18605. isDirectionalLight: true,
  18606. copy: function ( source ) {
  18607. Light.prototype.copy.call( this, source );
  18608. this.target = source.target.clone();
  18609. this.shadow = source.shadow.clone();
  18610. return this;
  18611. }
  18612. } );
  18613. /**
  18614. * @author mrdoob / http://mrdoob.com/
  18615. */
  18616. function AmbientLight( color, intensity ) {
  18617. Light.call( this, color, intensity );
  18618. this.type = 'AmbientLight';
  18619. this.castShadow = undefined;
  18620. }
  18621. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18622. constructor: AmbientLight,
  18623. isAmbientLight: true
  18624. } );
  18625. /**
  18626. * @author abelnation / http://github.com/abelnation
  18627. */
  18628. function RectAreaLight( color, intensity, width, height ) {
  18629. Light.call( this, color, intensity );
  18630. this.type = 'RectAreaLight';
  18631. this.position.set( 0, 1, 0 );
  18632. this.updateMatrix();
  18633. this.width = ( width !== undefined ) ? width : 10;
  18634. this.height = ( height !== undefined ) ? height : 10;
  18635. // TODO (abelnation): distance/decay
  18636. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18637. // TODO (abelnation): shadows
  18638. }
  18639. // TODO (abelnation): RectAreaLight update when light shape is changed
  18640. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18641. constructor: RectAreaLight,
  18642. isRectAreaLight: true,
  18643. copy: function ( source ) {
  18644. Light.prototype.copy.call( this, source );
  18645. this.width = source.width;
  18646. this.height = source.height;
  18647. return this;
  18648. },
  18649. toJSON: function ( meta ) {
  18650. var data = Light.prototype.toJSON.call( this, meta );
  18651. data.object.width = this.width;
  18652. data.object.height = this.height;
  18653. return data;
  18654. }
  18655. } );
  18656. /**
  18657. * @author tschw
  18658. * @author Ben Houston / http://clara.io/
  18659. * @author David Sarno / http://lighthaus.us/
  18660. */
  18661. var AnimationUtils = {
  18662. // same as Array.prototype.slice, but also works on typed arrays
  18663. arraySlice: function ( array, from, to ) {
  18664. if ( AnimationUtils.isTypedArray( array ) ) {
  18665. // in ios9 array.subarray(from, undefined) will return empty array
  18666. // but array.subarray(from) or array.subarray(from, len) is correct
  18667. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18668. }
  18669. return array.slice( from, to );
  18670. },
  18671. // converts an array to a specific type
  18672. convertArray: function ( array, type, forceClone ) {
  18673. if ( ! array || // let 'undefined' and 'null' pass
  18674. ! forceClone && array.constructor === type ) return array;
  18675. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18676. return new type( array ); // create typed array
  18677. }
  18678. return Array.prototype.slice.call( array ); // create Array
  18679. },
  18680. isTypedArray: function ( object ) {
  18681. return ArrayBuffer.isView( object ) &&
  18682. ! ( object instanceof DataView );
  18683. },
  18684. // returns an array by which times and values can be sorted
  18685. getKeyframeOrder: function ( times ) {
  18686. function compareTime( i, j ) {
  18687. return times[ i ] - times[ j ];
  18688. }
  18689. var n = times.length;
  18690. var result = new Array( n );
  18691. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18692. result.sort( compareTime );
  18693. return result;
  18694. },
  18695. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18696. sortedArray: function ( values, stride, order ) {
  18697. var nValues = values.length;
  18698. var result = new values.constructor( nValues );
  18699. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18700. var srcOffset = order[ i ] * stride;
  18701. for ( var j = 0; j !== stride; ++ j ) {
  18702. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18703. }
  18704. }
  18705. return result;
  18706. },
  18707. // function for parsing AOS keyframe formats
  18708. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18709. var i = 1, key = jsonKeys[ 0 ];
  18710. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18711. key = jsonKeys[ i ++ ];
  18712. }
  18713. if ( key === undefined ) return; // no data
  18714. var value = key[ valuePropertyName ];
  18715. if ( value === undefined ) return; // no data
  18716. if ( Array.isArray( value ) ) {
  18717. do {
  18718. value = key[ valuePropertyName ];
  18719. if ( value !== undefined ) {
  18720. times.push( key.time );
  18721. values.push.apply( values, value ); // push all elements
  18722. }
  18723. key = jsonKeys[ i ++ ];
  18724. } while ( key !== undefined );
  18725. } else if ( value.toArray !== undefined ) {
  18726. // ...assume THREE.Math-ish
  18727. do {
  18728. value = key[ valuePropertyName ];
  18729. if ( value !== undefined ) {
  18730. times.push( key.time );
  18731. value.toArray( values, values.length );
  18732. }
  18733. key = jsonKeys[ i ++ ];
  18734. } while ( key !== undefined );
  18735. } else {
  18736. // otherwise push as-is
  18737. do {
  18738. value = key[ valuePropertyName ];
  18739. if ( value !== undefined ) {
  18740. times.push( key.time );
  18741. values.push( value );
  18742. }
  18743. key = jsonKeys[ i ++ ];
  18744. } while ( key !== undefined );
  18745. }
  18746. }
  18747. };
  18748. /**
  18749. * Abstract base class of interpolants over parametric samples.
  18750. *
  18751. * The parameter domain is one dimensional, typically the time or a path
  18752. * along a curve defined by the data.
  18753. *
  18754. * The sample values can have any dimensionality and derived classes may
  18755. * apply special interpretations to the data.
  18756. *
  18757. * This class provides the interval seek in a Template Method, deferring
  18758. * the actual interpolation to derived classes.
  18759. *
  18760. * Time complexity is O(1) for linear access crossing at most two points
  18761. * and O(log N) for random access, where N is the number of positions.
  18762. *
  18763. * References:
  18764. *
  18765. * http://www.oodesign.com/template-method-pattern.html
  18766. *
  18767. * @author tschw
  18768. */
  18769. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18770. this.parameterPositions = parameterPositions;
  18771. this._cachedIndex = 0;
  18772. this.resultBuffer = resultBuffer !== undefined ?
  18773. resultBuffer : new sampleValues.constructor( sampleSize );
  18774. this.sampleValues = sampleValues;
  18775. this.valueSize = sampleSize;
  18776. }
  18777. Object.assign( Interpolant.prototype, {
  18778. evaluate: function( t ) {
  18779. var pp = this.parameterPositions,
  18780. i1 = this._cachedIndex,
  18781. t1 = pp[ i1 ],
  18782. t0 = pp[ i1 - 1 ];
  18783. validate_interval: {
  18784. seek: {
  18785. var right;
  18786. linear_scan: {
  18787. //- See http://jsperf.com/comparison-to-undefined/3
  18788. //- slower code:
  18789. //-
  18790. //- if ( t >= t1 || t1 === undefined ) {
  18791. forward_scan: if ( ! ( t < t1 ) ) {
  18792. for ( var giveUpAt = i1 + 2; ;) {
  18793. if ( t1 === undefined ) {
  18794. if ( t < t0 ) break forward_scan;
  18795. // after end
  18796. i1 = pp.length;
  18797. this._cachedIndex = i1;
  18798. return this.afterEnd_( i1 - 1, t, t0 );
  18799. }
  18800. if ( i1 === giveUpAt ) break; // this loop
  18801. t0 = t1;
  18802. t1 = pp[ ++ i1 ];
  18803. if ( t < t1 ) {
  18804. // we have arrived at the sought interval
  18805. break seek;
  18806. }
  18807. }
  18808. // prepare binary search on the right side of the index
  18809. right = pp.length;
  18810. break linear_scan;
  18811. }
  18812. //- slower code:
  18813. //- if ( t < t0 || t0 === undefined ) {
  18814. if ( ! ( t >= t0 ) ) {
  18815. // looping?
  18816. var t1global = pp[ 1 ];
  18817. if ( t < t1global ) {
  18818. i1 = 2; // + 1, using the scan for the details
  18819. t0 = t1global;
  18820. }
  18821. // linear reverse scan
  18822. for ( var giveUpAt = i1 - 2; ;) {
  18823. if ( t0 === undefined ) {
  18824. // before start
  18825. this._cachedIndex = 0;
  18826. return this.beforeStart_( 0, t, t1 );
  18827. }
  18828. if ( i1 === giveUpAt ) break; // this loop
  18829. t1 = t0;
  18830. t0 = pp[ -- i1 - 1 ];
  18831. if ( t >= t0 ) {
  18832. // we have arrived at the sought interval
  18833. break seek;
  18834. }
  18835. }
  18836. // prepare binary search on the left side of the index
  18837. right = i1;
  18838. i1 = 0;
  18839. break linear_scan;
  18840. }
  18841. // the interval is valid
  18842. break validate_interval;
  18843. } // linear scan
  18844. // binary search
  18845. while ( i1 < right ) {
  18846. var mid = ( i1 + right ) >>> 1;
  18847. if ( t < pp[ mid ] ) {
  18848. right = mid;
  18849. } else {
  18850. i1 = mid + 1;
  18851. }
  18852. }
  18853. t1 = pp[ i1 ];
  18854. t0 = pp[ i1 - 1 ];
  18855. // check boundary cases, again
  18856. if ( t0 === undefined ) {
  18857. this._cachedIndex = 0;
  18858. return this.beforeStart_( 0, t, t1 );
  18859. }
  18860. if ( t1 === undefined ) {
  18861. i1 = pp.length;
  18862. this._cachedIndex = i1;
  18863. return this.afterEnd_( i1 - 1, t0, t );
  18864. }
  18865. } // seek
  18866. this._cachedIndex = i1;
  18867. this.intervalChanged_( i1, t0, t1 );
  18868. } // validate_interval
  18869. return this.interpolate_( i1, t0, t, t1 );
  18870. },
  18871. settings: null, // optional, subclass-specific settings structure
  18872. // Note: The indirection allows central control of many interpolants.
  18873. // --- Protected interface
  18874. DefaultSettings_: {},
  18875. getSettings_: function() {
  18876. return this.settings || this.DefaultSettings_;
  18877. },
  18878. copySampleValue_: function( index ) {
  18879. // copies a sample value to the result buffer
  18880. var result = this.resultBuffer,
  18881. values = this.sampleValues,
  18882. stride = this.valueSize,
  18883. offset = index * stride;
  18884. for ( var i = 0; i !== stride; ++ i ) {
  18885. result[ i ] = values[ offset + i ];
  18886. }
  18887. return result;
  18888. },
  18889. // Template methods for derived classes:
  18890. interpolate_: function( i1, t0, t, t1 ) {
  18891. throw new Error( "call to abstract method" );
  18892. // implementations shall return this.resultBuffer
  18893. },
  18894. intervalChanged_: function( i1, t0, t1 ) {
  18895. // empty
  18896. }
  18897. } );
  18898. //!\ DECLARE ALIAS AFTER assign prototype !
  18899. Object.assign( Interpolant.prototype, {
  18900. //( 0, t, t0 ), returns this.resultBuffer
  18901. beforeStart_: Interpolant.prototype.copySampleValue_,
  18902. //( N-1, tN-1, t ), returns this.resultBuffer
  18903. afterEnd_: Interpolant.prototype.copySampleValue_,
  18904. } );
  18905. /**
  18906. * Fast and simple cubic spline interpolant.
  18907. *
  18908. * It was derived from a Hermitian construction setting the first derivative
  18909. * at each sample position to the linear slope between neighboring positions
  18910. * over their parameter interval.
  18911. *
  18912. * @author tschw
  18913. */
  18914. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18915. Interpolant.call(
  18916. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18917. this._weightPrev = -0;
  18918. this._offsetPrev = -0;
  18919. this._weightNext = -0;
  18920. this._offsetNext = -0;
  18921. }
  18922. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18923. constructor: CubicInterpolant,
  18924. DefaultSettings_: {
  18925. endingStart: ZeroCurvatureEnding,
  18926. endingEnd: ZeroCurvatureEnding
  18927. },
  18928. intervalChanged_: function( i1, t0, t1 ) {
  18929. var pp = this.parameterPositions,
  18930. iPrev = i1 - 2,
  18931. iNext = i1 + 1,
  18932. tPrev = pp[ iPrev ],
  18933. tNext = pp[ iNext ];
  18934. if ( tPrev === undefined ) {
  18935. switch ( this.getSettings_().endingStart ) {
  18936. case ZeroSlopeEnding:
  18937. // f'(t0) = 0
  18938. iPrev = i1;
  18939. tPrev = 2 * t0 - t1;
  18940. break;
  18941. case WrapAroundEnding:
  18942. // use the other end of the curve
  18943. iPrev = pp.length - 2;
  18944. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18945. break;
  18946. default: // ZeroCurvatureEnding
  18947. // f''(t0) = 0 a.k.a. Natural Spline
  18948. iPrev = i1;
  18949. tPrev = t1;
  18950. }
  18951. }
  18952. if ( tNext === undefined ) {
  18953. switch ( this.getSettings_().endingEnd ) {
  18954. case ZeroSlopeEnding:
  18955. // f'(tN) = 0
  18956. iNext = i1;
  18957. tNext = 2 * t1 - t0;
  18958. break;
  18959. case WrapAroundEnding:
  18960. // use the other end of the curve
  18961. iNext = 1;
  18962. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18963. break;
  18964. default: // ZeroCurvatureEnding
  18965. // f''(tN) = 0, a.k.a. Natural Spline
  18966. iNext = i1 - 1;
  18967. tNext = t0;
  18968. }
  18969. }
  18970. var halfDt = ( t1 - t0 ) * 0.5,
  18971. stride = this.valueSize;
  18972. this._weightPrev = halfDt / ( t0 - tPrev );
  18973. this._weightNext = halfDt / ( tNext - t1 );
  18974. this._offsetPrev = iPrev * stride;
  18975. this._offsetNext = iNext * stride;
  18976. },
  18977. interpolate_: function( i1, t0, t, t1 ) {
  18978. var result = this.resultBuffer,
  18979. values = this.sampleValues,
  18980. stride = this.valueSize,
  18981. o1 = i1 * stride, o0 = o1 - stride,
  18982. oP = this._offsetPrev, oN = this._offsetNext,
  18983. wP = this._weightPrev, wN = this._weightNext,
  18984. p = ( t - t0 ) / ( t1 - t0 ),
  18985. pp = p * p,
  18986. ppp = pp * p;
  18987. // evaluate polynomials
  18988. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18989. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18990. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18991. var sN = wN * ppp - wN * pp;
  18992. // combine data linearly
  18993. for ( var i = 0; i !== stride; ++ i ) {
  18994. result[ i ] =
  18995. sP * values[ oP + i ] +
  18996. s0 * values[ o0 + i ] +
  18997. s1 * values[ o1 + i ] +
  18998. sN * values[ oN + i ];
  18999. }
  19000. return result;
  19001. }
  19002. } );
  19003. /**
  19004. * @author tschw
  19005. */
  19006. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19007. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19008. }
  19009. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19010. constructor: LinearInterpolant,
  19011. interpolate_: function( i1, t0, t, t1 ) {
  19012. var result = this.resultBuffer,
  19013. values = this.sampleValues,
  19014. stride = this.valueSize,
  19015. offset1 = i1 * stride,
  19016. offset0 = offset1 - stride,
  19017. weight1 = ( t - t0 ) / ( t1 - t0 ),
  19018. weight0 = 1 - weight1;
  19019. for ( var i = 0; i !== stride; ++ i ) {
  19020. result[ i ] =
  19021. values[ offset0 + i ] * weight0 +
  19022. values[ offset1 + i ] * weight1;
  19023. }
  19024. return result;
  19025. }
  19026. } );
  19027. /**
  19028. *
  19029. * Interpolant that evaluates to the sample value at the position preceeding
  19030. * the parameter.
  19031. *
  19032. * @author tschw
  19033. */
  19034. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19035. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19036. }
  19037. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19038. constructor: DiscreteInterpolant,
  19039. interpolate_: function( i1, t0, t, t1 ) {
  19040. return this.copySampleValue_( i1 - 1 );
  19041. }
  19042. } );
  19043. var KeyframeTrackPrototype;
  19044. KeyframeTrackPrototype = {
  19045. TimeBufferType: Float32Array,
  19046. ValueBufferType: Float32Array,
  19047. DefaultInterpolation: InterpolateLinear,
  19048. InterpolantFactoryMethodDiscrete: function ( result ) {
  19049. return new DiscreteInterpolant(
  19050. this.times, this.values, this.getValueSize(), result );
  19051. },
  19052. InterpolantFactoryMethodLinear: function ( result ) {
  19053. return new LinearInterpolant(
  19054. this.times, this.values, this.getValueSize(), result );
  19055. },
  19056. InterpolantFactoryMethodSmooth: function ( result ) {
  19057. return new CubicInterpolant(
  19058. this.times, this.values, this.getValueSize(), result );
  19059. },
  19060. setInterpolation: function ( interpolation ) {
  19061. var factoryMethod;
  19062. switch ( interpolation ) {
  19063. case InterpolateDiscrete:
  19064. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19065. break;
  19066. case InterpolateLinear:
  19067. factoryMethod = this.InterpolantFactoryMethodLinear;
  19068. break;
  19069. case InterpolateSmooth:
  19070. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19071. break;
  19072. }
  19073. if ( factoryMethod === undefined ) {
  19074. var message = "unsupported interpolation for " +
  19075. this.ValueTypeName + " keyframe track named " + this.name;
  19076. if ( this.createInterpolant === undefined ) {
  19077. // fall back to default, unless the default itself is messed up
  19078. if ( interpolation !== this.DefaultInterpolation ) {
  19079. this.setInterpolation( this.DefaultInterpolation );
  19080. } else {
  19081. throw new Error( message ); // fatal, in this case
  19082. }
  19083. }
  19084. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  19085. return;
  19086. }
  19087. this.createInterpolant = factoryMethod;
  19088. },
  19089. getInterpolation: function () {
  19090. switch ( this.createInterpolant ) {
  19091. case this.InterpolantFactoryMethodDiscrete:
  19092. return InterpolateDiscrete;
  19093. case this.InterpolantFactoryMethodLinear:
  19094. return InterpolateLinear;
  19095. case this.InterpolantFactoryMethodSmooth:
  19096. return InterpolateSmooth;
  19097. }
  19098. },
  19099. getValueSize: function () {
  19100. return this.values.length / this.times.length;
  19101. },
  19102. // move all keyframes either forwards or backwards in time
  19103. shift: function ( timeOffset ) {
  19104. if ( timeOffset !== 0.0 ) {
  19105. var times = this.times;
  19106. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19107. times[ i ] += timeOffset;
  19108. }
  19109. }
  19110. return this;
  19111. },
  19112. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19113. scale: function ( timeScale ) {
  19114. if ( timeScale !== 1.0 ) {
  19115. var times = this.times;
  19116. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19117. times[ i ] *= timeScale;
  19118. }
  19119. }
  19120. return this;
  19121. },
  19122. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19123. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19124. trim: function ( startTime, endTime ) {
  19125. var times = this.times,
  19126. nKeys = times.length,
  19127. from = 0,
  19128. to = nKeys - 1;
  19129. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  19130. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  19131. ++ to; // inclusive -> exclusive bound
  19132. if ( from !== 0 || to !== nKeys ) {
  19133. // empty tracks are forbidden, so keep at least one keyframe
  19134. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  19135. var stride = this.getValueSize();
  19136. this.times = AnimationUtils.arraySlice( times, from, to );
  19137. this.values = AnimationUtils.
  19138. arraySlice( this.values, from * stride, to * stride );
  19139. }
  19140. return this;
  19141. },
  19142. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19143. validate: function () {
  19144. var valid = true;
  19145. var valueSize = this.getValueSize();
  19146. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19147. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  19148. valid = false;
  19149. }
  19150. var times = this.times,
  19151. values = this.values,
  19152. nKeys = times.length;
  19153. if ( nKeys === 0 ) {
  19154. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  19155. valid = false;
  19156. }
  19157. var prevTime = null;
  19158. for ( var i = 0; i !== nKeys; i ++ ) {
  19159. var currTime = times[ i ];
  19160. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19161. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  19162. valid = false;
  19163. break;
  19164. }
  19165. if ( prevTime !== null && prevTime > currTime ) {
  19166. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  19167. valid = false;
  19168. break;
  19169. }
  19170. prevTime = currTime;
  19171. }
  19172. if ( values !== undefined ) {
  19173. if ( AnimationUtils.isTypedArray( values ) ) {
  19174. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  19175. var value = values[ i ];
  19176. if ( isNaN( value ) ) {
  19177. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  19178. valid = false;
  19179. break;
  19180. }
  19181. }
  19182. }
  19183. }
  19184. return valid;
  19185. },
  19186. // removes equivalent sequential keys as common in morph target sequences
  19187. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19188. optimize: function () {
  19189. var times = this.times,
  19190. values = this.values,
  19191. stride = this.getValueSize(),
  19192. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19193. writeIndex = 1,
  19194. lastIndex = times.length - 1;
  19195. for ( var i = 1; i < lastIndex; ++ i ) {
  19196. var keep = false;
  19197. var time = times[ i ];
  19198. var timeNext = times[ i + 1 ];
  19199. // remove adjacent keyframes scheduled at the same time
  19200. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  19201. if ( ! smoothInterpolation ) {
  19202. // remove unnecessary keyframes same as their neighbors
  19203. var offset = i * stride,
  19204. offsetP = offset - stride,
  19205. offsetN = offset + stride;
  19206. for ( var j = 0; j !== stride; ++ j ) {
  19207. var value = values[ offset + j ];
  19208. if ( value !== values[ offsetP + j ] ||
  19209. value !== values[ offsetN + j ] ) {
  19210. keep = true;
  19211. break;
  19212. }
  19213. }
  19214. } else keep = true;
  19215. }
  19216. // in-place compaction
  19217. if ( keep ) {
  19218. if ( i !== writeIndex ) {
  19219. times[ writeIndex ] = times[ i ];
  19220. var readOffset = i * stride,
  19221. writeOffset = writeIndex * stride;
  19222. for ( var j = 0; j !== stride; ++ j )
  19223. values[ writeOffset + j ] = values[ readOffset + j ];
  19224. }
  19225. ++ writeIndex;
  19226. }
  19227. }
  19228. // flush last keyframe (compaction looks ahead)
  19229. if ( lastIndex > 0 ) {
  19230. times[ writeIndex ] = times[ lastIndex ];
  19231. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  19232. values[ writeOffset + j ] = values[ readOffset + j ];
  19233. ++ writeIndex;
  19234. }
  19235. if ( writeIndex !== times.length ) {
  19236. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19237. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19238. }
  19239. return this;
  19240. }
  19241. };
  19242. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  19243. if ( name === undefined ) throw new Error( "track name is undefined" );
  19244. if ( times === undefined || times.length === 0 ) {
  19245. throw new Error( "no keyframes in track named " + name );
  19246. }
  19247. this.name = name;
  19248. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19249. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19250. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19251. this.validate();
  19252. this.optimize();
  19253. }
  19254. /**
  19255. *
  19256. * A Track of vectored keyframe values.
  19257. *
  19258. *
  19259. * @author Ben Houston / http://clara.io/
  19260. * @author David Sarno / http://lighthaus.us/
  19261. * @author tschw
  19262. */
  19263. function VectorKeyframeTrack( name, times, values, interpolation ) {
  19264. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19265. }
  19266. VectorKeyframeTrack.prototype =
  19267. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19268. constructor: VectorKeyframeTrack,
  19269. ValueTypeName: 'vector'
  19270. // ValueBufferType is inherited
  19271. // DefaultInterpolation is inherited
  19272. } );
  19273. /**
  19274. * Spherical linear unit quaternion interpolant.
  19275. *
  19276. * @author tschw
  19277. */
  19278. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19279. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19280. }
  19281. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19282. constructor: QuaternionLinearInterpolant,
  19283. interpolate_: function( i1, t0, t, t1 ) {
  19284. var result = this.resultBuffer,
  19285. values = this.sampleValues,
  19286. stride = this.valueSize,
  19287. offset = i1 * stride,
  19288. alpha = ( t - t0 ) / ( t1 - t0 );
  19289. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  19290. Quaternion.slerpFlat( result, 0,
  19291. values, offset - stride, values, offset, alpha );
  19292. }
  19293. return result;
  19294. }
  19295. } );
  19296. /**
  19297. *
  19298. * A Track of quaternion keyframe values.
  19299. *
  19300. * @author Ben Houston / http://clara.io/
  19301. * @author David Sarno / http://lighthaus.us/
  19302. * @author tschw
  19303. */
  19304. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  19305. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19306. }
  19307. QuaternionKeyframeTrack.prototype =
  19308. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19309. constructor: QuaternionKeyframeTrack,
  19310. ValueTypeName: 'quaternion',
  19311. // ValueBufferType is inherited
  19312. DefaultInterpolation: InterpolateLinear,
  19313. InterpolantFactoryMethodLinear: function( result ) {
  19314. return new QuaternionLinearInterpolant(
  19315. this.times, this.values, this.getValueSize(), result );
  19316. },
  19317. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  19318. } );
  19319. /**
  19320. *
  19321. * A Track of numeric keyframe values.
  19322. *
  19323. * @author Ben Houston / http://clara.io/
  19324. * @author David Sarno / http://lighthaus.us/
  19325. * @author tschw
  19326. */
  19327. function NumberKeyframeTrack( name, times, values, interpolation ) {
  19328. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19329. }
  19330. NumberKeyframeTrack.prototype =
  19331. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19332. constructor: NumberKeyframeTrack,
  19333. ValueTypeName: 'number'
  19334. // ValueBufferType is inherited
  19335. // DefaultInterpolation is inherited
  19336. } );
  19337. /**
  19338. *
  19339. * A Track that interpolates Strings
  19340. *
  19341. *
  19342. * @author Ben Houston / http://clara.io/
  19343. * @author David Sarno / http://lighthaus.us/
  19344. * @author tschw
  19345. */
  19346. function StringKeyframeTrack( name, times, values, interpolation ) {
  19347. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19348. }
  19349. StringKeyframeTrack.prototype =
  19350. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19351. constructor: StringKeyframeTrack,
  19352. ValueTypeName: 'string',
  19353. ValueBufferType: Array,
  19354. DefaultInterpolation: InterpolateDiscrete,
  19355. InterpolantFactoryMethodLinear: undefined,
  19356. InterpolantFactoryMethodSmooth: undefined
  19357. } );
  19358. /**
  19359. *
  19360. * A Track of Boolean keyframe values.
  19361. *
  19362. *
  19363. * @author Ben Houston / http://clara.io/
  19364. * @author David Sarno / http://lighthaus.us/
  19365. * @author tschw
  19366. */
  19367. function BooleanKeyframeTrack( name, times, values ) {
  19368. KeyframeTrackConstructor.call( this, name, times, values );
  19369. }
  19370. BooleanKeyframeTrack.prototype =
  19371. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19372. constructor: BooleanKeyframeTrack,
  19373. ValueTypeName: 'bool',
  19374. ValueBufferType: Array,
  19375. DefaultInterpolation: InterpolateDiscrete,
  19376. InterpolantFactoryMethodLinear: undefined,
  19377. InterpolantFactoryMethodSmooth: undefined
  19378. // Note: Actually this track could have a optimized / compressed
  19379. // representation of a single value and a custom interpolant that
  19380. // computes "firstValue ^ isOdd( index )".
  19381. } );
  19382. /**
  19383. *
  19384. * A Track of keyframe values that represent color.
  19385. *
  19386. *
  19387. * @author Ben Houston / http://clara.io/
  19388. * @author David Sarno / http://lighthaus.us/
  19389. * @author tschw
  19390. */
  19391. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19392. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19393. }
  19394. ColorKeyframeTrack.prototype =
  19395. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19396. constructor: ColorKeyframeTrack,
  19397. ValueTypeName: 'color'
  19398. // ValueBufferType is inherited
  19399. // DefaultInterpolation is inherited
  19400. // Note: Very basic implementation and nothing special yet.
  19401. // However, this is the place for color space parameterization.
  19402. } );
  19403. /**
  19404. *
  19405. * A timed sequence of keyframes for a specific property.
  19406. *
  19407. *
  19408. * @author Ben Houston / http://clara.io/
  19409. * @author David Sarno / http://lighthaus.us/
  19410. * @author tschw
  19411. */
  19412. function KeyframeTrack( name, times, values, interpolation ) {
  19413. KeyframeTrackConstructor.apply( this, arguments );
  19414. }
  19415. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19416. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19417. // Static methods:
  19418. Object.assign( KeyframeTrack, {
  19419. // Serialization (in static context, because of constructor invocation
  19420. // and automatic invocation of .toJSON):
  19421. parse: function( json ) {
  19422. if( json.type === undefined ) {
  19423. throw new Error( "track type undefined, can not parse" );
  19424. }
  19425. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19426. if ( json.times === undefined ) {
  19427. var times = [], values = [];
  19428. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19429. json.times = times;
  19430. json.values = values;
  19431. }
  19432. // derived classes can define a static parse method
  19433. if ( trackType.parse !== undefined ) {
  19434. return trackType.parse( json );
  19435. } else {
  19436. // by default, we assume a constructor compatible with the base
  19437. return new trackType(
  19438. json.name, json.times, json.values, json.interpolation );
  19439. }
  19440. },
  19441. toJSON: function( track ) {
  19442. var trackType = track.constructor;
  19443. var json;
  19444. // derived classes can define a static toJSON method
  19445. if ( trackType.toJSON !== undefined ) {
  19446. json = trackType.toJSON( track );
  19447. } else {
  19448. // by default, we assume the data can be serialized as-is
  19449. json = {
  19450. 'name': track.name,
  19451. 'times': AnimationUtils.convertArray( track.times, Array ),
  19452. 'values': AnimationUtils.convertArray( track.values, Array )
  19453. };
  19454. var interpolation = track.getInterpolation();
  19455. if ( interpolation !== track.DefaultInterpolation ) {
  19456. json.interpolation = interpolation;
  19457. }
  19458. }
  19459. json.type = track.ValueTypeName; // mandatory
  19460. return json;
  19461. },
  19462. _getTrackTypeForValueTypeName: function( typeName ) {
  19463. switch( typeName.toLowerCase() ) {
  19464. case "scalar":
  19465. case "double":
  19466. case "float":
  19467. case "number":
  19468. case "integer":
  19469. return NumberKeyframeTrack;
  19470. case "vector":
  19471. case "vector2":
  19472. case "vector3":
  19473. case "vector4":
  19474. return VectorKeyframeTrack;
  19475. case "color":
  19476. return ColorKeyframeTrack;
  19477. case "quaternion":
  19478. return QuaternionKeyframeTrack;
  19479. case "bool":
  19480. case "boolean":
  19481. return BooleanKeyframeTrack;
  19482. case "string":
  19483. return StringKeyframeTrack;
  19484. }
  19485. throw new Error( "Unsupported typeName: " + typeName );
  19486. }
  19487. } );
  19488. /**
  19489. *
  19490. * Reusable set of Tracks that represent an animation.
  19491. *
  19492. * @author Ben Houston / http://clara.io/
  19493. * @author David Sarno / http://lighthaus.us/
  19494. */
  19495. function AnimationClip( name, duration, tracks ) {
  19496. this.name = name;
  19497. this.tracks = tracks;
  19498. this.duration = ( duration !== undefined ) ? duration : - 1;
  19499. this.uuid = _Math.generateUUID();
  19500. // this means it should figure out its duration by scanning the tracks
  19501. if ( this.duration < 0 ) {
  19502. this.resetDuration();
  19503. }
  19504. this.optimize();
  19505. }
  19506. Object.assign( AnimationClip, {
  19507. parse: function ( json ) {
  19508. var tracks = [],
  19509. jsonTracks = json.tracks,
  19510. frameTime = 1.0 / ( json.fps || 1.0 );
  19511. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19512. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19513. }
  19514. return new AnimationClip( json.name, json.duration, tracks );
  19515. },
  19516. toJSON: function ( clip ) {
  19517. var tracks = [],
  19518. clipTracks = clip.tracks;
  19519. var json = {
  19520. 'name': clip.name,
  19521. 'duration': clip.duration,
  19522. 'tracks': tracks
  19523. };
  19524. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19525. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19526. }
  19527. return json;
  19528. },
  19529. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19530. var numMorphTargets = morphTargetSequence.length;
  19531. var tracks = [];
  19532. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19533. var times = [];
  19534. var values = [];
  19535. times.push(
  19536. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19537. i,
  19538. ( i + 1 ) % numMorphTargets );
  19539. values.push( 0, 1, 0 );
  19540. var order = AnimationUtils.getKeyframeOrder( times );
  19541. times = AnimationUtils.sortedArray( times, 1, order );
  19542. values = AnimationUtils.sortedArray( values, 1, order );
  19543. // if there is a key at the first frame, duplicate it as the
  19544. // last frame as well for perfect loop.
  19545. if ( ! noLoop && times[ 0 ] === 0 ) {
  19546. times.push( numMorphTargets );
  19547. values.push( values[ 0 ] );
  19548. }
  19549. tracks.push(
  19550. new NumberKeyframeTrack(
  19551. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19552. times, values
  19553. ).scale( 1.0 / fps ) );
  19554. }
  19555. return new AnimationClip( name, - 1, tracks );
  19556. },
  19557. findByName: function ( objectOrClipArray, name ) {
  19558. var clipArray = objectOrClipArray;
  19559. if ( ! Array.isArray( objectOrClipArray ) ) {
  19560. var o = objectOrClipArray;
  19561. clipArray = o.geometry && o.geometry.animations || o.animations;
  19562. }
  19563. for ( var i = 0; i < clipArray.length; i ++ ) {
  19564. if ( clipArray[ i ].name === name ) {
  19565. return clipArray[ i ];
  19566. }
  19567. }
  19568. return null;
  19569. },
  19570. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19571. var animationToMorphTargets = {};
  19572. // tested with https://regex101.com/ on trick sequences
  19573. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19574. var pattern = /^([\w-]*?)([\d]+)$/;
  19575. // sort morph target names into animation groups based
  19576. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19577. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19578. var morphTarget = morphTargets[ i ];
  19579. var parts = morphTarget.name.match( pattern );
  19580. if ( parts && parts.length > 1 ) {
  19581. var name = parts[ 1 ];
  19582. var animationMorphTargets = animationToMorphTargets[ name ];
  19583. if ( ! animationMorphTargets ) {
  19584. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19585. }
  19586. animationMorphTargets.push( morphTarget );
  19587. }
  19588. }
  19589. var clips = [];
  19590. for ( var name in animationToMorphTargets ) {
  19591. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19592. }
  19593. return clips;
  19594. },
  19595. // parse the animation.hierarchy format
  19596. parseAnimation: function ( animation, bones ) {
  19597. if ( ! animation ) {
  19598. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  19599. return null;
  19600. }
  19601. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19602. // only return track if there are actually keys.
  19603. if ( animationKeys.length !== 0 ) {
  19604. var times = [];
  19605. var values = [];
  19606. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19607. // empty keys are filtered out, so check again
  19608. if ( times.length !== 0 ) {
  19609. destTracks.push( new trackType( trackName, times, values ) );
  19610. }
  19611. }
  19612. };
  19613. var tracks = [];
  19614. var clipName = animation.name || 'default';
  19615. // automatic length determination in AnimationClip.
  19616. var duration = animation.length || - 1;
  19617. var fps = animation.fps || 30;
  19618. var hierarchyTracks = animation.hierarchy || [];
  19619. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19620. var animationKeys = hierarchyTracks[ h ].keys;
  19621. // skip empty tracks
  19622. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19623. // process morph targets
  19624. if ( animationKeys[ 0 ].morphTargets ) {
  19625. // figure out all morph targets used in this track
  19626. var morphTargetNames = {};
  19627. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19628. if ( animationKeys[ k ].morphTargets ) {
  19629. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19630. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19631. }
  19632. }
  19633. }
  19634. // create a track for each morph target with all zero
  19635. // morphTargetInfluences except for the keys in which
  19636. // the morphTarget is named.
  19637. for ( var morphTargetName in morphTargetNames ) {
  19638. var times = [];
  19639. var values = [];
  19640. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19641. var animationKey = animationKeys[ k ];
  19642. times.push( animationKey.time );
  19643. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19644. }
  19645. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19646. }
  19647. duration = morphTargetNames.length * ( fps || 1.0 );
  19648. } else {
  19649. // ...assume skeletal animation
  19650. var boneName = '.bones[' + bones[ h ].name + ']';
  19651. addNonemptyTrack(
  19652. VectorKeyframeTrack, boneName + '.position',
  19653. animationKeys, 'pos', tracks );
  19654. addNonemptyTrack(
  19655. QuaternionKeyframeTrack, boneName + '.quaternion',
  19656. animationKeys, 'rot', tracks );
  19657. addNonemptyTrack(
  19658. VectorKeyframeTrack, boneName + '.scale',
  19659. animationKeys, 'scl', tracks );
  19660. }
  19661. }
  19662. if ( tracks.length === 0 ) {
  19663. return null;
  19664. }
  19665. var clip = new AnimationClip( clipName, duration, tracks );
  19666. return clip;
  19667. }
  19668. } );
  19669. Object.assign( AnimationClip.prototype, {
  19670. resetDuration: function () {
  19671. var tracks = this.tracks, duration = 0;
  19672. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19673. var track = this.tracks[ i ];
  19674. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19675. }
  19676. this.duration = duration;
  19677. },
  19678. trim: function () {
  19679. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19680. this.tracks[ i ].trim( 0, this.duration );
  19681. }
  19682. return this;
  19683. },
  19684. optimize: function () {
  19685. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19686. this.tracks[ i ].optimize();
  19687. }
  19688. return this;
  19689. }
  19690. } );
  19691. /**
  19692. * @author mrdoob / http://mrdoob.com/
  19693. */
  19694. function MaterialLoader( manager ) {
  19695. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19696. this.textures = {};
  19697. }
  19698. Object.assign( MaterialLoader.prototype, {
  19699. load: function ( url, onLoad, onProgress, onError ) {
  19700. var scope = this;
  19701. var loader = new FileLoader( scope.manager );
  19702. loader.load( url, function ( text ) {
  19703. onLoad( scope.parse( JSON.parse( text ) ) );
  19704. }, onProgress, onError );
  19705. },
  19706. setTextures: function ( value ) {
  19707. this.textures = value;
  19708. },
  19709. parse: function ( json ) {
  19710. var textures = this.textures;
  19711. function getTexture( name ) {
  19712. if ( textures[ name ] === undefined ) {
  19713. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19714. }
  19715. return textures[ name ];
  19716. }
  19717. var material = new Materials[ json.type ]();
  19718. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19719. if ( json.name !== undefined ) material.name = json.name;
  19720. if ( json.color !== undefined ) material.color.setHex( json.color );
  19721. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19722. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19723. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19724. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19725. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19726. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19727. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19728. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19729. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19730. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19731. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19732. if ( json.fog !== undefined ) material.fog = json.fog;
  19733. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  19734. if ( json.blending !== undefined ) material.blending = json.blending;
  19735. if ( json.side !== undefined ) material.side = json.side;
  19736. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19737. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19738. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19739. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19740. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19741. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19742. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19743. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19744. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19745. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19746. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19747. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19748. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  19749. if ( json.visible !== undefined ) material.visible = json.visible;
  19750. if ( json.userData !== undefined ) material.userData = json.userData;
  19751. // Deprecated
  19752. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  19753. // for PointsMaterial
  19754. if ( json.size !== undefined ) material.size = json.size;
  19755. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19756. // maps
  19757. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19758. if ( json.alphaMap !== undefined ) {
  19759. material.alphaMap = getTexture( json.alphaMap );
  19760. material.transparent = true;
  19761. }
  19762. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19763. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19764. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19765. if ( json.normalScale !== undefined ) {
  19766. var normalScale = json.normalScale;
  19767. if ( Array.isArray( normalScale ) === false ) {
  19768. // Blender exporter used to export a scalar. See #7459
  19769. normalScale = [ normalScale, normalScale ];
  19770. }
  19771. material.normalScale = new Vector2().fromArray( normalScale );
  19772. }
  19773. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19774. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19775. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19776. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19777. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19778. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19779. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19780. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19781. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19782. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19783. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19784. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19785. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19786. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19787. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19788. return material;
  19789. }
  19790. } );
  19791. /**
  19792. * @author mrdoob / http://mrdoob.com/
  19793. */
  19794. function BufferGeometryLoader( manager ) {
  19795. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19796. }
  19797. Object.assign( BufferGeometryLoader.prototype, {
  19798. load: function ( url, onLoad, onProgress, onError ) {
  19799. var scope = this;
  19800. var loader = new FileLoader( scope.manager );
  19801. loader.load( url, function ( text ) {
  19802. onLoad( scope.parse( JSON.parse( text ) ) );
  19803. }, onProgress, onError );
  19804. },
  19805. parse: function ( json ) {
  19806. var geometry = new BufferGeometry();
  19807. var index = json.data.index;
  19808. if ( index !== undefined ) {
  19809. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19810. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19811. }
  19812. var attributes = json.data.attributes;
  19813. for ( var key in attributes ) {
  19814. var attribute = attributes[ key ];
  19815. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19816. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19817. }
  19818. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19819. if ( groups !== undefined ) {
  19820. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19821. var group = groups[ i ];
  19822. geometry.addGroup( group.start, group.count, group.materialIndex );
  19823. }
  19824. }
  19825. var boundingSphere = json.data.boundingSphere;
  19826. if ( boundingSphere !== undefined ) {
  19827. var center = new Vector3();
  19828. if ( boundingSphere.center !== undefined ) {
  19829. center.fromArray( boundingSphere.center );
  19830. }
  19831. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19832. }
  19833. return geometry;
  19834. }
  19835. } );
  19836. var TYPED_ARRAYS = {
  19837. Int8Array: Int8Array,
  19838. Uint8Array: Uint8Array,
  19839. // Workaround for IE11 pre KB2929437. See #11440
  19840. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  19841. Int16Array: Int16Array,
  19842. Uint16Array: Uint16Array,
  19843. Int32Array: Int32Array,
  19844. Uint32Array: Uint32Array,
  19845. Float32Array: Float32Array,
  19846. Float64Array: Float64Array
  19847. };
  19848. /**
  19849. * @author alteredq / http://alteredqualia.com/
  19850. */
  19851. function Loader() {
  19852. this.onLoadStart = function () {};
  19853. this.onLoadProgress = function () {};
  19854. this.onLoadComplete = function () {};
  19855. }
  19856. Loader.Handlers = {
  19857. handlers: [],
  19858. add: function ( regex, loader ) {
  19859. this.handlers.push( regex, loader );
  19860. },
  19861. get: function ( file ) {
  19862. var handlers = this.handlers;
  19863. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19864. var regex = handlers[ i ];
  19865. var loader = handlers[ i + 1 ];
  19866. if ( regex.test( file ) ) {
  19867. return loader;
  19868. }
  19869. }
  19870. return null;
  19871. }
  19872. };
  19873. Object.assign( Loader.prototype, {
  19874. crossOrigin: undefined,
  19875. extractUrlBase: function ( url ) {
  19876. var parts = url.split( '/' );
  19877. if ( parts.length === 1 ) return './';
  19878. parts.pop();
  19879. return parts.join( '/' ) + '/';
  19880. },
  19881. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19882. var array = [];
  19883. for ( var i = 0; i < materials.length; ++ i ) {
  19884. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19885. }
  19886. return array;
  19887. },
  19888. createMaterial: ( function () {
  19889. var BlendingMode = {
  19890. NoBlending: NoBlending,
  19891. NormalBlending: NormalBlending,
  19892. AdditiveBlending: AdditiveBlending,
  19893. SubtractiveBlending: SubtractiveBlending,
  19894. MultiplyBlending: MultiplyBlending,
  19895. CustomBlending: CustomBlending
  19896. };
  19897. var color = new Color();
  19898. var textureLoader = new TextureLoader();
  19899. var materialLoader = new MaterialLoader();
  19900. return function createMaterial( m, texturePath, crossOrigin ) {
  19901. // convert from old material format
  19902. var textures = {};
  19903. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19904. var fullPath = texturePath + path;
  19905. var loader = Loader.Handlers.get( fullPath );
  19906. var texture;
  19907. if ( loader !== null ) {
  19908. texture = loader.load( fullPath );
  19909. } else {
  19910. textureLoader.setCrossOrigin( crossOrigin );
  19911. texture = textureLoader.load( fullPath );
  19912. }
  19913. if ( repeat !== undefined ) {
  19914. texture.repeat.fromArray( repeat );
  19915. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19916. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19917. }
  19918. if ( offset !== undefined ) {
  19919. texture.offset.fromArray( offset );
  19920. }
  19921. if ( wrap !== undefined ) {
  19922. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19923. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19924. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19925. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19926. }
  19927. if ( anisotropy !== undefined ) {
  19928. texture.anisotropy = anisotropy;
  19929. }
  19930. var uuid = _Math.generateUUID();
  19931. textures[ uuid ] = texture;
  19932. return uuid;
  19933. }
  19934. //
  19935. var json = {
  19936. uuid: _Math.generateUUID(),
  19937. type: 'MeshLambertMaterial'
  19938. };
  19939. for ( var name in m ) {
  19940. var value = m[ name ];
  19941. switch ( name ) {
  19942. case 'DbgColor':
  19943. case 'DbgIndex':
  19944. case 'opticalDensity':
  19945. case 'illumination':
  19946. break;
  19947. case 'DbgName':
  19948. json.name = value;
  19949. break;
  19950. case 'blending':
  19951. json.blending = BlendingMode[ value ];
  19952. break;
  19953. case 'colorAmbient':
  19954. case 'mapAmbient':
  19955. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19956. break;
  19957. case 'colorDiffuse':
  19958. json.color = color.fromArray( value ).getHex();
  19959. break;
  19960. case 'colorSpecular':
  19961. json.specular = color.fromArray( value ).getHex();
  19962. break;
  19963. case 'colorEmissive':
  19964. json.emissive = color.fromArray( value ).getHex();
  19965. break;
  19966. case 'specularCoef':
  19967. json.shininess = value;
  19968. break;
  19969. case 'shading':
  19970. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19971. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19972. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19973. break;
  19974. case 'mapDiffuse':
  19975. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19976. break;
  19977. case 'mapDiffuseRepeat':
  19978. case 'mapDiffuseOffset':
  19979. case 'mapDiffuseWrap':
  19980. case 'mapDiffuseAnisotropy':
  19981. break;
  19982. case 'mapEmissive':
  19983. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19984. break;
  19985. case 'mapEmissiveRepeat':
  19986. case 'mapEmissiveOffset':
  19987. case 'mapEmissiveWrap':
  19988. case 'mapEmissiveAnisotropy':
  19989. break;
  19990. case 'mapLight':
  19991. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19992. break;
  19993. case 'mapLightRepeat':
  19994. case 'mapLightOffset':
  19995. case 'mapLightWrap':
  19996. case 'mapLightAnisotropy':
  19997. break;
  19998. case 'mapAO':
  19999. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  20000. break;
  20001. case 'mapAORepeat':
  20002. case 'mapAOOffset':
  20003. case 'mapAOWrap':
  20004. case 'mapAOAnisotropy':
  20005. break;
  20006. case 'mapBump':
  20007. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  20008. break;
  20009. case 'mapBumpScale':
  20010. json.bumpScale = value;
  20011. break;
  20012. case 'mapBumpRepeat':
  20013. case 'mapBumpOffset':
  20014. case 'mapBumpWrap':
  20015. case 'mapBumpAnisotropy':
  20016. break;
  20017. case 'mapNormal':
  20018. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  20019. break;
  20020. case 'mapNormalFactor':
  20021. json.normalScale = [ value, value ];
  20022. break;
  20023. case 'mapNormalRepeat':
  20024. case 'mapNormalOffset':
  20025. case 'mapNormalWrap':
  20026. case 'mapNormalAnisotropy':
  20027. break;
  20028. case 'mapSpecular':
  20029. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  20030. break;
  20031. case 'mapSpecularRepeat':
  20032. case 'mapSpecularOffset':
  20033. case 'mapSpecularWrap':
  20034. case 'mapSpecularAnisotropy':
  20035. break;
  20036. case 'mapMetalness':
  20037. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  20038. break;
  20039. case 'mapMetalnessRepeat':
  20040. case 'mapMetalnessOffset':
  20041. case 'mapMetalnessWrap':
  20042. case 'mapMetalnessAnisotropy':
  20043. break;
  20044. case 'mapRoughness':
  20045. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  20046. break;
  20047. case 'mapRoughnessRepeat':
  20048. case 'mapRoughnessOffset':
  20049. case 'mapRoughnessWrap':
  20050. case 'mapRoughnessAnisotropy':
  20051. break;
  20052. case 'mapAlpha':
  20053. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  20054. break;
  20055. case 'mapAlphaRepeat':
  20056. case 'mapAlphaOffset':
  20057. case 'mapAlphaWrap':
  20058. case 'mapAlphaAnisotropy':
  20059. break;
  20060. case 'flipSided':
  20061. json.side = BackSide;
  20062. break;
  20063. case 'doubleSided':
  20064. json.side = DoubleSide;
  20065. break;
  20066. case 'transparency':
  20067. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  20068. json.opacity = value;
  20069. break;
  20070. case 'depthTest':
  20071. case 'depthWrite':
  20072. case 'colorWrite':
  20073. case 'opacity':
  20074. case 'reflectivity':
  20075. case 'transparent':
  20076. case 'visible':
  20077. case 'wireframe':
  20078. json[ name ] = value;
  20079. break;
  20080. case 'vertexColors':
  20081. if ( value === true ) json.vertexColors = VertexColors;
  20082. if ( value === 'face' ) json.vertexColors = FaceColors;
  20083. break;
  20084. default:
  20085. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  20086. break;
  20087. }
  20088. }
  20089. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  20090. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  20091. if ( json.opacity < 1 ) json.transparent = true;
  20092. materialLoader.setTextures( textures );
  20093. return materialLoader.parse( json );
  20094. };
  20095. } )()
  20096. } );
  20097. /**
  20098. * @author mrdoob / http://mrdoob.com/
  20099. * @author alteredq / http://alteredqualia.com/
  20100. */
  20101. function JSONLoader( manager ) {
  20102. if ( typeof manager === 'boolean' ) {
  20103. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  20104. manager = undefined;
  20105. }
  20106. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20107. this.withCredentials = false;
  20108. }
  20109. Object.assign( JSONLoader.prototype, {
  20110. load: function ( url, onLoad, onProgress, onError ) {
  20111. var scope = this;
  20112. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  20113. var loader = new FileLoader( this.manager );
  20114. loader.setWithCredentials( this.withCredentials );
  20115. loader.load( url, function ( text ) {
  20116. var json = JSON.parse( text );
  20117. var metadata = json.metadata;
  20118. if ( metadata !== undefined ) {
  20119. var type = metadata.type;
  20120. if ( type !== undefined ) {
  20121. if ( type.toLowerCase() === 'object' ) {
  20122. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  20123. return;
  20124. }
  20125. if ( type.toLowerCase() === 'scene' ) {
  20126. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  20127. return;
  20128. }
  20129. }
  20130. }
  20131. var object = scope.parse( json, texturePath );
  20132. onLoad( object.geometry, object.materials );
  20133. }, onProgress, onError );
  20134. },
  20135. setTexturePath: function ( value ) {
  20136. this.texturePath = value;
  20137. },
  20138. parse: ( function () {
  20139. function parseModel( json, geometry ) {
  20140. function isBitSet( value, position ) {
  20141. return value & ( 1 << position );
  20142. }
  20143. var i, j, fi,
  20144. offset, zLength,
  20145. colorIndex, normalIndex, uvIndex, materialIndex,
  20146. type,
  20147. isQuad,
  20148. hasMaterial,
  20149. hasFaceVertexUv,
  20150. hasFaceNormal, hasFaceVertexNormal,
  20151. hasFaceColor, hasFaceVertexColor,
  20152. vertex, face, faceA, faceB, hex, normal,
  20153. uvLayer, uv, u, v,
  20154. faces = json.faces,
  20155. vertices = json.vertices,
  20156. normals = json.normals,
  20157. colors = json.colors,
  20158. scale = json.scale,
  20159. nUvLayers = 0;
  20160. if ( json.uvs !== undefined ) {
  20161. // disregard empty arrays
  20162. for ( i = 0; i < json.uvs.length; i ++ ) {
  20163. if ( json.uvs[ i ].length ) nUvLayers ++;
  20164. }
  20165. for ( i = 0; i < nUvLayers; i ++ ) {
  20166. geometry.faceVertexUvs[ i ] = [];
  20167. }
  20168. }
  20169. offset = 0;
  20170. zLength = vertices.length;
  20171. while ( offset < zLength ) {
  20172. vertex = new Vector3();
  20173. vertex.x = vertices[ offset ++ ] * scale;
  20174. vertex.y = vertices[ offset ++ ] * scale;
  20175. vertex.z = vertices[ offset ++ ] * scale;
  20176. geometry.vertices.push( vertex );
  20177. }
  20178. offset = 0;
  20179. zLength = faces.length;
  20180. while ( offset < zLength ) {
  20181. type = faces[ offset ++ ];
  20182. isQuad = isBitSet( type, 0 );
  20183. hasMaterial = isBitSet( type, 1 );
  20184. hasFaceVertexUv = isBitSet( type, 3 );
  20185. hasFaceNormal = isBitSet( type, 4 );
  20186. hasFaceVertexNormal = isBitSet( type, 5 );
  20187. hasFaceColor = isBitSet( type, 6 );
  20188. hasFaceVertexColor = isBitSet( type, 7 );
  20189. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  20190. if ( isQuad ) {
  20191. faceA = new Face3();
  20192. faceA.a = faces[ offset ];
  20193. faceA.b = faces[ offset + 1 ];
  20194. faceA.c = faces[ offset + 3 ];
  20195. faceB = new Face3();
  20196. faceB.a = faces[ offset + 1 ];
  20197. faceB.b = faces[ offset + 2 ];
  20198. faceB.c = faces[ offset + 3 ];
  20199. offset += 4;
  20200. if ( hasMaterial ) {
  20201. materialIndex = faces[ offset ++ ];
  20202. faceA.materialIndex = materialIndex;
  20203. faceB.materialIndex = materialIndex;
  20204. }
  20205. // to get face <=> uv index correspondence
  20206. fi = geometry.faces.length;
  20207. if ( hasFaceVertexUv ) {
  20208. for ( i = 0; i < nUvLayers; i ++ ) {
  20209. uvLayer = json.uvs[ i ];
  20210. geometry.faceVertexUvs[ i ][ fi ] = [];
  20211. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  20212. for ( j = 0; j < 4; j ++ ) {
  20213. uvIndex = faces[ offset ++ ];
  20214. u = uvLayer[ uvIndex * 2 ];
  20215. v = uvLayer[ uvIndex * 2 + 1 ];
  20216. uv = new Vector2( u, v );
  20217. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20218. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  20219. }
  20220. }
  20221. }
  20222. if ( hasFaceNormal ) {
  20223. normalIndex = faces[ offset ++ ] * 3;
  20224. faceA.normal.set(
  20225. normals[ normalIndex ++ ],
  20226. normals[ normalIndex ++ ],
  20227. normals[ normalIndex ]
  20228. );
  20229. faceB.normal.copy( faceA.normal );
  20230. }
  20231. if ( hasFaceVertexNormal ) {
  20232. for ( i = 0; i < 4; i ++ ) {
  20233. normalIndex = faces[ offset ++ ] * 3;
  20234. normal = new Vector3(
  20235. normals[ normalIndex ++ ],
  20236. normals[ normalIndex ++ ],
  20237. normals[ normalIndex ]
  20238. );
  20239. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  20240. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  20241. }
  20242. }
  20243. if ( hasFaceColor ) {
  20244. colorIndex = faces[ offset ++ ];
  20245. hex = colors[ colorIndex ];
  20246. faceA.color.setHex( hex );
  20247. faceB.color.setHex( hex );
  20248. }
  20249. if ( hasFaceVertexColor ) {
  20250. for ( i = 0; i < 4; i ++ ) {
  20251. colorIndex = faces[ offset ++ ];
  20252. hex = colors[ colorIndex ];
  20253. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  20254. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  20255. }
  20256. }
  20257. geometry.faces.push( faceA );
  20258. geometry.faces.push( faceB );
  20259. } else {
  20260. face = new Face3();
  20261. face.a = faces[ offset ++ ];
  20262. face.b = faces[ offset ++ ];
  20263. face.c = faces[ offset ++ ];
  20264. if ( hasMaterial ) {
  20265. materialIndex = faces[ offset ++ ];
  20266. face.materialIndex = materialIndex;
  20267. }
  20268. // to get face <=> uv index correspondence
  20269. fi = geometry.faces.length;
  20270. if ( hasFaceVertexUv ) {
  20271. for ( i = 0; i < nUvLayers; i ++ ) {
  20272. uvLayer = json.uvs[ i ];
  20273. geometry.faceVertexUvs[ i ][ fi ] = [];
  20274. for ( j = 0; j < 3; j ++ ) {
  20275. uvIndex = faces[ offset ++ ];
  20276. u = uvLayer[ uvIndex * 2 ];
  20277. v = uvLayer[ uvIndex * 2 + 1 ];
  20278. uv = new Vector2( u, v );
  20279. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20280. }
  20281. }
  20282. }
  20283. if ( hasFaceNormal ) {
  20284. normalIndex = faces[ offset ++ ] * 3;
  20285. face.normal.set(
  20286. normals[ normalIndex ++ ],
  20287. normals[ normalIndex ++ ],
  20288. normals[ normalIndex ]
  20289. );
  20290. }
  20291. if ( hasFaceVertexNormal ) {
  20292. for ( i = 0; i < 3; i ++ ) {
  20293. normalIndex = faces[ offset ++ ] * 3;
  20294. normal = new Vector3(
  20295. normals[ normalIndex ++ ],
  20296. normals[ normalIndex ++ ],
  20297. normals[ normalIndex ]
  20298. );
  20299. face.vertexNormals.push( normal );
  20300. }
  20301. }
  20302. if ( hasFaceColor ) {
  20303. colorIndex = faces[ offset ++ ];
  20304. face.color.setHex( colors[ colorIndex ] );
  20305. }
  20306. if ( hasFaceVertexColor ) {
  20307. for ( i = 0; i < 3; i ++ ) {
  20308. colorIndex = faces[ offset ++ ];
  20309. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  20310. }
  20311. }
  20312. geometry.faces.push( face );
  20313. }
  20314. }
  20315. }
  20316. function parseSkin( json, geometry ) {
  20317. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  20318. if ( json.skinWeights ) {
  20319. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  20320. var x = json.skinWeights[ i ];
  20321. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  20322. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  20323. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  20324. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  20325. }
  20326. }
  20327. if ( json.skinIndices ) {
  20328. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  20329. var a = json.skinIndices[ i ];
  20330. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  20331. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  20332. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  20333. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  20334. }
  20335. }
  20336. geometry.bones = json.bones;
  20337. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  20338. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  20339. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  20340. }
  20341. }
  20342. function parseMorphing( json, geometry ) {
  20343. var scale = json.scale;
  20344. if ( json.morphTargets !== undefined ) {
  20345. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20346. geometry.morphTargets[ i ] = {};
  20347. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20348. geometry.morphTargets[ i ].vertices = [];
  20349. var dstVertices = geometry.morphTargets[ i ].vertices;
  20350. var srcVertices = json.morphTargets[ i ].vertices;
  20351. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20352. var vertex = new Vector3();
  20353. vertex.x = srcVertices[ v ] * scale;
  20354. vertex.y = srcVertices[ v + 1 ] * scale;
  20355. vertex.z = srcVertices[ v + 2 ] * scale;
  20356. dstVertices.push( vertex );
  20357. }
  20358. }
  20359. }
  20360. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  20361. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  20362. var faces = geometry.faces;
  20363. var morphColors = json.morphColors[ 0 ].colors;
  20364. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20365. faces[ i ].color.fromArray( morphColors, i * 3 );
  20366. }
  20367. }
  20368. }
  20369. function parseAnimations( json, geometry ) {
  20370. var outputAnimations = [];
  20371. // parse old style Bone/Hierarchy animations
  20372. var animations = [];
  20373. if ( json.animation !== undefined ) {
  20374. animations.push( json.animation );
  20375. }
  20376. if ( json.animations !== undefined ) {
  20377. if ( json.animations.length ) {
  20378. animations = animations.concat( json.animations );
  20379. } else {
  20380. animations.push( json.animations );
  20381. }
  20382. }
  20383. for ( var i = 0; i < animations.length; i ++ ) {
  20384. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20385. if ( clip ) outputAnimations.push( clip );
  20386. }
  20387. // parse implicit morph animations
  20388. if ( geometry.morphTargets ) {
  20389. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20390. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20391. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20392. }
  20393. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20394. }
  20395. return function ( json, texturePath ) {
  20396. if ( json.data !== undefined ) {
  20397. // Geometry 4.0 spec
  20398. json = json.data;
  20399. }
  20400. if ( json.scale !== undefined ) {
  20401. json.scale = 1.0 / json.scale;
  20402. } else {
  20403. json.scale = 1.0;
  20404. }
  20405. var geometry = new Geometry();
  20406. parseModel( json, geometry );
  20407. parseSkin( json, geometry );
  20408. parseMorphing( json, geometry );
  20409. parseAnimations( json, geometry );
  20410. geometry.computeFaceNormals();
  20411. geometry.computeBoundingSphere();
  20412. if ( json.materials === undefined || json.materials.length === 0 ) {
  20413. return { geometry: geometry };
  20414. } else {
  20415. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20416. return { geometry: geometry, materials: materials };
  20417. }
  20418. };
  20419. } )()
  20420. } );
  20421. /**
  20422. * @author mrdoob / http://mrdoob.com/
  20423. */
  20424. function ObjectLoader( manager ) {
  20425. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20426. this.texturePath = '';
  20427. }
  20428. Object.assign( ObjectLoader.prototype, {
  20429. load: function ( url, onLoad, onProgress, onError ) {
  20430. if ( this.texturePath === '' ) {
  20431. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20432. }
  20433. var scope = this;
  20434. var loader = new FileLoader( scope.manager );
  20435. loader.load( url, function ( text ) {
  20436. var json = null;
  20437. try {
  20438. json = JSON.parse( text );
  20439. } catch ( error ) {
  20440. if ( onError !== undefined ) onError( error );
  20441. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20442. return;
  20443. }
  20444. var metadata = json.metadata;
  20445. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20446. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20447. return;
  20448. }
  20449. scope.parse( json, onLoad );
  20450. }, onProgress, onError );
  20451. },
  20452. setTexturePath: function ( value ) {
  20453. this.texturePath = value;
  20454. },
  20455. setCrossOrigin: function ( value ) {
  20456. this.crossOrigin = value;
  20457. },
  20458. parse: function ( json, onLoad ) {
  20459. var geometries = this.parseGeometries( json.geometries );
  20460. var images = this.parseImages( json.images, function () {
  20461. if ( onLoad !== undefined ) onLoad( object );
  20462. } );
  20463. var textures = this.parseTextures( json.textures, images );
  20464. var materials = this.parseMaterials( json.materials, textures );
  20465. var object = this.parseObject( json.object, geometries, materials );
  20466. if ( json.animations ) {
  20467. object.animations = this.parseAnimations( json.animations );
  20468. }
  20469. if ( json.images === undefined || json.images.length === 0 ) {
  20470. if ( onLoad !== undefined ) onLoad( object );
  20471. }
  20472. return object;
  20473. },
  20474. parseGeometries: function ( json ) {
  20475. var geometries = {};
  20476. if ( json !== undefined ) {
  20477. var geometryLoader = new JSONLoader();
  20478. var bufferGeometryLoader = new BufferGeometryLoader();
  20479. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20480. var geometry;
  20481. var data = json[ i ];
  20482. switch ( data.type ) {
  20483. case 'PlaneGeometry':
  20484. case 'PlaneBufferGeometry':
  20485. geometry = new Geometries[ data.type ](
  20486. data.width,
  20487. data.height,
  20488. data.widthSegments,
  20489. data.heightSegments
  20490. );
  20491. break;
  20492. case 'BoxGeometry':
  20493. case 'BoxBufferGeometry':
  20494. case 'CubeGeometry': // backwards compatible
  20495. geometry = new Geometries[ data.type ](
  20496. data.width,
  20497. data.height,
  20498. data.depth,
  20499. data.widthSegments,
  20500. data.heightSegments,
  20501. data.depthSegments
  20502. );
  20503. break;
  20504. case 'CircleGeometry':
  20505. case 'CircleBufferGeometry':
  20506. geometry = new Geometries[ data.type ](
  20507. data.radius,
  20508. data.segments,
  20509. data.thetaStart,
  20510. data.thetaLength
  20511. );
  20512. break;
  20513. case 'CylinderGeometry':
  20514. case 'CylinderBufferGeometry':
  20515. geometry = new Geometries[ data.type ](
  20516. data.radiusTop,
  20517. data.radiusBottom,
  20518. data.height,
  20519. data.radialSegments,
  20520. data.heightSegments,
  20521. data.openEnded,
  20522. data.thetaStart,
  20523. data.thetaLength
  20524. );
  20525. break;
  20526. case 'ConeGeometry':
  20527. case 'ConeBufferGeometry':
  20528. geometry = new Geometries[ data.type ](
  20529. data.radius,
  20530. data.height,
  20531. data.radialSegments,
  20532. data.heightSegments,
  20533. data.openEnded,
  20534. data.thetaStart,
  20535. data.thetaLength
  20536. );
  20537. break;
  20538. case 'SphereGeometry':
  20539. case 'SphereBufferGeometry':
  20540. geometry = new Geometries[ data.type ](
  20541. data.radius,
  20542. data.widthSegments,
  20543. data.heightSegments,
  20544. data.phiStart,
  20545. data.phiLength,
  20546. data.thetaStart,
  20547. data.thetaLength
  20548. );
  20549. break;
  20550. case 'DodecahedronGeometry':
  20551. case 'IcosahedronGeometry':
  20552. case 'OctahedronGeometry':
  20553. case 'TetrahedronGeometry':
  20554. geometry = new Geometries[ data.type ](
  20555. data.radius,
  20556. data.detail
  20557. );
  20558. break;
  20559. case 'RingGeometry':
  20560. case 'RingBufferGeometry':
  20561. geometry = new Geometries[ data.type ](
  20562. data.innerRadius,
  20563. data.outerRadius,
  20564. data.thetaSegments,
  20565. data.phiSegments,
  20566. data.thetaStart,
  20567. data.thetaLength
  20568. );
  20569. break;
  20570. case 'TorusGeometry':
  20571. case 'TorusBufferGeometry':
  20572. geometry = new Geometries[ data.type ](
  20573. data.radius,
  20574. data.tube,
  20575. data.radialSegments,
  20576. data.tubularSegments,
  20577. data.arc
  20578. );
  20579. break;
  20580. case 'TorusKnotGeometry':
  20581. case 'TorusKnotBufferGeometry':
  20582. geometry = new Geometries[ data.type ](
  20583. data.radius,
  20584. data.tube,
  20585. data.tubularSegments,
  20586. data.radialSegments,
  20587. data.p,
  20588. data.q
  20589. );
  20590. break;
  20591. case 'LatheGeometry':
  20592. case 'LatheBufferGeometry':
  20593. geometry = new Geometries[ data.type ](
  20594. data.points,
  20595. data.segments,
  20596. data.phiStart,
  20597. data.phiLength
  20598. );
  20599. break;
  20600. case 'BufferGeometry':
  20601. geometry = bufferGeometryLoader.parse( data );
  20602. break;
  20603. case 'Geometry':
  20604. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20605. break;
  20606. default:
  20607. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20608. continue;
  20609. }
  20610. geometry.uuid = data.uuid;
  20611. if ( data.name !== undefined ) geometry.name = data.name;
  20612. geometries[ data.uuid ] = geometry;
  20613. }
  20614. }
  20615. return geometries;
  20616. },
  20617. parseMaterials: function ( json, textures ) {
  20618. var materials = {};
  20619. if ( json !== undefined ) {
  20620. var loader = new MaterialLoader();
  20621. loader.setTextures( textures );
  20622. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20623. var data = json[ i ];
  20624. if ( data.type === 'MultiMaterial' ) {
  20625. // Deprecated
  20626. var array = [];
  20627. for ( var j = 0; j < data.materials.length; j ++ ) {
  20628. array.push( loader.parse( data.materials[ j ] ) );
  20629. }
  20630. materials[ data.uuid ] = array;
  20631. } else {
  20632. materials[ data.uuid ] = loader.parse( data );
  20633. }
  20634. }
  20635. }
  20636. return materials;
  20637. },
  20638. parseAnimations: function ( json ) {
  20639. var animations = [];
  20640. for ( var i = 0; i < json.length; i ++ ) {
  20641. var clip = AnimationClip.parse( json[ i ] );
  20642. animations.push( clip );
  20643. }
  20644. return animations;
  20645. },
  20646. parseImages: function ( json, onLoad ) {
  20647. var scope = this;
  20648. var images = {};
  20649. function loadImage( url ) {
  20650. scope.manager.itemStart( url );
  20651. return loader.load( url, function () {
  20652. scope.manager.itemEnd( url );
  20653. }, undefined, function () {
  20654. scope.manager.itemEnd( url );
  20655. scope.manager.itemError( url );
  20656. } );
  20657. }
  20658. if ( json !== undefined && json.length > 0 ) {
  20659. var manager = new LoadingManager( onLoad );
  20660. var loader = new ImageLoader( manager );
  20661. loader.setCrossOrigin( this.crossOrigin );
  20662. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20663. var image = json[ i ];
  20664. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20665. images[ image.uuid ] = loadImage( path );
  20666. }
  20667. }
  20668. return images;
  20669. },
  20670. parseTextures: function ( json, images ) {
  20671. function parseConstant( value, type ) {
  20672. if ( typeof( value ) === 'number' ) return value;
  20673. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20674. return type[ value ];
  20675. }
  20676. var textures = {};
  20677. if ( json !== undefined ) {
  20678. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20679. var data = json[ i ];
  20680. if ( data.image === undefined ) {
  20681. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20682. }
  20683. if ( images[ data.image ] === undefined ) {
  20684. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20685. }
  20686. var texture = new Texture( images[ data.image ] );
  20687. texture.needsUpdate = true;
  20688. texture.uuid = data.uuid;
  20689. if ( data.name !== undefined ) texture.name = data.name;
  20690. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20691. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20692. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20693. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  20694. if ( data.wrap !== undefined ) {
  20695. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20696. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20697. }
  20698. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20699. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20700. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20701. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20702. textures[ data.uuid ] = texture;
  20703. }
  20704. }
  20705. return textures;
  20706. },
  20707. parseObject: function () {
  20708. var matrix = new Matrix4();
  20709. return function parseObject( data, geometries, materials ) {
  20710. var object;
  20711. function getGeometry( name ) {
  20712. if ( geometries[ name ] === undefined ) {
  20713. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20714. }
  20715. return geometries[ name ];
  20716. }
  20717. function getMaterial( name ) {
  20718. if ( name === undefined ) return undefined;
  20719. if ( Array.isArray( name ) ) {
  20720. var array = [];
  20721. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20722. var uuid = name[ i ];
  20723. if ( materials[ uuid ] === undefined ) {
  20724. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20725. }
  20726. array.push( materials[ uuid ] );
  20727. }
  20728. return array;
  20729. }
  20730. if ( materials[ name ] === undefined ) {
  20731. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20732. }
  20733. return materials[ name ];
  20734. }
  20735. switch ( data.type ) {
  20736. case 'Scene':
  20737. object = new Scene();
  20738. if ( data.background !== undefined ) {
  20739. if ( Number.isInteger( data.background ) ) {
  20740. object.background = new Color( data.background );
  20741. }
  20742. }
  20743. if ( data.fog !== undefined ) {
  20744. if ( data.fog.type === 'Fog' ) {
  20745. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20746. } else if ( data.fog.type === 'FogExp2' ) {
  20747. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20748. }
  20749. }
  20750. break;
  20751. case 'PerspectiveCamera':
  20752. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20753. if ( data.focus !== undefined ) object.focus = data.focus;
  20754. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20755. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20756. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20757. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20758. break;
  20759. case 'OrthographicCamera':
  20760. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20761. break;
  20762. case 'AmbientLight':
  20763. object = new AmbientLight( data.color, data.intensity );
  20764. break;
  20765. case 'DirectionalLight':
  20766. object = new DirectionalLight( data.color, data.intensity );
  20767. break;
  20768. case 'PointLight':
  20769. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20770. break;
  20771. case 'RectAreaLight':
  20772. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20773. break;
  20774. case 'SpotLight':
  20775. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20776. break;
  20777. case 'HemisphereLight':
  20778. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20779. break;
  20780. case 'SkinnedMesh':
  20781. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20782. case 'Mesh':
  20783. var geometry = getGeometry( data.geometry );
  20784. var material = getMaterial( data.material );
  20785. if ( geometry.bones && geometry.bones.length > 0 ) {
  20786. object = new SkinnedMesh( geometry, material );
  20787. } else {
  20788. object = new Mesh( geometry, material );
  20789. }
  20790. break;
  20791. case 'LOD':
  20792. object = new LOD();
  20793. break;
  20794. case 'Line':
  20795. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20796. break;
  20797. case 'LineLoop':
  20798. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20799. break;
  20800. case 'LineSegments':
  20801. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20802. break;
  20803. case 'PointCloud':
  20804. case 'Points':
  20805. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20806. break;
  20807. case 'Sprite':
  20808. object = new Sprite( getMaterial( data.material ) );
  20809. break;
  20810. case 'Group':
  20811. object = new Group();
  20812. break;
  20813. default:
  20814. object = new Object3D();
  20815. }
  20816. object.uuid = data.uuid;
  20817. if ( data.name !== undefined ) object.name = data.name;
  20818. if ( data.matrix !== undefined ) {
  20819. matrix.fromArray( data.matrix );
  20820. matrix.decompose( object.position, object.quaternion, object.scale );
  20821. } else {
  20822. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20823. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20824. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20825. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20826. }
  20827. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20828. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20829. if ( data.shadow ) {
  20830. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20831. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20832. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20833. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20834. }
  20835. if ( data.visible !== undefined ) object.visible = data.visible;
  20836. if ( data.userData !== undefined ) object.userData = data.userData;
  20837. if ( data.children !== undefined ) {
  20838. var children = data.children;
  20839. for ( var i = 0; i < children.length; i ++ ) {
  20840. object.add( this.parseObject( children[ i ], geometries, materials ) );
  20841. }
  20842. }
  20843. if ( data.type === 'LOD' ) {
  20844. var levels = data.levels;
  20845. for ( var l = 0; l < levels.length; l ++ ) {
  20846. var level = levels[ l ];
  20847. var child = object.getObjectByProperty( 'uuid', level.object );
  20848. if ( child !== undefined ) {
  20849. object.addLevel( child, level.distance );
  20850. }
  20851. }
  20852. }
  20853. return object;
  20854. };
  20855. }()
  20856. } );
  20857. var TEXTURE_MAPPING = {
  20858. UVMapping: UVMapping,
  20859. CubeReflectionMapping: CubeReflectionMapping,
  20860. CubeRefractionMapping: CubeRefractionMapping,
  20861. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20862. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20863. SphericalReflectionMapping: SphericalReflectionMapping,
  20864. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20865. CubeUVRefractionMapping: CubeUVRefractionMapping
  20866. };
  20867. var TEXTURE_WRAPPING = {
  20868. RepeatWrapping: RepeatWrapping,
  20869. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20870. MirroredRepeatWrapping: MirroredRepeatWrapping
  20871. };
  20872. var TEXTURE_FILTER = {
  20873. NearestFilter: NearestFilter,
  20874. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20875. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20876. LinearFilter: LinearFilter,
  20877. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20878. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20879. };
  20880. /**
  20881. * @author zz85 / http://www.lab4games.net/zz85/blog
  20882. *
  20883. * Bezier Curves formulas obtained from
  20884. * http://en.wikipedia.org/wiki/Bézier_curve
  20885. */
  20886. function CatmullRom( t, p0, p1, p2, p3 ) {
  20887. var v0 = ( p2 - p0 ) * 0.5;
  20888. var v1 = ( p3 - p1 ) * 0.5;
  20889. var t2 = t * t;
  20890. var t3 = t * t2;
  20891. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20892. }
  20893. //
  20894. function QuadraticBezierP0( t, p ) {
  20895. var k = 1 - t;
  20896. return k * k * p;
  20897. }
  20898. function QuadraticBezierP1( t, p ) {
  20899. return 2 * ( 1 - t ) * t * p;
  20900. }
  20901. function QuadraticBezierP2( t, p ) {
  20902. return t * t * p;
  20903. }
  20904. function QuadraticBezier( t, p0, p1, p2 ) {
  20905. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20906. QuadraticBezierP2( t, p2 );
  20907. }
  20908. //
  20909. function CubicBezierP0( t, p ) {
  20910. var k = 1 - t;
  20911. return k * k * k * p;
  20912. }
  20913. function CubicBezierP1( t, p ) {
  20914. var k = 1 - t;
  20915. return 3 * k * k * t * p;
  20916. }
  20917. function CubicBezierP2( t, p ) {
  20918. return 3 * ( 1 - t ) * t * t * p;
  20919. }
  20920. function CubicBezierP3( t, p ) {
  20921. return t * t * t * p;
  20922. }
  20923. function CubicBezier( t, p0, p1, p2, p3 ) {
  20924. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20925. CubicBezierP3( t, p3 );
  20926. }
  20927. /**
  20928. * @author zz85 / http://www.lab4games.net/zz85/blog
  20929. * Extensible curve object
  20930. *
  20931. * Some common of curve methods:
  20932. * .getPoint(t), getTangent(t)
  20933. * .getPointAt(u), getTangentAt(u)
  20934. * .getPoints(), .getSpacedPoints()
  20935. * .getLength()
  20936. * .updateArcLengths()
  20937. *
  20938. * This following curves inherit from THREE.Curve:
  20939. *
  20940. * -- 2D curves --
  20941. * THREE.ArcCurve
  20942. * THREE.CubicBezierCurve
  20943. * THREE.EllipseCurve
  20944. * THREE.LineCurve
  20945. * THREE.QuadraticBezierCurve
  20946. * THREE.SplineCurve
  20947. *
  20948. * -- 3D curves --
  20949. * THREE.CatmullRomCurve3
  20950. * THREE.CubicBezierCurve3
  20951. * THREE.LineCurve3
  20952. * THREE.QuadraticBezierCurve3
  20953. *
  20954. * A series of curves can be represented as a THREE.CurvePath.
  20955. *
  20956. **/
  20957. /**************************************************************
  20958. * Abstract Curve base class
  20959. **************************************************************/
  20960. function Curve() {
  20961. this.arcLengthDivisions = 200;
  20962. }
  20963. Object.assign( Curve.prototype, {
  20964. // Virtual base class method to overwrite and implement in subclasses
  20965. // - t [0 .. 1]
  20966. getPoint: function () {
  20967. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20968. return null;
  20969. },
  20970. // Get point at relative position in curve according to arc length
  20971. // - u [0 .. 1]
  20972. getPointAt: function ( u ) {
  20973. var t = this.getUtoTmapping( u );
  20974. return this.getPoint( t );
  20975. },
  20976. // Get sequence of points using getPoint( t )
  20977. getPoints: function ( divisions ) {
  20978. if ( divisions === undefined ) divisions = 5;
  20979. var points = [];
  20980. for ( var d = 0; d <= divisions; d ++ ) {
  20981. points.push( this.getPoint( d / divisions ) );
  20982. }
  20983. return points;
  20984. },
  20985. // Get sequence of points using getPointAt( u )
  20986. getSpacedPoints: function ( divisions ) {
  20987. if ( divisions === undefined ) divisions = 5;
  20988. var points = [];
  20989. for ( var d = 0; d <= divisions; d ++ ) {
  20990. points.push( this.getPointAt( d / divisions ) );
  20991. }
  20992. return points;
  20993. },
  20994. // Get total curve arc length
  20995. getLength: function () {
  20996. var lengths = this.getLengths();
  20997. return lengths[ lengths.length - 1 ];
  20998. },
  20999. // Get list of cumulative segment lengths
  21000. getLengths: function ( divisions ) {
  21001. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  21002. if ( this.cacheArcLengths &&
  21003. ( this.cacheArcLengths.length === divisions + 1 ) &&
  21004. ! this.needsUpdate ) {
  21005. return this.cacheArcLengths;
  21006. }
  21007. this.needsUpdate = false;
  21008. var cache = [];
  21009. var current, last = this.getPoint( 0 );
  21010. var p, sum = 0;
  21011. cache.push( 0 );
  21012. for ( p = 1; p <= divisions; p ++ ) {
  21013. current = this.getPoint( p / divisions );
  21014. sum += current.distanceTo( last );
  21015. cache.push( sum );
  21016. last = current;
  21017. }
  21018. this.cacheArcLengths = cache;
  21019. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21020. },
  21021. updateArcLengths: function () {
  21022. this.needsUpdate = true;
  21023. this.getLengths();
  21024. },
  21025. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21026. getUtoTmapping: function ( u, distance ) {
  21027. var arcLengths = this.getLengths();
  21028. var i = 0, il = arcLengths.length;
  21029. var targetArcLength; // The targeted u distance value to get
  21030. if ( distance ) {
  21031. targetArcLength = distance;
  21032. } else {
  21033. targetArcLength = u * arcLengths[ il - 1 ];
  21034. }
  21035. // binary search for the index with largest value smaller than target u distance
  21036. var low = 0, high = il - 1, comparison;
  21037. while ( low <= high ) {
  21038. 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
  21039. comparison = arcLengths[ i ] - targetArcLength;
  21040. if ( comparison < 0 ) {
  21041. low = i + 1;
  21042. } else if ( comparison > 0 ) {
  21043. high = i - 1;
  21044. } else {
  21045. high = i;
  21046. break;
  21047. // DONE
  21048. }
  21049. }
  21050. i = high;
  21051. if ( arcLengths[ i ] === targetArcLength ) {
  21052. return i / ( il - 1 );
  21053. }
  21054. // we could get finer grain at lengths, or use simple interpolation between two points
  21055. var lengthBefore = arcLengths[ i ];
  21056. var lengthAfter = arcLengths[ i + 1 ];
  21057. var segmentLength = lengthAfter - lengthBefore;
  21058. // determine where we are between the 'before' and 'after' points
  21059. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21060. // add that fractional amount to t
  21061. var t = ( i + segmentFraction ) / ( il - 1 );
  21062. return t;
  21063. },
  21064. // Returns a unit vector tangent at t
  21065. // In case any sub curve does not implement its tangent derivation,
  21066. // 2 points a small delta apart will be used to find its gradient
  21067. // which seems to give a reasonable approximation
  21068. getTangent: function ( t ) {
  21069. var delta = 0.0001;
  21070. var t1 = t - delta;
  21071. var t2 = t + delta;
  21072. // Capping in case of danger
  21073. if ( t1 < 0 ) t1 = 0;
  21074. if ( t2 > 1 ) t2 = 1;
  21075. var pt1 = this.getPoint( t1 );
  21076. var pt2 = this.getPoint( t2 );
  21077. var vec = pt2.clone().sub( pt1 );
  21078. return vec.normalize();
  21079. },
  21080. getTangentAt: function ( u ) {
  21081. var t = this.getUtoTmapping( u );
  21082. return this.getTangent( t );
  21083. },
  21084. computeFrenetFrames: function ( segments, closed ) {
  21085. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21086. var normal = new Vector3();
  21087. var tangents = [];
  21088. var normals = [];
  21089. var binormals = [];
  21090. var vec = new Vector3();
  21091. var mat = new Matrix4();
  21092. var i, u, theta;
  21093. // compute the tangent vectors for each segment on the curve
  21094. for ( i = 0; i <= segments; i ++ ) {
  21095. u = i / segments;
  21096. tangents[ i ] = this.getTangentAt( u );
  21097. tangents[ i ].normalize();
  21098. }
  21099. // select an initial normal vector perpendicular to the first tangent vector,
  21100. // and in the direction of the minimum tangent xyz component
  21101. normals[ 0 ] = new Vector3();
  21102. binormals[ 0 ] = new Vector3();
  21103. var min = Number.MAX_VALUE;
  21104. var tx = Math.abs( tangents[ 0 ].x );
  21105. var ty = Math.abs( tangents[ 0 ].y );
  21106. var tz = Math.abs( tangents[ 0 ].z );
  21107. if ( tx <= min ) {
  21108. min = tx;
  21109. normal.set( 1, 0, 0 );
  21110. }
  21111. if ( ty <= min ) {
  21112. min = ty;
  21113. normal.set( 0, 1, 0 );
  21114. }
  21115. if ( tz <= min ) {
  21116. normal.set( 0, 0, 1 );
  21117. }
  21118. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21119. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21120. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21121. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21122. for ( i = 1; i <= segments; i ++ ) {
  21123. normals[ i ] = normals[ i - 1 ].clone();
  21124. binormals[ i ] = binormals[ i - 1 ].clone();
  21125. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21126. if ( vec.length() > Number.EPSILON ) {
  21127. vec.normalize();
  21128. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21129. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21130. }
  21131. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21132. }
  21133. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21134. if ( closed === true ) {
  21135. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21136. theta /= segments;
  21137. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21138. theta = - theta;
  21139. }
  21140. for ( i = 1; i <= segments; i ++ ) {
  21141. // twist a little...
  21142. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21143. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21144. }
  21145. }
  21146. return {
  21147. tangents: tangents,
  21148. normals: normals,
  21149. binormals: binormals
  21150. };
  21151. }
  21152. } );
  21153. function LineCurve( v1, v2 ) {
  21154. Curve.call( this );
  21155. this.v1 = v1;
  21156. this.v2 = v2;
  21157. }
  21158. LineCurve.prototype = Object.create( Curve.prototype );
  21159. LineCurve.prototype.constructor = LineCurve;
  21160. LineCurve.prototype.isLineCurve = true;
  21161. LineCurve.prototype.getPoint = function ( t ) {
  21162. if ( t === 1 ) {
  21163. return this.v2.clone();
  21164. }
  21165. var point = this.v2.clone().sub( this.v1 );
  21166. point.multiplyScalar( t ).add( this.v1 );
  21167. return point;
  21168. };
  21169. // Line curve is linear, so we can overwrite default getPointAt
  21170. LineCurve.prototype.getPointAt = function ( u ) {
  21171. return this.getPoint( u );
  21172. };
  21173. LineCurve.prototype.getTangent = function ( t ) {
  21174. var tangent = this.v2.clone().sub( this.v1 );
  21175. return tangent.normalize();
  21176. };
  21177. /**
  21178. * @author zz85 / http://www.lab4games.net/zz85/blog
  21179. *
  21180. **/
  21181. /**************************************************************
  21182. * Curved Path - a curve path is simply a array of connected
  21183. * curves, but retains the api of a curve
  21184. **************************************************************/
  21185. function CurvePath() {
  21186. Curve.call( this );
  21187. this.curves = [];
  21188. this.autoClose = false; // Automatically closes the path
  21189. }
  21190. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  21191. constructor: CurvePath,
  21192. add: function ( curve ) {
  21193. this.curves.push( curve );
  21194. },
  21195. closePath: function () {
  21196. // Add a line curve if start and end of lines are not connected
  21197. var startPoint = this.curves[ 0 ].getPoint( 0 );
  21198. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21199. if ( ! startPoint.equals( endPoint ) ) {
  21200. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21201. }
  21202. },
  21203. // To get accurate point with reference to
  21204. // entire path distance at time t,
  21205. // following has to be done:
  21206. // 1. Length of each sub path have to be known
  21207. // 2. Locate and identify type of curve
  21208. // 3. Get t for the curve
  21209. // 4. Return curve.getPointAt(t')
  21210. getPoint: function ( t ) {
  21211. var d = t * this.getLength();
  21212. var curveLengths = this.getCurveLengths();
  21213. var i = 0;
  21214. // To think about boundaries points.
  21215. while ( i < curveLengths.length ) {
  21216. if ( curveLengths[ i ] >= d ) {
  21217. var diff = curveLengths[ i ] - d;
  21218. var curve = this.curves[ i ];
  21219. var segmentLength = curve.getLength();
  21220. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21221. return curve.getPointAt( u );
  21222. }
  21223. i ++;
  21224. }
  21225. return null;
  21226. // loop where sum != 0, sum > d , sum+1 <d
  21227. },
  21228. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21229. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21230. // getPoint() depends on getLength
  21231. getLength: function () {
  21232. var lens = this.getCurveLengths();
  21233. return lens[ lens.length - 1 ];
  21234. },
  21235. // cacheLengths must be recalculated.
  21236. updateArcLengths: function () {
  21237. this.needsUpdate = true;
  21238. this.cacheLengths = null;
  21239. this.getCurveLengths();
  21240. },
  21241. // Compute lengths and cache them
  21242. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21243. getCurveLengths: function () {
  21244. // We use cache values if curves and cache array are same length
  21245. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21246. return this.cacheLengths;
  21247. }
  21248. // Get length of sub-curve
  21249. // Push sums into cached array
  21250. var lengths = [], sums = 0;
  21251. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  21252. sums += this.curves[ i ].getLength();
  21253. lengths.push( sums );
  21254. }
  21255. this.cacheLengths = lengths;
  21256. return lengths;
  21257. },
  21258. getSpacedPoints: function ( divisions ) {
  21259. if ( divisions === undefined ) divisions = 40;
  21260. var points = [];
  21261. for ( var i = 0; i <= divisions; i ++ ) {
  21262. points.push( this.getPoint( i / divisions ) );
  21263. }
  21264. if ( this.autoClose ) {
  21265. points.push( points[ 0 ] );
  21266. }
  21267. return points;
  21268. },
  21269. getPoints: function ( divisions ) {
  21270. divisions = divisions || 12;
  21271. var points = [], last;
  21272. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21273. var curve = curves[ i ];
  21274. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  21275. : (curve && curve.isLineCurve) ? 1
  21276. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  21277. : divisions;
  21278. var pts = curve.getPoints( resolution );
  21279. for ( var j = 0; j < pts.length; j++ ) {
  21280. var point = pts[ j ];
  21281. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21282. points.push( point );
  21283. last = point;
  21284. }
  21285. }
  21286. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21287. points.push( points[ 0 ] );
  21288. }
  21289. return points;
  21290. },
  21291. /**************************************************************
  21292. * Create Geometries Helpers
  21293. **************************************************************/
  21294. /// Generate geometry from path points (for Line or Points objects)
  21295. createPointsGeometry: function ( divisions ) {
  21296. var pts = this.getPoints( divisions );
  21297. return this.createGeometry( pts );
  21298. },
  21299. // Generate geometry from equidistant sampling along the path
  21300. createSpacedPointsGeometry: function ( divisions ) {
  21301. var pts = this.getSpacedPoints( divisions );
  21302. return this.createGeometry( pts );
  21303. },
  21304. createGeometry: function ( points ) {
  21305. var geometry = new Geometry();
  21306. for ( var i = 0, l = points.length; i < l; i ++ ) {
  21307. var point = points[ i ];
  21308. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  21309. }
  21310. return geometry;
  21311. }
  21312. } );
  21313. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21314. Curve.call( this );
  21315. this.aX = aX;
  21316. this.aY = aY;
  21317. this.xRadius = xRadius;
  21318. this.yRadius = yRadius;
  21319. this.aStartAngle = aStartAngle;
  21320. this.aEndAngle = aEndAngle;
  21321. this.aClockwise = aClockwise;
  21322. this.aRotation = aRotation || 0;
  21323. }
  21324. EllipseCurve.prototype = Object.create( Curve.prototype );
  21325. EllipseCurve.prototype.constructor = EllipseCurve;
  21326. EllipseCurve.prototype.isEllipseCurve = true;
  21327. EllipseCurve.prototype.getPoint = function ( t ) {
  21328. var twoPi = Math.PI * 2;
  21329. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21330. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21331. // ensures that deltaAngle is 0 .. 2 PI
  21332. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21333. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21334. if ( deltaAngle < Number.EPSILON ) {
  21335. if ( samePoints ) {
  21336. deltaAngle = 0;
  21337. } else {
  21338. deltaAngle = twoPi;
  21339. }
  21340. }
  21341. if ( this.aClockwise === true && ! samePoints ) {
  21342. if ( deltaAngle === twoPi ) {
  21343. deltaAngle = - twoPi;
  21344. } else {
  21345. deltaAngle = deltaAngle - twoPi;
  21346. }
  21347. }
  21348. var angle = this.aStartAngle + t * deltaAngle;
  21349. var x = this.aX + this.xRadius * Math.cos( angle );
  21350. var y = this.aY + this.yRadius * Math.sin( angle );
  21351. if ( this.aRotation !== 0 ) {
  21352. var cos = Math.cos( this.aRotation );
  21353. var sin = Math.sin( this.aRotation );
  21354. var tx = x - this.aX;
  21355. var ty = y - this.aY;
  21356. // Rotate the point about the center of the ellipse.
  21357. x = tx * cos - ty * sin + this.aX;
  21358. y = tx * sin + ty * cos + this.aY;
  21359. }
  21360. return new Vector2( x, y );
  21361. };
  21362. function SplineCurve( points /* array of Vector2 */ ) {
  21363. Curve.call( this );
  21364. this.points = ( points === undefined ) ? [] : points;
  21365. }
  21366. SplineCurve.prototype = Object.create( Curve.prototype );
  21367. SplineCurve.prototype.constructor = SplineCurve;
  21368. SplineCurve.prototype.isSplineCurve = true;
  21369. SplineCurve.prototype.getPoint = function ( t ) {
  21370. var points = this.points;
  21371. var point = ( points.length - 1 ) * t;
  21372. var intPoint = Math.floor( point );
  21373. var weight = point - intPoint;
  21374. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21375. var point1 = points[ intPoint ];
  21376. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21377. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21378. return new Vector2(
  21379. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21380. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21381. );
  21382. };
  21383. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21384. Curve.call( this );
  21385. this.v0 = v0;
  21386. this.v1 = v1;
  21387. this.v2 = v2;
  21388. this.v3 = v3;
  21389. }
  21390. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21391. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21392. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21393. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21394. return new Vector2(
  21395. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21396. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21397. );
  21398. };
  21399. function QuadraticBezierCurve( v0, v1, v2 ) {
  21400. Curve.call( this );
  21401. this.v0 = v0;
  21402. this.v1 = v1;
  21403. this.v2 = v2;
  21404. }
  21405. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21406. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21407. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21408. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21409. return new Vector2(
  21410. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21411. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21412. );
  21413. };
  21414. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21415. fromPoints: function ( vectors ) {
  21416. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21417. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21418. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21419. }
  21420. },
  21421. moveTo: function ( x, y ) {
  21422. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21423. },
  21424. lineTo: function ( x, y ) {
  21425. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21426. this.curves.push( curve );
  21427. this.currentPoint.set( x, y );
  21428. },
  21429. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21430. var curve = new QuadraticBezierCurve(
  21431. this.currentPoint.clone(),
  21432. new Vector2( aCPx, aCPy ),
  21433. new Vector2( aX, aY )
  21434. );
  21435. this.curves.push( curve );
  21436. this.currentPoint.set( aX, aY );
  21437. },
  21438. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21439. var curve = new CubicBezierCurve(
  21440. this.currentPoint.clone(),
  21441. new Vector2( aCP1x, aCP1y ),
  21442. new Vector2( aCP2x, aCP2y ),
  21443. new Vector2( aX, aY )
  21444. );
  21445. this.curves.push( curve );
  21446. this.currentPoint.set( aX, aY );
  21447. },
  21448. splineThru: function ( pts /*Array of Vector*/ ) {
  21449. var npts = [ this.currentPoint.clone() ].concat( pts );
  21450. var curve = new SplineCurve( npts );
  21451. this.curves.push( curve );
  21452. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21453. },
  21454. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21455. var x0 = this.currentPoint.x;
  21456. var y0 = this.currentPoint.y;
  21457. this.absarc( aX + x0, aY + y0, aRadius,
  21458. aStartAngle, aEndAngle, aClockwise );
  21459. },
  21460. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21461. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21462. },
  21463. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21464. var x0 = this.currentPoint.x;
  21465. var y0 = this.currentPoint.y;
  21466. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21467. },
  21468. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21469. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21470. if ( this.curves.length > 0 ) {
  21471. // if a previous curve is present, attempt to join
  21472. var firstPoint = curve.getPoint( 0 );
  21473. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21474. this.lineTo( firstPoint.x, firstPoint.y );
  21475. }
  21476. }
  21477. this.curves.push( curve );
  21478. var lastPoint = curve.getPoint( 1 );
  21479. this.currentPoint.copy( lastPoint );
  21480. }
  21481. } );
  21482. /**
  21483. * @author zz85 / http://www.lab4games.net/zz85/blog
  21484. * Creates free form 2d path using series of points, lines or curves.
  21485. **/
  21486. function Path( points ) {
  21487. CurvePath.call( this );
  21488. this.currentPoint = new Vector2();
  21489. if ( points ) {
  21490. this.fromPoints( points );
  21491. }
  21492. }
  21493. Path.prototype = PathPrototype;
  21494. PathPrototype.constructor = Path;
  21495. /**
  21496. * @author zz85 / http://www.lab4games.net/zz85/blog
  21497. * Defines a 2d shape plane using paths.
  21498. **/
  21499. // STEP 1 Create a path.
  21500. // STEP 2 Turn path into shape.
  21501. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21502. // STEP 3a - Extract points from each shape, turn to vertices
  21503. // STEP 3b - Triangulate each shape, add faces.
  21504. function Shape() {
  21505. Path.apply( this, arguments );
  21506. this.holes = [];
  21507. }
  21508. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21509. constructor: Shape,
  21510. getPointsHoles: function ( divisions ) {
  21511. var holesPts = [];
  21512. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21513. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21514. }
  21515. return holesPts;
  21516. },
  21517. // Get points of shape and holes (keypoints based on segments parameter)
  21518. extractAllPoints: function ( divisions ) {
  21519. return {
  21520. shape: this.getPoints( divisions ),
  21521. holes: this.getPointsHoles( divisions )
  21522. };
  21523. },
  21524. extractPoints: function ( divisions ) {
  21525. return this.extractAllPoints( divisions );
  21526. }
  21527. } );
  21528. /**
  21529. * @author zz85 / http://www.lab4games.net/zz85/blog
  21530. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21531. **/
  21532. function ShapePath() {
  21533. this.subPaths = [];
  21534. this.currentPath = null;
  21535. }
  21536. Object.assign( ShapePath.prototype, {
  21537. moveTo: function ( x, y ) {
  21538. this.currentPath = new Path();
  21539. this.subPaths.push( this.currentPath );
  21540. this.currentPath.moveTo( x, y );
  21541. },
  21542. lineTo: function ( x, y ) {
  21543. this.currentPath.lineTo( x, y );
  21544. },
  21545. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21546. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21547. },
  21548. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21549. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21550. },
  21551. splineThru: function ( pts ) {
  21552. this.currentPath.splineThru( pts );
  21553. },
  21554. toShapes: function ( isCCW, noHoles ) {
  21555. function toShapesNoHoles( inSubpaths ) {
  21556. var shapes = [];
  21557. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21558. var tmpPath = inSubpaths[ i ];
  21559. var tmpShape = new Shape();
  21560. tmpShape.curves = tmpPath.curves;
  21561. shapes.push( tmpShape );
  21562. }
  21563. return shapes;
  21564. }
  21565. function isPointInsidePolygon( inPt, inPolygon ) {
  21566. var polyLen = inPolygon.length;
  21567. // inPt on polygon contour => immediate success or
  21568. // toggling of inside/outside at every single! intersection point of an edge
  21569. // with the horizontal line through inPt, left of inPt
  21570. // not counting lowerY endpoints of edges and whole edges on that line
  21571. var inside = false;
  21572. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21573. var edgeLowPt = inPolygon[ p ];
  21574. var edgeHighPt = inPolygon[ q ];
  21575. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21576. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21577. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21578. // not parallel
  21579. if ( edgeDy < 0 ) {
  21580. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21581. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21582. }
  21583. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21584. if ( inPt.y === edgeLowPt.y ) {
  21585. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21586. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21587. } else {
  21588. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21589. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21590. if ( perpEdge < 0 ) continue;
  21591. inside = ! inside; // true intersection left of inPt
  21592. }
  21593. } else {
  21594. // parallel or collinear
  21595. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21596. // edge lies on the same horizontal line as inPt
  21597. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21598. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21599. // continue;
  21600. }
  21601. }
  21602. return inside;
  21603. }
  21604. var isClockWise = ShapeUtils.isClockWise;
  21605. var subPaths = this.subPaths;
  21606. if ( subPaths.length === 0 ) return [];
  21607. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21608. var solid, tmpPath, tmpShape, shapes = [];
  21609. if ( subPaths.length === 1 ) {
  21610. tmpPath = subPaths[ 0 ];
  21611. tmpShape = new Shape();
  21612. tmpShape.curves = tmpPath.curves;
  21613. shapes.push( tmpShape );
  21614. return shapes;
  21615. }
  21616. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21617. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21618. // console.log("Holes first", holesFirst);
  21619. var betterShapeHoles = [];
  21620. var newShapes = [];
  21621. var newShapeHoles = [];
  21622. var mainIdx = 0;
  21623. var tmpPoints;
  21624. newShapes[ mainIdx ] = undefined;
  21625. newShapeHoles[ mainIdx ] = [];
  21626. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21627. tmpPath = subPaths[ i ];
  21628. tmpPoints = tmpPath.getPoints();
  21629. solid = isClockWise( tmpPoints );
  21630. solid = isCCW ? ! solid : solid;
  21631. if ( solid ) {
  21632. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21633. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21634. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21635. if ( holesFirst ) mainIdx ++;
  21636. newShapeHoles[ mainIdx ] = [];
  21637. //console.log('cw', i);
  21638. } else {
  21639. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21640. //console.log('ccw', i);
  21641. }
  21642. }
  21643. // only Holes? -> probably all Shapes with wrong orientation
  21644. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21645. if ( newShapes.length > 1 ) {
  21646. var ambiguous = false;
  21647. var toChange = [];
  21648. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21649. betterShapeHoles[ sIdx ] = [];
  21650. }
  21651. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21652. var sho = newShapeHoles[ sIdx ];
  21653. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21654. var ho = sho[ hIdx ];
  21655. var hole_unassigned = true;
  21656. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21657. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21658. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21659. if ( hole_unassigned ) {
  21660. hole_unassigned = false;
  21661. betterShapeHoles[ s2Idx ].push( ho );
  21662. } else {
  21663. ambiguous = true;
  21664. }
  21665. }
  21666. }
  21667. if ( hole_unassigned ) {
  21668. betterShapeHoles[ sIdx ].push( ho );
  21669. }
  21670. }
  21671. }
  21672. // console.log("ambiguous: ", ambiguous);
  21673. if ( toChange.length > 0 ) {
  21674. // console.log("to change: ", toChange);
  21675. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21676. }
  21677. }
  21678. var tmpHoles;
  21679. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21680. tmpShape = newShapes[ i ].s;
  21681. shapes.push( tmpShape );
  21682. tmpHoles = newShapeHoles[ i ];
  21683. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21684. tmpShape.holes.push( tmpHoles[ j ].h );
  21685. }
  21686. }
  21687. //console.log("shape", shapes);
  21688. return shapes;
  21689. }
  21690. } );
  21691. /**
  21692. * @author zz85 / http://www.lab4games.net/zz85/blog
  21693. * @author mrdoob / http://mrdoob.com/
  21694. */
  21695. function Font( data ) {
  21696. this.data = data;
  21697. }
  21698. Object.assign( Font.prototype, {
  21699. isFont: true,
  21700. generateShapes: function ( text, size, divisions ) {
  21701. function createPaths( text ) {
  21702. var chars = String( text ).split( '' );
  21703. var scale = size / data.resolution;
  21704. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21705. var offsetX = 0, offsetY = 0;
  21706. var paths = [];
  21707. for ( var i = 0; i < chars.length; i ++ ) {
  21708. var char = chars[ i ];
  21709. if ( char === '\n' ) {
  21710. offsetX = 0;
  21711. offsetY -= line_height;
  21712. } else {
  21713. var ret = createPath( char, scale, offsetX, offsetY );
  21714. offsetX += ret.offsetX;
  21715. paths.push( ret.path );
  21716. }
  21717. }
  21718. return paths;
  21719. }
  21720. function createPath( c, scale, offsetX, offsetY ) {
  21721. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21722. if ( ! glyph ) return;
  21723. var path = new ShapePath();
  21724. var pts = [];
  21725. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21726. if ( glyph.o ) {
  21727. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21728. for ( var i = 0, l = outline.length; i < l; ) {
  21729. var action = outline[ i ++ ];
  21730. switch ( action ) {
  21731. case 'm': // moveTo
  21732. x = outline[ i ++ ] * scale + offsetX;
  21733. y = outline[ i ++ ] * scale + offsetY;
  21734. path.moveTo( x, y );
  21735. break;
  21736. case 'l': // lineTo
  21737. x = outline[ i ++ ] * scale + offsetX;
  21738. y = outline[ i ++ ] * scale + offsetY;
  21739. path.lineTo( x, y );
  21740. break;
  21741. case 'q': // quadraticCurveTo
  21742. cpx = outline[ i ++ ] * scale + offsetX;
  21743. cpy = outline[ i ++ ] * scale + offsetY;
  21744. cpx1 = outline[ i ++ ] * scale + offsetX;
  21745. cpy1 = outline[ i ++ ] * scale + offsetY;
  21746. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21747. laste = pts[ pts.length - 1 ];
  21748. if ( laste ) {
  21749. cpx0 = laste.x;
  21750. cpy0 = laste.y;
  21751. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21752. var t = i2 / divisions;
  21753. QuadraticBezier( t, cpx0, cpx1, cpx );
  21754. QuadraticBezier( t, cpy0, cpy1, cpy );
  21755. }
  21756. }
  21757. break;
  21758. case 'b': // bezierCurveTo
  21759. cpx = outline[ i ++ ] * scale + offsetX;
  21760. cpy = outline[ i ++ ] * scale + offsetY;
  21761. cpx1 = outline[ i ++ ] * scale + offsetX;
  21762. cpy1 = outline[ i ++ ] * scale + offsetY;
  21763. cpx2 = outline[ i ++ ] * scale + offsetX;
  21764. cpy2 = outline[ i ++ ] * scale + offsetY;
  21765. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21766. laste = pts[ pts.length - 1 ];
  21767. if ( laste ) {
  21768. cpx0 = laste.x;
  21769. cpy0 = laste.y;
  21770. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21771. var t = i2 / divisions;
  21772. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21773. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21774. }
  21775. }
  21776. break;
  21777. }
  21778. }
  21779. }
  21780. return { offsetX: glyph.ha * scale, path: path };
  21781. }
  21782. //
  21783. if ( size === undefined ) size = 100;
  21784. if ( divisions === undefined ) divisions = 4;
  21785. var data = this.data;
  21786. var paths = createPaths( text );
  21787. var shapes = [];
  21788. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21789. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21790. }
  21791. return shapes;
  21792. }
  21793. } );
  21794. /**
  21795. * @author mrdoob / http://mrdoob.com/
  21796. */
  21797. function FontLoader( manager ) {
  21798. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21799. }
  21800. Object.assign( FontLoader.prototype, {
  21801. load: function ( url, onLoad, onProgress, onError ) {
  21802. var scope = this;
  21803. var loader = new FileLoader( this.manager );
  21804. loader.setPath( this.path );
  21805. loader.load( url, function ( text ) {
  21806. var json;
  21807. try {
  21808. json = JSON.parse( text );
  21809. } catch ( e ) {
  21810. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21811. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21812. }
  21813. var font = scope.parse( json );
  21814. if ( onLoad ) onLoad( font );
  21815. }, onProgress, onError );
  21816. },
  21817. parse: function ( json ) {
  21818. return new Font( json );
  21819. },
  21820. setPath: function ( value ) {
  21821. this.path = value;
  21822. return this;
  21823. }
  21824. } );
  21825. var context;
  21826. var AudioContext = {
  21827. getContext: function () {
  21828. if ( context === undefined ) {
  21829. context = new ( window.AudioContext || window.webkitAudioContext )();
  21830. }
  21831. return context;
  21832. },
  21833. setContext: function ( value ) {
  21834. context = value;
  21835. }
  21836. };
  21837. /**
  21838. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21839. */
  21840. function AudioLoader( manager ) {
  21841. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21842. }
  21843. Object.assign( AudioLoader.prototype, {
  21844. load: function ( url, onLoad, onProgress, onError ) {
  21845. var loader = new FileLoader( this.manager );
  21846. loader.setResponseType( 'arraybuffer' );
  21847. loader.load( url, function ( buffer ) {
  21848. var context = AudioContext.getContext();
  21849. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21850. onLoad( audioBuffer );
  21851. } );
  21852. }, onProgress, onError );
  21853. }
  21854. } );
  21855. /**
  21856. * @author mrdoob / http://mrdoob.com/
  21857. */
  21858. function StereoCamera() {
  21859. this.type = 'StereoCamera';
  21860. this.aspect = 1;
  21861. this.eyeSep = 0.064;
  21862. this.cameraL = new PerspectiveCamera();
  21863. this.cameraL.layers.enable( 1 );
  21864. this.cameraL.matrixAutoUpdate = false;
  21865. this.cameraR = new PerspectiveCamera();
  21866. this.cameraR.layers.enable( 2 );
  21867. this.cameraR.matrixAutoUpdate = false;
  21868. }
  21869. Object.assign( StereoCamera.prototype, {
  21870. update: ( function () {
  21871. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21872. var eyeRight = new Matrix4();
  21873. var eyeLeft = new Matrix4();
  21874. return function update( camera ) {
  21875. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21876. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21877. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21878. if ( needsUpdate ) {
  21879. instance = this;
  21880. focus = camera.focus;
  21881. fov = camera.fov;
  21882. aspect = camera.aspect * this.aspect;
  21883. near = camera.near;
  21884. far = camera.far;
  21885. zoom = camera.zoom;
  21886. // Off-axis stereoscopic effect based on
  21887. // http://paulbourke.net/stereographics/stereorender/
  21888. var projectionMatrix = camera.projectionMatrix.clone();
  21889. eyeSep = this.eyeSep / 2;
  21890. var eyeSepOnProjection = eyeSep * near / focus;
  21891. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21892. var xmin, xmax;
  21893. // translate xOffset
  21894. eyeLeft.elements[ 12 ] = - eyeSep;
  21895. eyeRight.elements[ 12 ] = eyeSep;
  21896. // for left eye
  21897. xmin = - ymax * aspect + eyeSepOnProjection;
  21898. xmax = ymax * aspect + eyeSepOnProjection;
  21899. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21900. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21901. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21902. // for right eye
  21903. xmin = - ymax * aspect - eyeSepOnProjection;
  21904. xmax = ymax * aspect - eyeSepOnProjection;
  21905. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21906. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21907. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21908. }
  21909. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21910. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21911. };
  21912. } )()
  21913. } );
  21914. /**
  21915. * Camera for rendering cube maps
  21916. * - renders scene into axis-aligned cube
  21917. *
  21918. * @author alteredq / http://alteredqualia.com/
  21919. */
  21920. function CubeCamera( near, far, cubeResolution ) {
  21921. Object3D.call( this );
  21922. this.type = 'CubeCamera';
  21923. var fov = 90, aspect = 1;
  21924. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21925. cameraPX.up.set( 0, - 1, 0 );
  21926. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21927. this.add( cameraPX );
  21928. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21929. cameraNX.up.set( 0, - 1, 0 );
  21930. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21931. this.add( cameraNX );
  21932. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21933. cameraPY.up.set( 0, 0, 1 );
  21934. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21935. this.add( cameraPY );
  21936. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21937. cameraNY.up.set( 0, 0, - 1 );
  21938. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21939. this.add( cameraNY );
  21940. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21941. cameraPZ.up.set( 0, - 1, 0 );
  21942. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21943. this.add( cameraPZ );
  21944. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21945. cameraNZ.up.set( 0, - 1, 0 );
  21946. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21947. this.add( cameraNZ );
  21948. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21949. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21950. this.renderTarget.texture.name = "CubeCamera";
  21951. this.update = function ( renderer, scene ) {
  21952. if ( this.parent === null ) this.updateMatrixWorld();
  21953. var renderTarget = this.renderTarget;
  21954. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21955. renderTarget.texture.generateMipmaps = false;
  21956. renderTarget.activeCubeFace = 0;
  21957. renderer.render( scene, cameraPX, renderTarget );
  21958. renderTarget.activeCubeFace = 1;
  21959. renderer.render( scene, cameraNX, renderTarget );
  21960. renderTarget.activeCubeFace = 2;
  21961. renderer.render( scene, cameraPY, renderTarget );
  21962. renderTarget.activeCubeFace = 3;
  21963. renderer.render( scene, cameraNY, renderTarget );
  21964. renderTarget.activeCubeFace = 4;
  21965. renderer.render( scene, cameraPZ, renderTarget );
  21966. renderTarget.texture.generateMipmaps = generateMipmaps;
  21967. renderTarget.activeCubeFace = 5;
  21968. renderer.render( scene, cameraNZ, renderTarget );
  21969. renderer.setRenderTarget( null );
  21970. };
  21971. this.clear = function ( renderer, color, depth, stencil ) {
  21972. var renderTarget = this.renderTarget;
  21973. for ( var i = 0; i < 6; i ++ ) {
  21974. renderTarget.activeCubeFace = i;
  21975. renderer.setRenderTarget( renderTarget );
  21976. renderer.clear( color, depth, stencil );
  21977. }
  21978. renderer.setRenderTarget( null );
  21979. };
  21980. }
  21981. CubeCamera.prototype = Object.create( Object3D.prototype );
  21982. CubeCamera.prototype.constructor = CubeCamera;
  21983. /**
  21984. * @author mrdoob / http://mrdoob.com/
  21985. */
  21986. function AudioListener() {
  21987. Object3D.call( this );
  21988. this.type = 'AudioListener';
  21989. this.context = AudioContext.getContext();
  21990. this.gain = this.context.createGain();
  21991. this.gain.connect( this.context.destination );
  21992. this.filter = null;
  21993. }
  21994. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21995. constructor: AudioListener,
  21996. getInput: function () {
  21997. return this.gain;
  21998. },
  21999. removeFilter: function ( ) {
  22000. if ( this.filter !== null ) {
  22001. this.gain.disconnect( this.filter );
  22002. this.filter.disconnect( this.context.destination );
  22003. this.gain.connect( this.context.destination );
  22004. this.filter = null;
  22005. }
  22006. },
  22007. getFilter: function () {
  22008. return this.filter;
  22009. },
  22010. setFilter: function ( value ) {
  22011. if ( this.filter !== null ) {
  22012. this.gain.disconnect( this.filter );
  22013. this.filter.disconnect( this.context.destination );
  22014. } else {
  22015. this.gain.disconnect( this.context.destination );
  22016. }
  22017. this.filter = value;
  22018. this.gain.connect( this.filter );
  22019. this.filter.connect( this.context.destination );
  22020. },
  22021. getMasterVolume: function () {
  22022. return this.gain.gain.value;
  22023. },
  22024. setMasterVolume: function ( value ) {
  22025. this.gain.gain.value = value;
  22026. },
  22027. updateMatrixWorld: ( function () {
  22028. var position = new Vector3();
  22029. var quaternion = new Quaternion();
  22030. var scale = new Vector3();
  22031. var orientation = new Vector3();
  22032. return function updateMatrixWorld( force ) {
  22033. Object3D.prototype.updateMatrixWorld.call( this, force );
  22034. var listener = this.context.listener;
  22035. var up = this.up;
  22036. this.matrixWorld.decompose( position, quaternion, scale );
  22037. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  22038. if ( listener.positionX ) {
  22039. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  22040. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  22041. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  22042. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  22043. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  22044. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  22045. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  22046. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  22047. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  22048. } else {
  22049. listener.setPosition( position.x, position.y, position.z );
  22050. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  22051. }
  22052. };
  22053. } )()
  22054. } );
  22055. /**
  22056. * @author mrdoob / http://mrdoob.com/
  22057. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  22058. */
  22059. function Audio( listener ) {
  22060. Object3D.call( this );
  22061. this.type = 'Audio';
  22062. this.context = listener.context;
  22063. this.gain = this.context.createGain();
  22064. this.gain.connect( listener.getInput() );
  22065. this.autoplay = false;
  22066. this.buffer = null;
  22067. this.loop = false;
  22068. this.startTime = 0;
  22069. this.playbackRate = 1;
  22070. this.isPlaying = false;
  22071. this.hasPlaybackControl = true;
  22072. this.sourceType = 'empty';
  22073. this.filters = [];
  22074. }
  22075. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22076. constructor: Audio,
  22077. getOutput: function () {
  22078. return this.gain;
  22079. },
  22080. setNodeSource: function ( audioNode ) {
  22081. this.hasPlaybackControl = false;
  22082. this.sourceType = 'audioNode';
  22083. this.source = audioNode;
  22084. this.connect();
  22085. return this;
  22086. },
  22087. setBuffer: function ( audioBuffer ) {
  22088. this.buffer = audioBuffer;
  22089. this.sourceType = 'buffer';
  22090. if ( this.autoplay ) this.play();
  22091. return this;
  22092. },
  22093. play: function () {
  22094. if ( this.isPlaying === true ) {
  22095. console.warn( 'THREE.Audio: Audio is already playing.' );
  22096. return;
  22097. }
  22098. if ( this.hasPlaybackControl === false ) {
  22099. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22100. return;
  22101. }
  22102. var source = this.context.createBufferSource();
  22103. source.buffer = this.buffer;
  22104. source.loop = this.loop;
  22105. source.onended = this.onEnded.bind( this );
  22106. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  22107. source.start( 0, this.startTime );
  22108. this.isPlaying = true;
  22109. this.source = source;
  22110. return this.connect();
  22111. },
  22112. pause: function () {
  22113. if ( this.hasPlaybackControl === false ) {
  22114. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22115. return;
  22116. }
  22117. this.source.stop();
  22118. this.startTime = this.context.currentTime;
  22119. this.isPlaying = false;
  22120. return this;
  22121. },
  22122. stop: function () {
  22123. if ( this.hasPlaybackControl === false ) {
  22124. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22125. return;
  22126. }
  22127. this.source.stop();
  22128. this.startTime = 0;
  22129. this.isPlaying = false;
  22130. return this;
  22131. },
  22132. connect: function () {
  22133. if ( this.filters.length > 0 ) {
  22134. this.source.connect( this.filters[ 0 ] );
  22135. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22136. this.filters[ i - 1 ].connect( this.filters[ i ] );
  22137. }
  22138. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  22139. } else {
  22140. this.source.connect( this.getOutput() );
  22141. }
  22142. return this;
  22143. },
  22144. disconnect: function () {
  22145. if ( this.filters.length > 0 ) {
  22146. this.source.disconnect( this.filters[ 0 ] );
  22147. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22148. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  22149. }
  22150. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  22151. } else {
  22152. this.source.disconnect( this.getOutput() );
  22153. }
  22154. return this;
  22155. },
  22156. getFilters: function () {
  22157. return this.filters;
  22158. },
  22159. setFilters: function ( value ) {
  22160. if ( ! value ) value = [];
  22161. if ( this.isPlaying === true ) {
  22162. this.disconnect();
  22163. this.filters = value;
  22164. this.connect();
  22165. } else {
  22166. this.filters = value;
  22167. }
  22168. return this;
  22169. },
  22170. getFilter: function () {
  22171. return this.getFilters()[ 0 ];
  22172. },
  22173. setFilter: function ( filter ) {
  22174. return this.setFilters( filter ? [ filter ] : [] );
  22175. },
  22176. setPlaybackRate: function ( value ) {
  22177. if ( this.hasPlaybackControl === false ) {
  22178. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22179. return;
  22180. }
  22181. this.playbackRate = value;
  22182. if ( this.isPlaying === true ) {
  22183. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  22184. }
  22185. return this;
  22186. },
  22187. getPlaybackRate: function () {
  22188. return this.playbackRate;
  22189. },
  22190. onEnded: function () {
  22191. this.isPlaying = false;
  22192. },
  22193. getLoop: function () {
  22194. if ( this.hasPlaybackControl === false ) {
  22195. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22196. return false;
  22197. }
  22198. return this.loop;
  22199. },
  22200. setLoop: function ( value ) {
  22201. if ( this.hasPlaybackControl === false ) {
  22202. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22203. return;
  22204. }
  22205. this.loop = value;
  22206. if ( this.isPlaying === true ) {
  22207. this.source.loop = this.loop;
  22208. }
  22209. return this;
  22210. },
  22211. getVolume: function () {
  22212. return this.gain.gain.value;
  22213. },
  22214. setVolume: function ( value ) {
  22215. this.gain.gain.value = value;
  22216. return this;
  22217. }
  22218. } );
  22219. /**
  22220. * @author mrdoob / http://mrdoob.com/
  22221. */
  22222. function PositionalAudio( listener ) {
  22223. Audio.call( this, listener );
  22224. this.panner = this.context.createPanner();
  22225. this.panner.connect( this.gain );
  22226. }
  22227. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  22228. constructor: PositionalAudio,
  22229. getOutput: function () {
  22230. return this.panner;
  22231. },
  22232. getRefDistance: function () {
  22233. return this.panner.refDistance;
  22234. },
  22235. setRefDistance: function ( value ) {
  22236. this.panner.refDistance = value;
  22237. },
  22238. getRolloffFactor: function () {
  22239. return this.panner.rolloffFactor;
  22240. },
  22241. setRolloffFactor: function ( value ) {
  22242. this.panner.rolloffFactor = value;
  22243. },
  22244. getDistanceModel: function () {
  22245. return this.panner.distanceModel;
  22246. },
  22247. setDistanceModel: function ( value ) {
  22248. this.panner.distanceModel = value;
  22249. },
  22250. getMaxDistance: function () {
  22251. return this.panner.maxDistance;
  22252. },
  22253. setMaxDistance: function ( value ) {
  22254. this.panner.maxDistance = value;
  22255. },
  22256. updateMatrixWorld: ( function () {
  22257. var position = new Vector3();
  22258. return function updateMatrixWorld( force ) {
  22259. Object3D.prototype.updateMatrixWorld.call( this, force );
  22260. position.setFromMatrixPosition( this.matrixWorld );
  22261. this.panner.setPosition( position.x, position.y, position.z );
  22262. };
  22263. } )()
  22264. } );
  22265. /**
  22266. * @author mrdoob / http://mrdoob.com/
  22267. */
  22268. function AudioAnalyser( audio, fftSize ) {
  22269. this.analyser = audio.context.createAnalyser();
  22270. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  22271. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  22272. audio.getOutput().connect( this.analyser );
  22273. }
  22274. Object.assign( AudioAnalyser.prototype, {
  22275. getFrequencyData: function () {
  22276. this.analyser.getByteFrequencyData( this.data );
  22277. return this.data;
  22278. },
  22279. getAverageFrequency: function () {
  22280. var value = 0, data = this.getFrequencyData();
  22281. for ( var i = 0; i < data.length; i ++ ) {
  22282. value += data[ i ];
  22283. }
  22284. return value / data.length;
  22285. }
  22286. } );
  22287. /**
  22288. *
  22289. * Buffered scene graph property that allows weighted accumulation.
  22290. *
  22291. *
  22292. * @author Ben Houston / http://clara.io/
  22293. * @author David Sarno / http://lighthaus.us/
  22294. * @author tschw
  22295. */
  22296. function PropertyMixer( binding, typeName, valueSize ) {
  22297. this.binding = binding;
  22298. this.valueSize = valueSize;
  22299. var bufferType = Float64Array,
  22300. mixFunction;
  22301. switch ( typeName ) {
  22302. case 'quaternion':
  22303. mixFunction = this._slerp;
  22304. break;
  22305. case 'string':
  22306. case 'bool':
  22307. bufferType = Array;
  22308. mixFunction = this._select;
  22309. break;
  22310. default:
  22311. mixFunction = this._lerp;
  22312. }
  22313. this.buffer = new bufferType( valueSize * 4 );
  22314. // layout: [ incoming | accu0 | accu1 | orig ]
  22315. //
  22316. // interpolators can use .buffer as their .result
  22317. // the data then goes to 'incoming'
  22318. //
  22319. // 'accu0' and 'accu1' are used frame-interleaved for
  22320. // the cumulative result and are compared to detect
  22321. // changes
  22322. //
  22323. // 'orig' stores the original state of the property
  22324. this._mixBufferRegion = mixFunction;
  22325. this.cumulativeWeight = 0;
  22326. this.useCount = 0;
  22327. this.referenceCount = 0;
  22328. }
  22329. Object.assign( PropertyMixer.prototype, {
  22330. // accumulate data in the 'incoming' region into 'accu<i>'
  22331. accumulate: function ( accuIndex, weight ) {
  22332. // note: happily accumulating nothing when weight = 0, the caller knows
  22333. // the weight and shouldn't have made the call in the first place
  22334. var buffer = this.buffer,
  22335. stride = this.valueSize,
  22336. offset = accuIndex * stride + stride,
  22337. currentWeight = this.cumulativeWeight;
  22338. if ( currentWeight === 0 ) {
  22339. // accuN := incoming * weight
  22340. for ( var i = 0; i !== stride; ++ i ) {
  22341. buffer[ offset + i ] = buffer[ i ];
  22342. }
  22343. currentWeight = weight;
  22344. } else {
  22345. // accuN := accuN + incoming * weight
  22346. currentWeight += weight;
  22347. var mix = weight / currentWeight;
  22348. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22349. }
  22350. this.cumulativeWeight = currentWeight;
  22351. },
  22352. // apply the state of 'accu<i>' to the binding when accus differ
  22353. apply: function ( accuIndex ) {
  22354. var stride = this.valueSize,
  22355. buffer = this.buffer,
  22356. offset = accuIndex * stride + stride,
  22357. weight = this.cumulativeWeight,
  22358. binding = this.binding;
  22359. this.cumulativeWeight = 0;
  22360. if ( weight < 1 ) {
  22361. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22362. var originalValueOffset = stride * 3;
  22363. this._mixBufferRegion(
  22364. buffer, offset, originalValueOffset, 1 - weight, stride );
  22365. }
  22366. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  22367. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22368. // value has changed -> update scene graph
  22369. binding.setValue( buffer, offset );
  22370. break;
  22371. }
  22372. }
  22373. },
  22374. // remember the state of the bound property and copy it to both accus
  22375. saveOriginalState: function () {
  22376. var binding = this.binding;
  22377. var buffer = this.buffer,
  22378. stride = this.valueSize,
  22379. originalValueOffset = stride * 3;
  22380. binding.getValue( buffer, originalValueOffset );
  22381. // accu[0..1] := orig -- initially detect changes against the original
  22382. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22383. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22384. }
  22385. this.cumulativeWeight = 0;
  22386. },
  22387. // apply the state previously taken via 'saveOriginalState' to the binding
  22388. restoreOriginalState: function () {
  22389. var originalValueOffset = this.valueSize * 3;
  22390. this.binding.setValue( this.buffer, originalValueOffset );
  22391. },
  22392. // mix functions
  22393. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22394. if ( t >= 0.5 ) {
  22395. for ( var i = 0; i !== stride; ++ i ) {
  22396. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22397. }
  22398. }
  22399. },
  22400. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22401. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22402. },
  22403. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22404. var s = 1 - t;
  22405. for ( var i = 0; i !== stride; ++ i ) {
  22406. var j = dstOffset + i;
  22407. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22408. }
  22409. }
  22410. } );
  22411. /**
  22412. *
  22413. * A reference to a real property in the scene graph.
  22414. *
  22415. *
  22416. * @author Ben Houston / http://clara.io/
  22417. * @author David Sarno / http://lighthaus.us/
  22418. * @author tschw
  22419. */
  22420. function Composite( targetGroup, path, optionalParsedPath ) {
  22421. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22422. this._targetGroup = targetGroup;
  22423. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22424. }
  22425. Object.assign( Composite.prototype, {
  22426. getValue: function ( array, offset ) {
  22427. this.bind(); // bind all binding
  22428. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22429. binding = this._bindings[ firstValidIndex ];
  22430. // and only call .getValue on the first
  22431. if ( binding !== undefined ) binding.getValue( array, offset );
  22432. },
  22433. setValue: function ( array, offset ) {
  22434. var bindings = this._bindings;
  22435. for ( var i = this._targetGroup.nCachedObjects_,
  22436. n = bindings.length; i !== n; ++ i ) {
  22437. bindings[ i ].setValue( array, offset );
  22438. }
  22439. },
  22440. bind: function () {
  22441. var bindings = this._bindings;
  22442. for ( var i = this._targetGroup.nCachedObjects_,
  22443. n = bindings.length; i !== n; ++ i ) {
  22444. bindings[ i ].bind();
  22445. }
  22446. },
  22447. unbind: function () {
  22448. var bindings = this._bindings;
  22449. for ( var i = this._targetGroup.nCachedObjects_,
  22450. n = bindings.length; i !== n; ++ i ) {
  22451. bindings[ i ].unbind();
  22452. }
  22453. }
  22454. } );
  22455. function PropertyBinding( rootNode, path, parsedPath ) {
  22456. this.path = path;
  22457. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22458. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22459. this.rootNode = rootNode;
  22460. }
  22461. Object.assign( PropertyBinding, {
  22462. Composite: Composite,
  22463. create: function ( root, path, parsedPath ) {
  22464. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22465. return new PropertyBinding( root, path, parsedPath );
  22466. } else {
  22467. return new PropertyBinding.Composite( root, path, parsedPath );
  22468. }
  22469. },
  22470. /**
  22471. * Replaces spaces with underscores and removes unsupported characters from
  22472. * node names, to ensure compatibility with parseTrackName().
  22473. *
  22474. * @param {string} name Node name to be sanitized.
  22475. * @return {string}
  22476. */
  22477. sanitizeNodeName: function ( name ) {
  22478. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  22479. },
  22480. parseTrackName: function () {
  22481. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22482. // be matched to parse the rest of the track name.
  22483. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22484. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22485. var nodeRe = /([\w-\.]+)?/;
  22486. // Object on target node, and accessor. Name may contain only word
  22487. // characters. Accessor may contain any character except closing bracket.
  22488. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22489. // Property and accessor. May contain only word characters. Accessor may
  22490. // contain any non-bracket characters.
  22491. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22492. var trackRe = new RegExp(''
  22493. + '^'
  22494. + directoryRe.source
  22495. + nodeRe.source
  22496. + objectRe.source
  22497. + propertyRe.source
  22498. + '$'
  22499. );
  22500. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22501. return function ( trackName ) {
  22502. var matches = trackRe.exec( trackName );
  22503. if ( ! matches ) {
  22504. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22505. }
  22506. var results = {
  22507. // directoryName: matches[ 1 ], // (tschw) currently unused
  22508. nodeName: matches[ 2 ],
  22509. objectName: matches[ 3 ],
  22510. objectIndex: matches[ 4 ],
  22511. propertyName: matches[ 5 ], // required
  22512. propertyIndex: matches[ 6 ]
  22513. };
  22514. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22515. if ( lastDot !== undefined && lastDot !== -1 ) {
  22516. var objectName = results.nodeName.substring( lastDot + 1 );
  22517. // Object names must be checked against a whitelist. Otherwise, there
  22518. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22519. // 'bar' could be the objectName, or part of a nodeName (which can
  22520. // include '.' characters).
  22521. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22522. results.nodeName = results.nodeName.substring( 0, lastDot );
  22523. results.objectName = objectName;
  22524. }
  22525. }
  22526. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22527. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22528. }
  22529. return results;
  22530. };
  22531. }(),
  22532. findNode: function ( root, nodeName ) {
  22533. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22534. return root;
  22535. }
  22536. // search into skeleton bones.
  22537. if ( root.skeleton ) {
  22538. var searchSkeleton = function ( skeleton ) {
  22539. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22540. var bone = skeleton.bones[ i ];
  22541. if ( bone.name === nodeName ) {
  22542. return bone;
  22543. }
  22544. }
  22545. return null;
  22546. };
  22547. var bone = searchSkeleton( root.skeleton );
  22548. if ( bone ) {
  22549. return bone;
  22550. }
  22551. }
  22552. // search into node subtree.
  22553. if ( root.children ) {
  22554. var searchNodeSubtree = function ( children ) {
  22555. for ( var i = 0; i < children.length; i ++ ) {
  22556. var childNode = children[ i ];
  22557. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22558. return childNode;
  22559. }
  22560. var result = searchNodeSubtree( childNode.children );
  22561. if ( result ) return result;
  22562. }
  22563. return null;
  22564. };
  22565. var subTreeNode = searchNodeSubtree( root.children );
  22566. if ( subTreeNode ) {
  22567. return subTreeNode;
  22568. }
  22569. }
  22570. return null;
  22571. }
  22572. } );
  22573. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22574. // these are used to "bind" a nonexistent property
  22575. _getValue_unavailable: function () {},
  22576. _setValue_unavailable: function () {},
  22577. BindingType: {
  22578. Direct: 0,
  22579. EntireArray: 1,
  22580. ArrayElement: 2,
  22581. HasFromToArray: 3
  22582. },
  22583. Versioning: {
  22584. None: 0,
  22585. NeedsUpdate: 1,
  22586. MatrixWorldNeedsUpdate: 2
  22587. },
  22588. GetterByBindingType: [
  22589. function getValue_direct( buffer, offset ) {
  22590. buffer[ offset ] = this.node[ this.propertyName ];
  22591. },
  22592. function getValue_array( buffer, offset ) {
  22593. var source = this.resolvedProperty;
  22594. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22595. buffer[ offset ++ ] = source[ i ];
  22596. }
  22597. },
  22598. function getValue_arrayElement( buffer, offset ) {
  22599. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22600. },
  22601. function getValue_toArray( buffer, offset ) {
  22602. this.resolvedProperty.toArray( buffer, offset );
  22603. }
  22604. ],
  22605. SetterByBindingTypeAndVersioning: [
  22606. [
  22607. // Direct
  22608. function setValue_direct( buffer, offset ) {
  22609. this.node[ this.propertyName ] = buffer[ offset ];
  22610. },
  22611. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22612. this.node[ this.propertyName ] = buffer[ offset ];
  22613. this.targetObject.needsUpdate = true;
  22614. },
  22615. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22616. this.node[ this.propertyName ] = buffer[ offset ];
  22617. this.targetObject.matrixWorldNeedsUpdate = true;
  22618. }
  22619. ], [
  22620. // EntireArray
  22621. function setValue_array( buffer, offset ) {
  22622. var dest = this.resolvedProperty;
  22623. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22624. dest[ i ] = buffer[ offset ++ ];
  22625. }
  22626. },
  22627. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22628. var dest = this.resolvedProperty;
  22629. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22630. dest[ i ] = buffer[ offset ++ ];
  22631. }
  22632. this.targetObject.needsUpdate = true;
  22633. },
  22634. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22635. var dest = this.resolvedProperty;
  22636. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22637. dest[ i ] = buffer[ offset ++ ];
  22638. }
  22639. this.targetObject.matrixWorldNeedsUpdate = true;
  22640. }
  22641. ], [
  22642. // ArrayElement
  22643. function setValue_arrayElement( buffer, offset ) {
  22644. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22645. },
  22646. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22647. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22648. this.targetObject.needsUpdate = true;
  22649. },
  22650. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22651. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22652. this.targetObject.matrixWorldNeedsUpdate = true;
  22653. }
  22654. ], [
  22655. // HasToFromArray
  22656. function setValue_fromArray( buffer, offset ) {
  22657. this.resolvedProperty.fromArray( buffer, offset );
  22658. },
  22659. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22660. this.resolvedProperty.fromArray( buffer, offset );
  22661. this.targetObject.needsUpdate = true;
  22662. },
  22663. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22664. this.resolvedProperty.fromArray( buffer, offset );
  22665. this.targetObject.matrixWorldNeedsUpdate = true;
  22666. }
  22667. ]
  22668. ],
  22669. getValue: function getValue_unbound( targetArray, offset ) {
  22670. this.bind();
  22671. this.getValue( targetArray, offset );
  22672. // Note: This class uses a State pattern on a per-method basis:
  22673. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22674. // prototype version of these methods with one that represents
  22675. // the bound state. When the property is not found, the methods
  22676. // become no-ops.
  22677. },
  22678. setValue: function getValue_unbound( sourceArray, offset ) {
  22679. this.bind();
  22680. this.setValue( sourceArray, offset );
  22681. },
  22682. // create getter / setter pair for a property in the scene graph
  22683. bind: function () {
  22684. var targetObject = this.node,
  22685. parsedPath = this.parsedPath,
  22686. objectName = parsedPath.objectName,
  22687. propertyName = parsedPath.propertyName,
  22688. propertyIndex = parsedPath.propertyIndex;
  22689. if ( ! targetObject ) {
  22690. targetObject = PropertyBinding.findNode(
  22691. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22692. this.node = targetObject;
  22693. }
  22694. // set fail state so we can just 'return' on error
  22695. this.getValue = this._getValue_unavailable;
  22696. this.setValue = this._setValue_unavailable;
  22697. // ensure there is a value node
  22698. if ( ! targetObject ) {
  22699. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22700. return;
  22701. }
  22702. if ( objectName ) {
  22703. var objectIndex = parsedPath.objectIndex;
  22704. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22705. switch ( objectName ) {
  22706. case 'materials':
  22707. if ( ! targetObject.material ) {
  22708. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22709. return;
  22710. }
  22711. if ( ! targetObject.material.materials ) {
  22712. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22713. return;
  22714. }
  22715. targetObject = targetObject.material.materials;
  22716. break;
  22717. case 'bones':
  22718. if ( ! targetObject.skeleton ) {
  22719. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22720. return;
  22721. }
  22722. // potential future optimization: skip this if propertyIndex is already an integer
  22723. // and convert the integer string to a true integer.
  22724. targetObject = targetObject.skeleton.bones;
  22725. // support resolving morphTarget names into indices.
  22726. for ( var i = 0; i < targetObject.length; i ++ ) {
  22727. if ( targetObject[ i ].name === objectIndex ) {
  22728. objectIndex = i;
  22729. break;
  22730. }
  22731. }
  22732. break;
  22733. default:
  22734. if ( targetObject[ objectName ] === undefined ) {
  22735. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22736. return;
  22737. }
  22738. targetObject = targetObject[ objectName ];
  22739. }
  22740. if ( objectIndex !== undefined ) {
  22741. if ( targetObject[ objectIndex ] === undefined ) {
  22742. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22743. return;
  22744. }
  22745. targetObject = targetObject[ objectIndex ];
  22746. }
  22747. }
  22748. // resolve property
  22749. var nodeProperty = targetObject[ propertyName ];
  22750. if ( nodeProperty === undefined ) {
  22751. var nodeName = parsedPath.nodeName;
  22752. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22753. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22754. return;
  22755. }
  22756. // determine versioning scheme
  22757. var versioning = this.Versioning.None;
  22758. if ( targetObject.needsUpdate !== undefined ) { // material
  22759. versioning = this.Versioning.NeedsUpdate;
  22760. this.targetObject = targetObject;
  22761. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22762. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22763. this.targetObject = targetObject;
  22764. }
  22765. // determine how the property gets bound
  22766. var bindingType = this.BindingType.Direct;
  22767. if ( propertyIndex !== undefined ) {
  22768. // access a sub element of the property array (only primitives are supported right now)
  22769. if ( propertyName === "morphTargetInfluences" ) {
  22770. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22771. // support resolving morphTarget names into indices.
  22772. if ( ! targetObject.geometry ) {
  22773. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22774. return;
  22775. }
  22776. if ( targetObject.geometry.isBufferGeometry ) {
  22777. if ( ! targetObject.geometry.morphAttributes ) {
  22778. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22779. return;
  22780. }
  22781. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  22782. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  22783. propertyIndex = i;
  22784. break;
  22785. }
  22786. }
  22787. } else {
  22788. if ( ! targetObject.geometry.morphTargets ) {
  22789. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  22790. return;
  22791. }
  22792. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22793. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22794. propertyIndex = i;
  22795. break;
  22796. }
  22797. }
  22798. }
  22799. }
  22800. bindingType = this.BindingType.ArrayElement;
  22801. this.resolvedProperty = nodeProperty;
  22802. this.propertyIndex = propertyIndex;
  22803. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22804. // must use copy for Object3D.Euler/Quaternion
  22805. bindingType = this.BindingType.HasFromToArray;
  22806. this.resolvedProperty = nodeProperty;
  22807. } else if ( Array.isArray( nodeProperty ) ) {
  22808. bindingType = this.BindingType.EntireArray;
  22809. this.resolvedProperty = nodeProperty;
  22810. } else {
  22811. this.propertyName = propertyName;
  22812. }
  22813. // select getter / setter
  22814. this.getValue = this.GetterByBindingType[ bindingType ];
  22815. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22816. },
  22817. unbind: function () {
  22818. this.node = null;
  22819. // back to the prototype version of getValue / setValue
  22820. // note: avoiding to mutate the shape of 'this' via 'delete'
  22821. this.getValue = this._getValue_unbound;
  22822. this.setValue = this._setValue_unbound;
  22823. }
  22824. } );
  22825. //!\ DECLARE ALIAS AFTER assign prototype !
  22826. Object.assign( PropertyBinding.prototype, {
  22827. // initial state of these methods that calls 'bind'
  22828. _getValue_unbound: PropertyBinding.prototype.getValue,
  22829. _setValue_unbound: PropertyBinding.prototype.setValue,
  22830. } );
  22831. /**
  22832. *
  22833. * A group of objects that receives a shared animation state.
  22834. *
  22835. * Usage:
  22836. *
  22837. * - Add objects you would otherwise pass as 'root' to the
  22838. * constructor or the .clipAction method of AnimationMixer.
  22839. *
  22840. * - Instead pass this object as 'root'.
  22841. *
  22842. * - You can also add and remove objects later when the mixer
  22843. * is running.
  22844. *
  22845. * Note:
  22846. *
  22847. * Objects of this class appear as one object to the mixer,
  22848. * so cache control of the individual objects must be done
  22849. * on the group.
  22850. *
  22851. * Limitation:
  22852. *
  22853. * - The animated properties must be compatible among the
  22854. * all objects in the group.
  22855. *
  22856. * - A single property can either be controlled through a
  22857. * target group or directly, but not both.
  22858. *
  22859. * @author tschw
  22860. */
  22861. function AnimationObjectGroup( var_args ) {
  22862. this.uuid = _Math.generateUUID();
  22863. // cached objects followed by the active ones
  22864. this._objects = Array.prototype.slice.call( arguments );
  22865. this.nCachedObjects_ = 0; // threshold
  22866. // note: read by PropertyBinding.Composite
  22867. var indices = {};
  22868. this._indicesByUUID = indices; // for bookkeeping
  22869. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22870. indices[ arguments[ i ].uuid ] = i;
  22871. }
  22872. this._paths = []; // inside: string
  22873. this._parsedPaths = []; // inside: { we don't care, here }
  22874. this._bindings = []; // inside: Array< PropertyBinding >
  22875. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22876. var scope = this;
  22877. this.stats = {
  22878. objects: {
  22879. get total() { return scope._objects.length; },
  22880. get inUse() { return this.total - scope.nCachedObjects_; }
  22881. },
  22882. get bindingsPerObject() { return scope._bindings.length; }
  22883. };
  22884. }
  22885. Object.assign( AnimationObjectGroup.prototype, {
  22886. isAnimationObjectGroup: true,
  22887. add: function( var_args ) {
  22888. var objects = this._objects,
  22889. nObjects = objects.length,
  22890. nCachedObjects = this.nCachedObjects_,
  22891. indicesByUUID = this._indicesByUUID,
  22892. paths = this._paths,
  22893. parsedPaths = this._parsedPaths,
  22894. bindings = this._bindings,
  22895. nBindings = bindings.length;
  22896. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22897. var object = arguments[ i ],
  22898. uuid = object.uuid,
  22899. index = indicesByUUID[ uuid ],
  22900. knownObject = undefined;
  22901. if ( index === undefined ) {
  22902. // unknown object -> add it to the ACTIVE region
  22903. index = nObjects ++;
  22904. indicesByUUID[ uuid ] = index;
  22905. objects.push( object );
  22906. // accounting is done, now do the same for all bindings
  22907. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22908. bindings[ j ].push(
  22909. new PropertyBinding(
  22910. object, paths[ j ], parsedPaths[ j ] ) );
  22911. }
  22912. } else if ( index < nCachedObjects ) {
  22913. knownObject = objects[ index ];
  22914. // move existing object to the ACTIVE region
  22915. var firstActiveIndex = -- nCachedObjects,
  22916. lastCachedObject = objects[ firstActiveIndex ];
  22917. indicesByUUID[ lastCachedObject.uuid ] = index;
  22918. objects[ index ] = lastCachedObject;
  22919. indicesByUUID[ uuid ] = firstActiveIndex;
  22920. objects[ firstActiveIndex ] = object;
  22921. // accounting is done, now do the same for all bindings
  22922. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22923. var bindingsForPath = bindings[ j ],
  22924. lastCached = bindingsForPath[ firstActiveIndex ],
  22925. binding = bindingsForPath[ index ];
  22926. bindingsForPath[ index ] = lastCached;
  22927. if ( binding === undefined ) {
  22928. // since we do not bother to create new bindings
  22929. // for objects that are cached, the binding may
  22930. // or may not exist
  22931. binding = new PropertyBinding(
  22932. object, paths[ j ], parsedPaths[ j ] );
  22933. }
  22934. bindingsForPath[ firstActiveIndex ] = binding;
  22935. }
  22936. } else if ( objects[ index ] !== knownObject ) {
  22937. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  22938. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  22939. } // else the object is already where we want it to be
  22940. } // for arguments
  22941. this.nCachedObjects_ = nCachedObjects;
  22942. },
  22943. remove: function( var_args ) {
  22944. var objects = this._objects,
  22945. nCachedObjects = this.nCachedObjects_,
  22946. indicesByUUID = this._indicesByUUID,
  22947. bindings = this._bindings,
  22948. nBindings = bindings.length;
  22949. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22950. var object = arguments[ i ],
  22951. uuid = object.uuid,
  22952. index = indicesByUUID[ uuid ];
  22953. if ( index !== undefined && index >= nCachedObjects ) {
  22954. // move existing object into the CACHED region
  22955. var lastCachedIndex = nCachedObjects ++,
  22956. firstActiveObject = objects[ lastCachedIndex ];
  22957. indicesByUUID[ firstActiveObject.uuid ] = index;
  22958. objects[ index ] = firstActiveObject;
  22959. indicesByUUID[ uuid ] = lastCachedIndex;
  22960. objects[ lastCachedIndex ] = object;
  22961. // accounting is done, now do the same for all bindings
  22962. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22963. var bindingsForPath = bindings[ j ],
  22964. firstActive = bindingsForPath[ lastCachedIndex ],
  22965. binding = bindingsForPath[ index ];
  22966. bindingsForPath[ index ] = firstActive;
  22967. bindingsForPath[ lastCachedIndex ] = binding;
  22968. }
  22969. }
  22970. } // for arguments
  22971. this.nCachedObjects_ = nCachedObjects;
  22972. },
  22973. // remove & forget
  22974. uncache: function( var_args ) {
  22975. var objects = this._objects,
  22976. nObjects = objects.length,
  22977. nCachedObjects = this.nCachedObjects_,
  22978. indicesByUUID = this._indicesByUUID,
  22979. bindings = this._bindings,
  22980. nBindings = bindings.length;
  22981. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22982. var object = arguments[ i ],
  22983. uuid = object.uuid,
  22984. index = indicesByUUID[ uuid ];
  22985. if ( index !== undefined ) {
  22986. delete indicesByUUID[ uuid ];
  22987. if ( index < nCachedObjects ) {
  22988. // object is cached, shrink the CACHED region
  22989. var firstActiveIndex = -- nCachedObjects,
  22990. lastCachedObject = objects[ firstActiveIndex ],
  22991. lastIndex = -- nObjects,
  22992. lastObject = objects[ lastIndex ];
  22993. // last cached object takes this object's place
  22994. indicesByUUID[ lastCachedObject.uuid ] = index;
  22995. objects[ index ] = lastCachedObject;
  22996. // last object goes to the activated slot and pop
  22997. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22998. objects[ firstActiveIndex ] = lastObject;
  22999. objects.pop();
  23000. // accounting is done, now do the same for all bindings
  23001. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  23002. var bindingsForPath = bindings[ j ],
  23003. lastCached = bindingsForPath[ firstActiveIndex ],
  23004. last = bindingsForPath[ lastIndex ];
  23005. bindingsForPath[ index ] = lastCached;
  23006. bindingsForPath[ firstActiveIndex ] = last;
  23007. bindingsForPath.pop();
  23008. }
  23009. } else {
  23010. // object is active, just swap with the last and pop
  23011. var lastIndex = -- nObjects,
  23012. lastObject = objects[ lastIndex ];
  23013. indicesByUUID[ lastObject.uuid ] = index;
  23014. objects[ index ] = lastObject;
  23015. objects.pop();
  23016. // accounting is done, now do the same for all bindings
  23017. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  23018. var bindingsForPath = bindings[ j ];
  23019. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  23020. bindingsForPath.pop();
  23021. }
  23022. } // cached or active
  23023. } // if object is known
  23024. } // for arguments
  23025. this.nCachedObjects_ = nCachedObjects;
  23026. },
  23027. // Internal interface used by befriended PropertyBinding.Composite:
  23028. subscribe_: function ( path, parsedPath ) {
  23029. // returns an array of bindings for the given path that is changed
  23030. // according to the contained objects in the group
  23031. var indicesByPath = this._bindingsIndicesByPath,
  23032. index = indicesByPath[ path ],
  23033. bindings = this._bindings;
  23034. if ( index !== undefined ) return bindings[ index ];
  23035. var paths = this._paths,
  23036. parsedPaths = this._parsedPaths,
  23037. objects = this._objects,
  23038. nObjects = objects.length,
  23039. nCachedObjects = this.nCachedObjects_,
  23040. bindingsForPath = new Array( nObjects );
  23041. index = bindings.length;
  23042. indicesByPath[ path ] = index;
  23043. paths.push( path );
  23044. parsedPaths.push( parsedPath );
  23045. bindings.push( bindingsForPath );
  23046. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  23047. var object = objects[ i ];
  23048. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  23049. }
  23050. return bindingsForPath;
  23051. },
  23052. unsubscribe_: function ( path ) {
  23053. // tells the group to forget about a property path and no longer
  23054. // update the array previously obtained with 'subscribe_'
  23055. var indicesByPath = this._bindingsIndicesByPath,
  23056. index = indicesByPath[ path ];
  23057. if ( index !== undefined ) {
  23058. var paths = this._paths,
  23059. parsedPaths = this._parsedPaths,
  23060. bindings = this._bindings,
  23061. lastBindingsIndex = bindings.length - 1,
  23062. lastBindings = bindings[ lastBindingsIndex ],
  23063. lastBindingsPath = path[ lastBindingsIndex ];
  23064. indicesByPath[ lastBindingsPath ] = index;
  23065. bindings[ index ] = lastBindings;
  23066. bindings.pop();
  23067. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  23068. parsedPaths.pop();
  23069. paths[ index ] = paths[ lastBindingsIndex ];
  23070. paths.pop();
  23071. }
  23072. }
  23073. } );
  23074. /**
  23075. *
  23076. * Action provided by AnimationMixer for scheduling clip playback on specific
  23077. * objects.
  23078. *
  23079. * @author Ben Houston / http://clara.io/
  23080. * @author David Sarno / http://lighthaus.us/
  23081. * @author tschw
  23082. *
  23083. */
  23084. function AnimationAction( mixer, clip, localRoot ) {
  23085. this._mixer = mixer;
  23086. this._clip = clip;
  23087. this._localRoot = localRoot || null;
  23088. var tracks = clip.tracks,
  23089. nTracks = tracks.length,
  23090. interpolants = new Array( nTracks );
  23091. var interpolantSettings = {
  23092. endingStart: ZeroCurvatureEnding,
  23093. endingEnd: ZeroCurvatureEnding
  23094. };
  23095. for ( var i = 0; i !== nTracks; ++ i ) {
  23096. var interpolant = tracks[ i ].createInterpolant( null );
  23097. interpolants[ i ] = interpolant;
  23098. interpolant.settings = interpolantSettings;
  23099. }
  23100. this._interpolantSettings = interpolantSettings;
  23101. this._interpolants = interpolants; // bound by the mixer
  23102. // inside: PropertyMixer (managed by the mixer)
  23103. this._propertyBindings = new Array( nTracks );
  23104. this._cacheIndex = null; // for the memory manager
  23105. this._byClipCacheIndex = null; // for the memory manager
  23106. this._timeScaleInterpolant = null;
  23107. this._weightInterpolant = null;
  23108. this.loop = LoopRepeat;
  23109. this._loopCount = -1;
  23110. // global mixer time when the action is to be started
  23111. // it's set back to 'null' upon start of the action
  23112. this._startTime = null;
  23113. // scaled local time of the action
  23114. // gets clamped or wrapped to 0..clip.duration according to loop
  23115. this.time = 0;
  23116. this.timeScale = 1;
  23117. this._effectiveTimeScale = 1;
  23118. this.weight = 1;
  23119. this._effectiveWeight = 1;
  23120. this.repetitions = Infinity; // no. of repetitions when looping
  23121. this.paused = false; // true -> zero effective time scale
  23122. this.enabled = true; // false -> zero effective weight
  23123. this.clampWhenFinished = false; // keep feeding the last frame?
  23124. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  23125. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  23126. }
  23127. Object.assign( AnimationAction.prototype, {
  23128. // State & Scheduling
  23129. play: function() {
  23130. this._mixer._activateAction( this );
  23131. return this;
  23132. },
  23133. stop: function() {
  23134. this._mixer._deactivateAction( this );
  23135. return this.reset();
  23136. },
  23137. reset: function() {
  23138. this.paused = false;
  23139. this.enabled = true;
  23140. this.time = 0; // restart clip
  23141. this._loopCount = -1; // forget previous loops
  23142. this._startTime = null; // forget scheduling
  23143. return this.stopFading().stopWarping();
  23144. },
  23145. isRunning: function() {
  23146. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  23147. this._startTime === null && this._mixer._isActiveAction( this );
  23148. },
  23149. // return true when play has been called
  23150. isScheduled: function() {
  23151. return this._mixer._isActiveAction( this );
  23152. },
  23153. startAt: function( time ) {
  23154. this._startTime = time;
  23155. return this;
  23156. },
  23157. setLoop: function( mode, repetitions ) {
  23158. this.loop = mode;
  23159. this.repetitions = repetitions;
  23160. return this;
  23161. },
  23162. // Weight
  23163. // set the weight stopping any scheduled fading
  23164. // although .enabled = false yields an effective weight of zero, this
  23165. // method does *not* change .enabled, because it would be confusing
  23166. setEffectiveWeight: function( weight ) {
  23167. this.weight = weight;
  23168. // note: same logic as when updated at runtime
  23169. this._effectiveWeight = this.enabled ? weight : 0;
  23170. return this.stopFading();
  23171. },
  23172. // return the weight considering fading and .enabled
  23173. getEffectiveWeight: function() {
  23174. return this._effectiveWeight;
  23175. },
  23176. fadeIn: function( duration ) {
  23177. return this._scheduleFading( duration, 0, 1 );
  23178. },
  23179. fadeOut: function( duration ) {
  23180. return this._scheduleFading( duration, 1, 0 );
  23181. },
  23182. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  23183. fadeOutAction.fadeOut( duration );
  23184. this.fadeIn( duration );
  23185. if( warp ) {
  23186. var fadeInDuration = this._clip.duration,
  23187. fadeOutDuration = fadeOutAction._clip.duration,
  23188. startEndRatio = fadeOutDuration / fadeInDuration,
  23189. endStartRatio = fadeInDuration / fadeOutDuration;
  23190. fadeOutAction.warp( 1.0, startEndRatio, duration );
  23191. this.warp( endStartRatio, 1.0, duration );
  23192. }
  23193. return this;
  23194. },
  23195. crossFadeTo: function( fadeInAction, duration, warp ) {
  23196. return fadeInAction.crossFadeFrom( this, duration, warp );
  23197. },
  23198. stopFading: function() {
  23199. var weightInterpolant = this._weightInterpolant;
  23200. if ( weightInterpolant !== null ) {
  23201. this._weightInterpolant = null;
  23202. this._mixer._takeBackControlInterpolant( weightInterpolant );
  23203. }
  23204. return this;
  23205. },
  23206. // Time Scale Control
  23207. // set the time scale stopping any scheduled warping
  23208. // although .paused = true yields an effective time scale of zero, this
  23209. // method does *not* change .paused, because it would be confusing
  23210. setEffectiveTimeScale: function( timeScale ) {
  23211. this.timeScale = timeScale;
  23212. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  23213. return this.stopWarping();
  23214. },
  23215. // return the time scale considering warping and .paused
  23216. getEffectiveTimeScale: function() {
  23217. return this._effectiveTimeScale;
  23218. },
  23219. setDuration: function( duration ) {
  23220. this.timeScale = this._clip.duration / duration;
  23221. return this.stopWarping();
  23222. },
  23223. syncWith: function( action ) {
  23224. this.time = action.time;
  23225. this.timeScale = action.timeScale;
  23226. return this.stopWarping();
  23227. },
  23228. halt: function( duration ) {
  23229. return this.warp( this._effectiveTimeScale, 0, duration );
  23230. },
  23231. warp: function( startTimeScale, endTimeScale, duration ) {
  23232. var mixer = this._mixer, now = mixer.time,
  23233. interpolant = this._timeScaleInterpolant,
  23234. timeScale = this.timeScale;
  23235. if ( interpolant === null ) {
  23236. interpolant = mixer._lendControlInterpolant();
  23237. this._timeScaleInterpolant = interpolant;
  23238. }
  23239. var times = interpolant.parameterPositions,
  23240. values = interpolant.sampleValues;
  23241. times[ 0 ] = now;
  23242. times[ 1 ] = now + duration;
  23243. values[ 0 ] = startTimeScale / timeScale;
  23244. values[ 1 ] = endTimeScale / timeScale;
  23245. return this;
  23246. },
  23247. stopWarping: function() {
  23248. var timeScaleInterpolant = this._timeScaleInterpolant;
  23249. if ( timeScaleInterpolant !== null ) {
  23250. this._timeScaleInterpolant = null;
  23251. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  23252. }
  23253. return this;
  23254. },
  23255. // Object Accessors
  23256. getMixer: function() {
  23257. return this._mixer;
  23258. },
  23259. getClip: function() {
  23260. return this._clip;
  23261. },
  23262. getRoot: function() {
  23263. return this._localRoot || this._mixer._root;
  23264. },
  23265. // Interna
  23266. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  23267. // called by the mixer
  23268. if ( ! this.enabled ) {
  23269. // call ._updateWeight() to update ._effectiveWeight
  23270. this._updateWeight( time );
  23271. return;
  23272. }
  23273. var startTime = this._startTime;
  23274. if ( startTime !== null ) {
  23275. // check for scheduled start of action
  23276. var timeRunning = ( time - startTime ) * timeDirection;
  23277. if ( timeRunning < 0 || timeDirection === 0 ) {
  23278. return; // yet to come / don't decide when delta = 0
  23279. }
  23280. // start
  23281. this._startTime = null; // unschedule
  23282. deltaTime = timeDirection * timeRunning;
  23283. }
  23284. // apply time scale and advance time
  23285. deltaTime *= this._updateTimeScale( time );
  23286. var clipTime = this._updateTime( deltaTime );
  23287. // note: _updateTime may disable the action resulting in
  23288. // an effective weight of 0
  23289. var weight = this._updateWeight( time );
  23290. if ( weight > 0 ) {
  23291. var interpolants = this._interpolants;
  23292. var propertyMixers = this._propertyBindings;
  23293. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  23294. interpolants[ j ].evaluate( clipTime );
  23295. propertyMixers[ j ].accumulate( accuIndex, weight );
  23296. }
  23297. }
  23298. },
  23299. _updateWeight: function( time ) {
  23300. var weight = 0;
  23301. if ( this.enabled ) {
  23302. weight = this.weight;
  23303. var interpolant = this._weightInterpolant;
  23304. if ( interpolant !== null ) {
  23305. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23306. weight *= interpolantValue;
  23307. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23308. this.stopFading();
  23309. if ( interpolantValue === 0 ) {
  23310. // faded out, disable
  23311. this.enabled = false;
  23312. }
  23313. }
  23314. }
  23315. }
  23316. this._effectiveWeight = weight;
  23317. return weight;
  23318. },
  23319. _updateTimeScale: function( time ) {
  23320. var timeScale = 0;
  23321. if ( ! this.paused ) {
  23322. timeScale = this.timeScale;
  23323. var interpolant = this._timeScaleInterpolant;
  23324. if ( interpolant !== null ) {
  23325. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23326. timeScale *= interpolantValue;
  23327. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23328. this.stopWarping();
  23329. if ( timeScale === 0 ) {
  23330. // motion has halted, pause
  23331. this.paused = true;
  23332. } else {
  23333. // warp done - apply final time scale
  23334. this.timeScale = timeScale;
  23335. }
  23336. }
  23337. }
  23338. }
  23339. this._effectiveTimeScale = timeScale;
  23340. return timeScale;
  23341. },
  23342. _updateTime: function( deltaTime ) {
  23343. var time = this.time + deltaTime;
  23344. if ( deltaTime === 0 ) return time;
  23345. var duration = this._clip.duration,
  23346. loop = this.loop,
  23347. loopCount = this._loopCount;
  23348. if ( loop === LoopOnce ) {
  23349. if ( loopCount === -1 ) {
  23350. // just started
  23351. this._loopCount = 0;
  23352. this._setEndings( true, true, false );
  23353. }
  23354. handle_stop: {
  23355. if ( time >= duration ) {
  23356. time = duration;
  23357. } else if ( time < 0 ) {
  23358. time = 0;
  23359. } else break handle_stop;
  23360. if ( this.clampWhenFinished ) this.paused = true;
  23361. else this.enabled = false;
  23362. this._mixer.dispatchEvent( {
  23363. type: 'finished', action: this,
  23364. direction: deltaTime < 0 ? -1 : 1
  23365. } );
  23366. }
  23367. } else { // repetitive Repeat or PingPong
  23368. var pingPong = ( loop === LoopPingPong );
  23369. if ( loopCount === -1 ) {
  23370. // just started
  23371. if ( deltaTime >= 0 ) {
  23372. loopCount = 0;
  23373. this._setEndings(
  23374. true, this.repetitions === 0, pingPong );
  23375. } else {
  23376. // when looping in reverse direction, the initial
  23377. // transition through zero counts as a repetition,
  23378. // so leave loopCount at -1
  23379. this._setEndings(
  23380. this.repetitions === 0, true, pingPong );
  23381. }
  23382. }
  23383. if ( time >= duration || time < 0 ) {
  23384. // wrap around
  23385. var loopDelta = Math.floor( time / duration ); // signed
  23386. time -= duration * loopDelta;
  23387. loopCount += Math.abs( loopDelta );
  23388. var pending = this.repetitions - loopCount;
  23389. if ( pending < 0 ) {
  23390. // have to stop (switch state, clamp time, fire event)
  23391. if ( this.clampWhenFinished ) this.paused = true;
  23392. else this.enabled = false;
  23393. time = deltaTime > 0 ? duration : 0;
  23394. this._mixer.dispatchEvent( {
  23395. type: 'finished', action: this,
  23396. direction: deltaTime > 0 ? 1 : -1
  23397. } );
  23398. } else {
  23399. // keep running
  23400. if ( pending === 0 ) {
  23401. // entering the last round
  23402. var atStart = deltaTime < 0;
  23403. this._setEndings( atStart, ! atStart, pingPong );
  23404. } else {
  23405. this._setEndings( false, false, pingPong );
  23406. }
  23407. this._loopCount = loopCount;
  23408. this._mixer.dispatchEvent( {
  23409. type: 'loop', action: this, loopDelta: loopDelta
  23410. } );
  23411. }
  23412. }
  23413. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23414. // invert time for the "pong round"
  23415. this.time = time;
  23416. return duration - time;
  23417. }
  23418. }
  23419. this.time = time;
  23420. return time;
  23421. },
  23422. _setEndings: function( atStart, atEnd, pingPong ) {
  23423. var settings = this._interpolantSettings;
  23424. if ( pingPong ) {
  23425. settings.endingStart = ZeroSlopeEnding;
  23426. settings.endingEnd = ZeroSlopeEnding;
  23427. } else {
  23428. // assuming for LoopOnce atStart == atEnd == true
  23429. if ( atStart ) {
  23430. settings.endingStart = this.zeroSlopeAtStart ?
  23431. ZeroSlopeEnding : ZeroCurvatureEnding;
  23432. } else {
  23433. settings.endingStart = WrapAroundEnding;
  23434. }
  23435. if ( atEnd ) {
  23436. settings.endingEnd = this.zeroSlopeAtEnd ?
  23437. ZeroSlopeEnding : ZeroCurvatureEnding;
  23438. } else {
  23439. settings.endingEnd = WrapAroundEnding;
  23440. }
  23441. }
  23442. },
  23443. _scheduleFading: function( duration, weightNow, weightThen ) {
  23444. var mixer = this._mixer, now = mixer.time,
  23445. interpolant = this._weightInterpolant;
  23446. if ( interpolant === null ) {
  23447. interpolant = mixer._lendControlInterpolant();
  23448. this._weightInterpolant = interpolant;
  23449. }
  23450. var times = interpolant.parameterPositions,
  23451. values = interpolant.sampleValues;
  23452. times[ 0 ] = now; values[ 0 ] = weightNow;
  23453. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23454. return this;
  23455. }
  23456. } );
  23457. /**
  23458. *
  23459. * Player for AnimationClips.
  23460. *
  23461. *
  23462. * @author Ben Houston / http://clara.io/
  23463. * @author David Sarno / http://lighthaus.us/
  23464. * @author tschw
  23465. */
  23466. function AnimationMixer( root ) {
  23467. this._root = root;
  23468. this._initMemoryManager();
  23469. this._accuIndex = 0;
  23470. this.time = 0;
  23471. this.timeScale = 1.0;
  23472. }
  23473. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23474. _bindAction: function ( action, prototypeAction ) {
  23475. var root = action._localRoot || this._root,
  23476. tracks = action._clip.tracks,
  23477. nTracks = tracks.length,
  23478. bindings = action._propertyBindings,
  23479. interpolants = action._interpolants,
  23480. rootUuid = root.uuid,
  23481. bindingsByRoot = this._bindingsByRootAndName,
  23482. bindingsByName = bindingsByRoot[ rootUuid ];
  23483. if ( bindingsByName === undefined ) {
  23484. bindingsByName = {};
  23485. bindingsByRoot[ rootUuid ] = bindingsByName;
  23486. }
  23487. for ( var i = 0; i !== nTracks; ++ i ) {
  23488. var track = tracks[ i ],
  23489. trackName = track.name,
  23490. binding = bindingsByName[ trackName ];
  23491. if ( binding !== undefined ) {
  23492. bindings[ i ] = binding;
  23493. } else {
  23494. binding = bindings[ i ];
  23495. if ( binding !== undefined ) {
  23496. // existing binding, make sure the cache knows
  23497. if ( binding._cacheIndex === null ) {
  23498. ++ binding.referenceCount;
  23499. this._addInactiveBinding( binding, rootUuid, trackName );
  23500. }
  23501. continue;
  23502. }
  23503. var path = prototypeAction && prototypeAction.
  23504. _propertyBindings[ i ].binding.parsedPath;
  23505. binding = new PropertyMixer(
  23506. PropertyBinding.create( root, trackName, path ),
  23507. track.ValueTypeName, track.getValueSize() );
  23508. ++ binding.referenceCount;
  23509. this._addInactiveBinding( binding, rootUuid, trackName );
  23510. bindings[ i ] = binding;
  23511. }
  23512. interpolants[ i ].resultBuffer = binding.buffer;
  23513. }
  23514. },
  23515. _activateAction: function ( action ) {
  23516. if ( ! this._isActiveAction( action ) ) {
  23517. if ( action._cacheIndex === null ) {
  23518. // this action has been forgotten by the cache, but the user
  23519. // appears to be still using it -> rebind
  23520. var rootUuid = ( action._localRoot || this._root ).uuid,
  23521. clipUuid = action._clip.uuid,
  23522. actionsForClip = this._actionsByClip[ clipUuid ];
  23523. this._bindAction( action,
  23524. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23525. this._addInactiveAction( action, clipUuid, rootUuid );
  23526. }
  23527. var bindings = action._propertyBindings;
  23528. // increment reference counts / sort out state
  23529. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23530. var binding = bindings[ i ];
  23531. if ( binding.useCount ++ === 0 ) {
  23532. this._lendBinding( binding );
  23533. binding.saveOriginalState();
  23534. }
  23535. }
  23536. this._lendAction( action );
  23537. }
  23538. },
  23539. _deactivateAction: function ( action ) {
  23540. if ( this._isActiveAction( action ) ) {
  23541. var bindings = action._propertyBindings;
  23542. // decrement reference counts / sort out state
  23543. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23544. var binding = bindings[ i ];
  23545. if ( -- binding.useCount === 0 ) {
  23546. binding.restoreOriginalState();
  23547. this._takeBackBinding( binding );
  23548. }
  23549. }
  23550. this._takeBackAction( action );
  23551. }
  23552. },
  23553. // Memory manager
  23554. _initMemoryManager: function () {
  23555. this._actions = []; // 'nActiveActions' followed by inactive ones
  23556. this._nActiveActions = 0;
  23557. this._actionsByClip = {};
  23558. // inside:
  23559. // {
  23560. // knownActions: Array< AnimationAction > - used as prototypes
  23561. // actionByRoot: AnimationAction - lookup
  23562. // }
  23563. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23564. this._nActiveBindings = 0;
  23565. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23566. this._controlInterpolants = []; // same game as above
  23567. this._nActiveControlInterpolants = 0;
  23568. var scope = this;
  23569. this.stats = {
  23570. actions: {
  23571. get total() { return scope._actions.length; },
  23572. get inUse() { return scope._nActiveActions; }
  23573. },
  23574. bindings: {
  23575. get total() { return scope._bindings.length; },
  23576. get inUse() { return scope._nActiveBindings; }
  23577. },
  23578. controlInterpolants: {
  23579. get total() { return scope._controlInterpolants.length; },
  23580. get inUse() { return scope._nActiveControlInterpolants; }
  23581. }
  23582. };
  23583. },
  23584. // Memory management for AnimationAction objects
  23585. _isActiveAction: function ( action ) {
  23586. var index = action._cacheIndex;
  23587. return index !== null && index < this._nActiveActions;
  23588. },
  23589. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23590. var actions = this._actions,
  23591. actionsByClip = this._actionsByClip,
  23592. actionsForClip = actionsByClip[ clipUuid ];
  23593. if ( actionsForClip === undefined ) {
  23594. actionsForClip = {
  23595. knownActions: [ action ],
  23596. actionByRoot: {}
  23597. };
  23598. action._byClipCacheIndex = 0;
  23599. actionsByClip[ clipUuid ] = actionsForClip;
  23600. } else {
  23601. var knownActions = actionsForClip.knownActions;
  23602. action._byClipCacheIndex = knownActions.length;
  23603. knownActions.push( action );
  23604. }
  23605. action._cacheIndex = actions.length;
  23606. actions.push( action );
  23607. actionsForClip.actionByRoot[ rootUuid ] = action;
  23608. },
  23609. _removeInactiveAction: function ( action ) {
  23610. var actions = this._actions,
  23611. lastInactiveAction = actions[ actions.length - 1 ],
  23612. cacheIndex = action._cacheIndex;
  23613. lastInactiveAction._cacheIndex = cacheIndex;
  23614. actions[ cacheIndex ] = lastInactiveAction;
  23615. actions.pop();
  23616. action._cacheIndex = null;
  23617. var clipUuid = action._clip.uuid,
  23618. actionsByClip = this._actionsByClip,
  23619. actionsForClip = actionsByClip[ clipUuid ],
  23620. knownActionsForClip = actionsForClip.knownActions,
  23621. lastKnownAction =
  23622. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23623. byClipCacheIndex = action._byClipCacheIndex;
  23624. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23625. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23626. knownActionsForClip.pop();
  23627. action._byClipCacheIndex = null;
  23628. var actionByRoot = actionsForClip.actionByRoot,
  23629. rootUuid = ( action._localRoot || this._root ).uuid;
  23630. delete actionByRoot[ rootUuid ];
  23631. if ( knownActionsForClip.length === 0 ) {
  23632. delete actionsByClip[ clipUuid ];
  23633. }
  23634. this._removeInactiveBindingsForAction( action );
  23635. },
  23636. _removeInactiveBindingsForAction: function ( action ) {
  23637. var bindings = action._propertyBindings;
  23638. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23639. var binding = bindings[ i ];
  23640. if ( -- binding.referenceCount === 0 ) {
  23641. this._removeInactiveBinding( binding );
  23642. }
  23643. }
  23644. },
  23645. _lendAction: function ( action ) {
  23646. // [ active actions | inactive actions ]
  23647. // [ active actions >| inactive actions ]
  23648. // s a
  23649. // <-swap->
  23650. // a s
  23651. var actions = this._actions,
  23652. prevIndex = action._cacheIndex,
  23653. lastActiveIndex = this._nActiveActions ++,
  23654. firstInactiveAction = actions[ lastActiveIndex ];
  23655. action._cacheIndex = lastActiveIndex;
  23656. actions[ lastActiveIndex ] = action;
  23657. firstInactiveAction._cacheIndex = prevIndex;
  23658. actions[ prevIndex ] = firstInactiveAction;
  23659. },
  23660. _takeBackAction: function ( action ) {
  23661. // [ active actions | inactive actions ]
  23662. // [ active actions |< inactive actions ]
  23663. // a s
  23664. // <-swap->
  23665. // s a
  23666. var actions = this._actions,
  23667. prevIndex = action._cacheIndex,
  23668. firstInactiveIndex = -- this._nActiveActions,
  23669. lastActiveAction = actions[ firstInactiveIndex ];
  23670. action._cacheIndex = firstInactiveIndex;
  23671. actions[ firstInactiveIndex ] = action;
  23672. lastActiveAction._cacheIndex = prevIndex;
  23673. actions[ prevIndex ] = lastActiveAction;
  23674. },
  23675. // Memory management for PropertyMixer objects
  23676. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23677. var bindingsByRoot = this._bindingsByRootAndName,
  23678. bindingByName = bindingsByRoot[ rootUuid ],
  23679. bindings = this._bindings;
  23680. if ( bindingByName === undefined ) {
  23681. bindingByName = {};
  23682. bindingsByRoot[ rootUuid ] = bindingByName;
  23683. }
  23684. bindingByName[ trackName ] = binding;
  23685. binding._cacheIndex = bindings.length;
  23686. bindings.push( binding );
  23687. },
  23688. _removeInactiveBinding: function ( binding ) {
  23689. var bindings = this._bindings,
  23690. propBinding = binding.binding,
  23691. rootUuid = propBinding.rootNode.uuid,
  23692. trackName = propBinding.path,
  23693. bindingsByRoot = this._bindingsByRootAndName,
  23694. bindingByName = bindingsByRoot[ rootUuid ],
  23695. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23696. cacheIndex = binding._cacheIndex;
  23697. lastInactiveBinding._cacheIndex = cacheIndex;
  23698. bindings[ cacheIndex ] = lastInactiveBinding;
  23699. bindings.pop();
  23700. delete bindingByName[ trackName ];
  23701. remove_empty_map: {
  23702. for ( var _ in bindingByName ) break remove_empty_map;
  23703. delete bindingsByRoot[ rootUuid ];
  23704. }
  23705. },
  23706. _lendBinding: function ( binding ) {
  23707. var bindings = this._bindings,
  23708. prevIndex = binding._cacheIndex,
  23709. lastActiveIndex = this._nActiveBindings ++,
  23710. firstInactiveBinding = bindings[ lastActiveIndex ];
  23711. binding._cacheIndex = lastActiveIndex;
  23712. bindings[ lastActiveIndex ] = binding;
  23713. firstInactiveBinding._cacheIndex = prevIndex;
  23714. bindings[ prevIndex ] = firstInactiveBinding;
  23715. },
  23716. _takeBackBinding: function ( binding ) {
  23717. var bindings = this._bindings,
  23718. prevIndex = binding._cacheIndex,
  23719. firstInactiveIndex = -- this._nActiveBindings,
  23720. lastActiveBinding = bindings[ firstInactiveIndex ];
  23721. binding._cacheIndex = firstInactiveIndex;
  23722. bindings[ firstInactiveIndex ] = binding;
  23723. lastActiveBinding._cacheIndex = prevIndex;
  23724. bindings[ prevIndex ] = lastActiveBinding;
  23725. },
  23726. // Memory management of Interpolants for weight and time scale
  23727. _lendControlInterpolant: function () {
  23728. var interpolants = this._controlInterpolants,
  23729. lastActiveIndex = this._nActiveControlInterpolants ++,
  23730. interpolant = interpolants[ lastActiveIndex ];
  23731. if ( interpolant === undefined ) {
  23732. interpolant = new LinearInterpolant(
  23733. new Float32Array( 2 ), new Float32Array( 2 ),
  23734. 1, this._controlInterpolantsResultBuffer );
  23735. interpolant.__cacheIndex = lastActiveIndex;
  23736. interpolants[ lastActiveIndex ] = interpolant;
  23737. }
  23738. return interpolant;
  23739. },
  23740. _takeBackControlInterpolant: function ( interpolant ) {
  23741. var interpolants = this._controlInterpolants,
  23742. prevIndex = interpolant.__cacheIndex,
  23743. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23744. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23745. interpolant.__cacheIndex = firstInactiveIndex;
  23746. interpolants[ firstInactiveIndex ] = interpolant;
  23747. lastActiveInterpolant.__cacheIndex = prevIndex;
  23748. interpolants[ prevIndex ] = lastActiveInterpolant;
  23749. },
  23750. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23751. // return an action for a clip optionally using a custom root target
  23752. // object (this method allocates a lot of dynamic memory in case a
  23753. // previously unknown clip/root combination is specified)
  23754. clipAction: function ( clip, optionalRoot ) {
  23755. var root = optionalRoot || this._root,
  23756. rootUuid = root.uuid,
  23757. clipObject = typeof clip === 'string' ?
  23758. AnimationClip.findByName( root, clip ) : clip,
  23759. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23760. actionsForClip = this._actionsByClip[ clipUuid ],
  23761. prototypeAction = null;
  23762. if ( actionsForClip !== undefined ) {
  23763. var existingAction =
  23764. actionsForClip.actionByRoot[ rootUuid ];
  23765. if ( existingAction !== undefined ) {
  23766. return existingAction;
  23767. }
  23768. // we know the clip, so we don't have to parse all
  23769. // the bindings again but can just copy
  23770. prototypeAction = actionsForClip.knownActions[ 0 ];
  23771. // also, take the clip from the prototype action
  23772. if ( clipObject === null )
  23773. clipObject = prototypeAction._clip;
  23774. }
  23775. // clip must be known when specified via string
  23776. if ( clipObject === null ) return null;
  23777. // allocate all resources required to run it
  23778. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23779. this._bindAction( newAction, prototypeAction );
  23780. // and make the action known to the memory manager
  23781. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23782. return newAction;
  23783. },
  23784. // get an existing action
  23785. existingAction: function ( clip, optionalRoot ) {
  23786. var root = optionalRoot || this._root,
  23787. rootUuid = root.uuid,
  23788. clipObject = typeof clip === 'string' ?
  23789. AnimationClip.findByName( root, clip ) : clip,
  23790. clipUuid = clipObject ? clipObject.uuid : clip,
  23791. actionsForClip = this._actionsByClip[ clipUuid ];
  23792. if ( actionsForClip !== undefined ) {
  23793. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23794. }
  23795. return null;
  23796. },
  23797. // deactivates all previously scheduled actions
  23798. stopAllAction: function () {
  23799. var actions = this._actions,
  23800. nActions = this._nActiveActions,
  23801. bindings = this._bindings,
  23802. nBindings = this._nActiveBindings;
  23803. this._nActiveActions = 0;
  23804. this._nActiveBindings = 0;
  23805. for ( var i = 0; i !== nActions; ++ i ) {
  23806. actions[ i ].reset();
  23807. }
  23808. for ( var i = 0; i !== nBindings; ++ i ) {
  23809. bindings[ i ].useCount = 0;
  23810. }
  23811. return this;
  23812. },
  23813. // advance the time and update apply the animation
  23814. update: function ( deltaTime ) {
  23815. deltaTime *= this.timeScale;
  23816. var actions = this._actions,
  23817. nActions = this._nActiveActions,
  23818. time = this.time += deltaTime,
  23819. timeDirection = Math.sign( deltaTime ),
  23820. accuIndex = this._accuIndex ^= 1;
  23821. // run active actions
  23822. for ( var i = 0; i !== nActions; ++ i ) {
  23823. var action = actions[ i ];
  23824. action._update( time, deltaTime, timeDirection, accuIndex );
  23825. }
  23826. // update scene graph
  23827. var bindings = this._bindings,
  23828. nBindings = this._nActiveBindings;
  23829. for ( var i = 0; i !== nBindings; ++ i ) {
  23830. bindings[ i ].apply( accuIndex );
  23831. }
  23832. return this;
  23833. },
  23834. // return this mixer's root target object
  23835. getRoot: function () {
  23836. return this._root;
  23837. },
  23838. // free all resources specific to a particular clip
  23839. uncacheClip: function ( clip ) {
  23840. var actions = this._actions,
  23841. clipUuid = clip.uuid,
  23842. actionsByClip = this._actionsByClip,
  23843. actionsForClip = actionsByClip[ clipUuid ];
  23844. if ( actionsForClip !== undefined ) {
  23845. // note: just calling _removeInactiveAction would mess up the
  23846. // iteration state and also require updating the state we can
  23847. // just throw away
  23848. var actionsToRemove = actionsForClip.knownActions;
  23849. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23850. var action = actionsToRemove[ i ];
  23851. this._deactivateAction( action );
  23852. var cacheIndex = action._cacheIndex,
  23853. lastInactiveAction = actions[ actions.length - 1 ];
  23854. action._cacheIndex = null;
  23855. action._byClipCacheIndex = null;
  23856. lastInactiveAction._cacheIndex = cacheIndex;
  23857. actions[ cacheIndex ] = lastInactiveAction;
  23858. actions.pop();
  23859. this._removeInactiveBindingsForAction( action );
  23860. }
  23861. delete actionsByClip[ clipUuid ];
  23862. }
  23863. },
  23864. // free all resources specific to a particular root target object
  23865. uncacheRoot: function ( root ) {
  23866. var rootUuid = root.uuid,
  23867. actionsByClip = this._actionsByClip;
  23868. for ( var clipUuid in actionsByClip ) {
  23869. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23870. action = actionByRoot[ rootUuid ];
  23871. if ( action !== undefined ) {
  23872. this._deactivateAction( action );
  23873. this._removeInactiveAction( action );
  23874. }
  23875. }
  23876. var bindingsByRoot = this._bindingsByRootAndName,
  23877. bindingByName = bindingsByRoot[ rootUuid ];
  23878. if ( bindingByName !== undefined ) {
  23879. for ( var trackName in bindingByName ) {
  23880. var binding = bindingByName[ trackName ];
  23881. binding.restoreOriginalState();
  23882. this._removeInactiveBinding( binding );
  23883. }
  23884. }
  23885. },
  23886. // remove a targeted clip from the cache
  23887. uncacheAction: function ( clip, optionalRoot ) {
  23888. var action = this.existingAction( clip, optionalRoot );
  23889. if ( action !== null ) {
  23890. this._deactivateAction( action );
  23891. this._removeInactiveAction( action );
  23892. }
  23893. }
  23894. } );
  23895. /**
  23896. * @author mrdoob / http://mrdoob.com/
  23897. */
  23898. function Uniform( value ) {
  23899. if ( typeof value === 'string' ) {
  23900. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23901. value = arguments[ 1 ];
  23902. }
  23903. this.value = value;
  23904. }
  23905. Uniform.prototype.clone = function () {
  23906. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23907. };
  23908. /**
  23909. * @author benaadams / https://twitter.com/ben_a_adams
  23910. */
  23911. function InstancedBufferGeometry() {
  23912. BufferGeometry.call( this );
  23913. this.type = 'InstancedBufferGeometry';
  23914. this.maxInstancedCount = undefined;
  23915. }
  23916. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23917. constructor: InstancedBufferGeometry,
  23918. isInstancedBufferGeometry: true,
  23919. addGroup: function ( start, count, materialIndex ) {
  23920. this.groups.push( {
  23921. start: start,
  23922. count: count,
  23923. materialIndex: materialIndex
  23924. } );
  23925. },
  23926. copy: function ( source ) {
  23927. var index = source.index;
  23928. if ( index !== null ) {
  23929. this.setIndex( index.clone() );
  23930. }
  23931. var attributes = source.attributes;
  23932. for ( var name in attributes ) {
  23933. var attribute = attributes[ name ];
  23934. this.addAttribute( name, attribute.clone() );
  23935. }
  23936. var groups = source.groups;
  23937. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23938. var group = groups[ i ];
  23939. this.addGroup( group.start, group.count, group.materialIndex );
  23940. }
  23941. return this;
  23942. }
  23943. } );
  23944. /**
  23945. * @author benaadams / https://twitter.com/ben_a_adams
  23946. */
  23947. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23948. this.uuid = _Math.generateUUID();
  23949. this.data = interleavedBuffer;
  23950. this.itemSize = itemSize;
  23951. this.offset = offset;
  23952. this.normalized = normalized === true;
  23953. }
  23954. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23955. count: {
  23956. get: function () {
  23957. return this.data.count;
  23958. }
  23959. },
  23960. array: {
  23961. get: function () {
  23962. return this.data.array;
  23963. }
  23964. }
  23965. } );
  23966. Object.assign( InterleavedBufferAttribute.prototype, {
  23967. isInterleavedBufferAttribute: true,
  23968. setX: function ( index, x ) {
  23969. this.data.array[ index * this.data.stride + this.offset ] = x;
  23970. return this;
  23971. },
  23972. setY: function ( index, y ) {
  23973. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23974. return this;
  23975. },
  23976. setZ: function ( index, z ) {
  23977. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23978. return this;
  23979. },
  23980. setW: function ( index, w ) {
  23981. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23982. return this;
  23983. },
  23984. getX: function ( index ) {
  23985. return this.data.array[ index * this.data.stride + this.offset ];
  23986. },
  23987. getY: function ( index ) {
  23988. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23989. },
  23990. getZ: function ( index ) {
  23991. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23992. },
  23993. getW: function ( index ) {
  23994. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23995. },
  23996. setXY: function ( index, x, y ) {
  23997. index = index * this.data.stride + this.offset;
  23998. this.data.array[ index + 0 ] = x;
  23999. this.data.array[ index + 1 ] = y;
  24000. return this;
  24001. },
  24002. setXYZ: function ( index, x, y, z ) {
  24003. index = index * this.data.stride + this.offset;
  24004. this.data.array[ index + 0 ] = x;
  24005. this.data.array[ index + 1 ] = y;
  24006. this.data.array[ index + 2 ] = z;
  24007. return this;
  24008. },
  24009. setXYZW: function ( index, x, y, z, w ) {
  24010. index = index * this.data.stride + this.offset;
  24011. this.data.array[ index + 0 ] = x;
  24012. this.data.array[ index + 1 ] = y;
  24013. this.data.array[ index + 2 ] = z;
  24014. this.data.array[ index + 3 ] = w;
  24015. return this;
  24016. }
  24017. } );
  24018. /**
  24019. * @author benaadams / https://twitter.com/ben_a_adams
  24020. */
  24021. function InterleavedBuffer( array, stride ) {
  24022. this.uuid = _Math.generateUUID();
  24023. this.array = array;
  24024. this.stride = stride;
  24025. this.count = array !== undefined ? array.length / stride : 0;
  24026. this.dynamic = false;
  24027. this.updateRange = { offset: 0, count: - 1 };
  24028. this.onUploadCallback = function () {};
  24029. this.version = 0;
  24030. }
  24031. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  24032. set: function ( value ) {
  24033. if ( value === true ) this.version ++;
  24034. }
  24035. } );
  24036. Object.assign( InterleavedBuffer.prototype, {
  24037. isInterleavedBuffer: true,
  24038. setArray: function ( array ) {
  24039. if ( Array.isArray( array ) ) {
  24040. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  24041. }
  24042. this.count = array !== undefined ? array.length / this.stride : 0;
  24043. this.array = array;
  24044. },
  24045. setDynamic: function ( value ) {
  24046. this.dynamic = value;
  24047. return this;
  24048. },
  24049. copy: function ( source ) {
  24050. this.array = new source.array.constructor( source.array );
  24051. this.count = source.count;
  24052. this.stride = source.stride;
  24053. this.dynamic = source.dynamic;
  24054. return this;
  24055. },
  24056. copyAt: function ( index1, attribute, index2 ) {
  24057. index1 *= this.stride;
  24058. index2 *= attribute.stride;
  24059. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  24060. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  24061. }
  24062. return this;
  24063. },
  24064. set: function ( value, offset ) {
  24065. if ( offset === undefined ) offset = 0;
  24066. this.array.set( value, offset );
  24067. return this;
  24068. },
  24069. clone: function () {
  24070. return new this.constructor().copy( this );
  24071. },
  24072. onUpload: function ( callback ) {
  24073. this.onUploadCallback = callback;
  24074. return this;
  24075. }
  24076. } );
  24077. /**
  24078. * @author benaadams / https://twitter.com/ben_a_adams
  24079. */
  24080. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  24081. InterleavedBuffer.call( this, array, stride );
  24082. this.meshPerAttribute = meshPerAttribute || 1;
  24083. }
  24084. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  24085. constructor: InstancedInterleavedBuffer,
  24086. isInstancedInterleavedBuffer: true,
  24087. copy: function ( source ) {
  24088. InterleavedBuffer.prototype.copy.call( this, source );
  24089. this.meshPerAttribute = source.meshPerAttribute;
  24090. return this;
  24091. }
  24092. } );
  24093. /**
  24094. * @author benaadams / https://twitter.com/ben_a_adams
  24095. */
  24096. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  24097. BufferAttribute.call( this, array, itemSize );
  24098. this.meshPerAttribute = meshPerAttribute || 1;
  24099. }
  24100. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24101. constructor: InstancedBufferAttribute,
  24102. isInstancedBufferAttribute: true,
  24103. copy: function ( source ) {
  24104. BufferAttribute.prototype.copy.call( this, source );
  24105. this.meshPerAttribute = source.meshPerAttribute;
  24106. return this;
  24107. }
  24108. } );
  24109. /**
  24110. * @author mrdoob / http://mrdoob.com/
  24111. * @author bhouston / http://clara.io/
  24112. * @author stephomi / http://stephaneginier.com/
  24113. */
  24114. function Raycaster( origin, direction, near, far ) {
  24115. this.ray = new Ray( origin, direction );
  24116. // direction is assumed to be normalized (for accurate distance calculations)
  24117. this.near = near || 0;
  24118. this.far = far || Infinity;
  24119. this.params = {
  24120. Mesh: {},
  24121. Line: {},
  24122. LOD: {},
  24123. Points: { threshold: 1 },
  24124. Sprite: {}
  24125. };
  24126. Object.defineProperties( this.params, {
  24127. PointCloud: {
  24128. get: function () {
  24129. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  24130. return this.Points;
  24131. }
  24132. }
  24133. } );
  24134. }
  24135. function ascSort( a, b ) {
  24136. return a.distance - b.distance;
  24137. }
  24138. function intersectObject( object, raycaster, intersects, recursive ) {
  24139. if ( object.visible === false ) return;
  24140. object.raycast( raycaster, intersects );
  24141. if ( recursive === true ) {
  24142. var children = object.children;
  24143. for ( var i = 0, l = children.length; i < l; i ++ ) {
  24144. intersectObject( children[ i ], raycaster, intersects, true );
  24145. }
  24146. }
  24147. }
  24148. Object.assign( Raycaster.prototype, {
  24149. linePrecision: 1,
  24150. set: function ( origin, direction ) {
  24151. // direction is assumed to be normalized (for accurate distance calculations)
  24152. this.ray.set( origin, direction );
  24153. },
  24154. setFromCamera: function ( coords, camera ) {
  24155. if ( ( camera && camera.isPerspectiveCamera ) ) {
  24156. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  24157. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  24158. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  24159. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  24160. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  24161. } else {
  24162. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  24163. }
  24164. },
  24165. intersectObject: function ( object, recursive ) {
  24166. var intersects = [];
  24167. intersectObject( object, this, intersects, recursive );
  24168. intersects.sort( ascSort );
  24169. return intersects;
  24170. },
  24171. intersectObjects: function ( objects, recursive ) {
  24172. var intersects = [];
  24173. if ( Array.isArray( objects ) === false ) {
  24174. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  24175. return intersects;
  24176. }
  24177. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  24178. intersectObject( objects[ i ], this, intersects, recursive );
  24179. }
  24180. intersects.sort( ascSort );
  24181. return intersects;
  24182. }
  24183. } );
  24184. /**
  24185. * @author alteredq / http://alteredqualia.com/
  24186. */
  24187. function Clock( autoStart ) {
  24188. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  24189. this.startTime = 0;
  24190. this.oldTime = 0;
  24191. this.elapsedTime = 0;
  24192. this.running = false;
  24193. }
  24194. Object.assign( Clock.prototype, {
  24195. start: function () {
  24196. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24197. this.oldTime = this.startTime;
  24198. this.elapsedTime = 0;
  24199. this.running = true;
  24200. },
  24201. stop: function () {
  24202. this.getElapsedTime();
  24203. this.running = false;
  24204. this.autoStart = false;
  24205. },
  24206. getElapsedTime: function () {
  24207. this.getDelta();
  24208. return this.elapsedTime;
  24209. },
  24210. getDelta: function () {
  24211. var diff = 0;
  24212. if ( this.autoStart && ! this.running ) {
  24213. this.start();
  24214. return 0;
  24215. }
  24216. if ( this.running ) {
  24217. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  24218. diff = ( newTime - this.oldTime ) / 1000;
  24219. this.oldTime = newTime;
  24220. this.elapsedTime += diff;
  24221. }
  24222. return diff;
  24223. }
  24224. } );
  24225. /**
  24226. * @author bhouston / http://clara.io
  24227. * @author WestLangley / http://github.com/WestLangley
  24228. *
  24229. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  24230. *
  24231. * The poles (phi) are at the positive and negative y axis.
  24232. * The equator starts at positive z.
  24233. */
  24234. function Spherical( radius, phi, theta ) {
  24235. this.radius = ( radius !== undefined ) ? radius : 1.0;
  24236. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  24237. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  24238. return this;
  24239. }
  24240. Object.assign( Spherical.prototype, {
  24241. set: function ( radius, phi, theta ) {
  24242. this.radius = radius;
  24243. this.phi = phi;
  24244. this.theta = theta;
  24245. return this;
  24246. },
  24247. clone: function () {
  24248. return new this.constructor().copy( this );
  24249. },
  24250. copy: function ( other ) {
  24251. this.radius = other.radius;
  24252. this.phi = other.phi;
  24253. this.theta = other.theta;
  24254. return this;
  24255. },
  24256. // restrict phi to be betwee EPS and PI-EPS
  24257. makeSafe: function() {
  24258. var EPS = 0.000001;
  24259. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  24260. return this;
  24261. },
  24262. setFromVector3: function( vec3 ) {
  24263. this.radius = vec3.length();
  24264. if ( this.radius === 0 ) {
  24265. this.theta = 0;
  24266. this.phi = 0;
  24267. } else {
  24268. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  24269. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  24270. }
  24271. return this;
  24272. }
  24273. } );
  24274. /**
  24275. * @author Mugen87 / https://github.com/Mugen87
  24276. *
  24277. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  24278. *
  24279. */
  24280. function Cylindrical( radius, theta, y ) {
  24281. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  24282. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  24283. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  24284. return this;
  24285. }
  24286. Object.assign( Cylindrical.prototype, {
  24287. set: function ( radius, theta, y ) {
  24288. this.radius = radius;
  24289. this.theta = theta;
  24290. this.y = y;
  24291. return this;
  24292. },
  24293. clone: function () {
  24294. return new this.constructor().copy( this );
  24295. },
  24296. copy: function ( other ) {
  24297. this.radius = other.radius;
  24298. this.theta = other.theta;
  24299. this.y = other.y;
  24300. return this;
  24301. },
  24302. setFromVector3: function( vec3 ) {
  24303. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  24304. this.theta = Math.atan2( vec3.x, vec3.z );
  24305. this.y = vec3.y;
  24306. return this;
  24307. }
  24308. } );
  24309. /**
  24310. * @author alteredq / http://alteredqualia.com/
  24311. */
  24312. function ImmediateRenderObject( material ) {
  24313. Object3D.call( this );
  24314. this.material = material;
  24315. this.render = function ( renderCallback ) {};
  24316. }
  24317. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24318. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24319. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24320. /**
  24321. * @author mrdoob / http://mrdoob.com/
  24322. * @author WestLangley / http://github.com/WestLangley
  24323. */
  24324. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24325. this.object = object;
  24326. this.size = ( size !== undefined ) ? size : 1;
  24327. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24328. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24329. //
  24330. var nNormals = 0;
  24331. var objGeometry = this.object.geometry;
  24332. if ( objGeometry && objGeometry.isGeometry ) {
  24333. nNormals = objGeometry.faces.length * 3;
  24334. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24335. nNormals = objGeometry.attributes.normal.count;
  24336. }
  24337. //
  24338. var geometry = new BufferGeometry();
  24339. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24340. geometry.addAttribute( 'position', positions );
  24341. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24342. //
  24343. this.matrixAutoUpdate = false;
  24344. this.update();
  24345. }
  24346. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24347. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24348. VertexNormalsHelper.prototype.update = ( function () {
  24349. var v1 = new Vector3();
  24350. var v2 = new Vector3();
  24351. var normalMatrix = new Matrix3();
  24352. return function update() {
  24353. var keys = [ 'a', 'b', 'c' ];
  24354. this.object.updateMatrixWorld( true );
  24355. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24356. var matrixWorld = this.object.matrixWorld;
  24357. var position = this.geometry.attributes.position;
  24358. //
  24359. var objGeometry = this.object.geometry;
  24360. if ( objGeometry && objGeometry.isGeometry ) {
  24361. var vertices = objGeometry.vertices;
  24362. var faces = objGeometry.faces;
  24363. var idx = 0;
  24364. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24365. var face = faces[ i ];
  24366. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24367. var vertex = vertices[ face[ keys[ j ] ] ];
  24368. var normal = face.vertexNormals[ j ];
  24369. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24370. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24371. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24372. idx = idx + 1;
  24373. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24374. idx = idx + 1;
  24375. }
  24376. }
  24377. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24378. var objPos = objGeometry.attributes.position;
  24379. var objNorm = objGeometry.attributes.normal;
  24380. var idx = 0;
  24381. // for simplicity, ignore index and drawcalls, and render every normal
  24382. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24383. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24384. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24385. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24386. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24387. idx = idx + 1;
  24388. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24389. idx = idx + 1;
  24390. }
  24391. }
  24392. position.needsUpdate = true;
  24393. };
  24394. }() );
  24395. /**
  24396. * @author alteredq / http://alteredqualia.com/
  24397. * @author mrdoob / http://mrdoob.com/
  24398. * @author WestLangley / http://github.com/WestLangley
  24399. */
  24400. function SpotLightHelper( light, color ) {
  24401. Object3D.call( this );
  24402. this.light = light;
  24403. this.light.updateMatrixWorld();
  24404. this.matrix = light.matrixWorld;
  24405. this.matrixAutoUpdate = false;
  24406. this.color = color;
  24407. var geometry = new BufferGeometry();
  24408. var positions = [
  24409. 0, 0, 0, 0, 0, 1,
  24410. 0, 0, 0, 1, 0, 1,
  24411. 0, 0, 0, - 1, 0, 1,
  24412. 0, 0, 0, 0, 1, 1,
  24413. 0, 0, 0, 0, - 1, 1
  24414. ];
  24415. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24416. var p1 = ( i / l ) * Math.PI * 2;
  24417. var p2 = ( j / l ) * Math.PI * 2;
  24418. positions.push(
  24419. Math.cos( p1 ), Math.sin( p1 ), 1,
  24420. Math.cos( p2 ), Math.sin( p2 ), 1
  24421. );
  24422. }
  24423. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24424. var material = new LineBasicMaterial( { fog: false } );
  24425. this.cone = new LineSegments( geometry, material );
  24426. this.add( this.cone );
  24427. this.update();
  24428. }
  24429. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24430. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24431. SpotLightHelper.prototype.dispose = function () {
  24432. this.cone.geometry.dispose();
  24433. this.cone.material.dispose();
  24434. };
  24435. SpotLightHelper.prototype.update = function () {
  24436. var vector = new Vector3();
  24437. var vector2 = new Vector3();
  24438. return function update() {
  24439. this.light.updateMatrixWorld();
  24440. var coneLength = this.light.distance ? this.light.distance : 1000;
  24441. var coneWidth = coneLength * Math.tan( this.light.angle );
  24442. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24443. vector.setFromMatrixPosition( this.light.matrixWorld );
  24444. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24445. this.cone.lookAt( vector2.sub( vector ) );
  24446. if ( this.color !== undefined ) {
  24447. this.cone.material.color.set( this.color );
  24448. } else {
  24449. this.cone.material.color.copy( this.light.color );
  24450. }
  24451. };
  24452. }();
  24453. /**
  24454. * @author Sean Griffin / http://twitter.com/sgrif
  24455. * @author Michael Guerrero / http://realitymeltdown.com
  24456. * @author mrdoob / http://mrdoob.com/
  24457. * @author ikerr / http://verold.com
  24458. * @author Mugen87 / https://github.com/Mugen87
  24459. */
  24460. function getBoneList( object ) {
  24461. var boneList = [];
  24462. if ( object && object.isBone ) {
  24463. boneList.push( object );
  24464. }
  24465. for ( var i = 0; i < object.children.length; i ++ ) {
  24466. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  24467. }
  24468. return boneList;
  24469. }
  24470. function SkeletonHelper( object ) {
  24471. var bones = getBoneList( object );
  24472. var geometry = new BufferGeometry();
  24473. var vertices = [];
  24474. var colors = [];
  24475. var color1 = new Color( 0, 0, 1 );
  24476. var color2 = new Color( 0, 1, 0 );
  24477. for ( var i = 0; i < bones.length; i ++ ) {
  24478. var bone = bones[ i ];
  24479. if ( bone.parent && bone.parent.isBone ) {
  24480. vertices.push( 0, 0, 0 );
  24481. vertices.push( 0, 0, 0 );
  24482. colors.push( color1.r, color1.g, color1.b );
  24483. colors.push( color2.r, color2.g, color2.b );
  24484. }
  24485. }
  24486. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24487. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24488. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24489. LineSegments.call( this, geometry, material );
  24490. this.root = object;
  24491. this.bones = bones;
  24492. this.matrix = object.matrixWorld;
  24493. this.matrixAutoUpdate = false;
  24494. }
  24495. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24496. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24497. SkeletonHelper.prototype.updateMatrixWorld = function () {
  24498. var vector = new Vector3();
  24499. var boneMatrix = new Matrix4();
  24500. var matrixWorldInv = new Matrix4();
  24501. return function updateMatrixWorld( force ) {
  24502. var bones = this.bones;
  24503. var geometry = this.geometry;
  24504. var position = geometry.getAttribute( 'position' );
  24505. matrixWorldInv.getInverse( this.root.matrixWorld );
  24506. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  24507. var bone = bones[ i ];
  24508. if ( bone.parent && bone.parent.isBone ) {
  24509. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24510. vector.setFromMatrixPosition( boneMatrix );
  24511. position.setXYZ( j, vector.x, vector.y, vector.z );
  24512. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24513. vector.setFromMatrixPosition( boneMatrix );
  24514. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24515. j += 2;
  24516. }
  24517. }
  24518. geometry.getAttribute( 'position' ).needsUpdate = true;
  24519. Object3D.prototype.updateMatrixWorld.call( this, force );
  24520. };
  24521. }();
  24522. /**
  24523. * @author alteredq / http://alteredqualia.com/
  24524. * @author mrdoob / http://mrdoob.com/
  24525. */
  24526. function PointLightHelper( light, sphereSize, color ) {
  24527. this.light = light;
  24528. this.light.updateMatrixWorld();
  24529. this.color = color;
  24530. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24531. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24532. Mesh.call( this, geometry, material );
  24533. this.matrix = this.light.matrixWorld;
  24534. this.matrixAutoUpdate = false;
  24535. this.update();
  24536. /*
  24537. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24538. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24539. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24540. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24541. var d = light.distance;
  24542. if ( d === 0.0 ) {
  24543. this.lightDistance.visible = false;
  24544. } else {
  24545. this.lightDistance.scale.set( d, d, d );
  24546. }
  24547. this.add( this.lightDistance );
  24548. */
  24549. }
  24550. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24551. PointLightHelper.prototype.constructor = PointLightHelper;
  24552. PointLightHelper.prototype.dispose = function () {
  24553. this.geometry.dispose();
  24554. this.material.dispose();
  24555. };
  24556. PointLightHelper.prototype.update = function () {
  24557. if ( this.color !== undefined ) {
  24558. this.material.color.set( this.color );
  24559. } else {
  24560. this.material.color.copy( this.light.color );
  24561. }
  24562. /*
  24563. var d = this.light.distance;
  24564. if ( d === 0.0 ) {
  24565. this.lightDistance.visible = false;
  24566. } else {
  24567. this.lightDistance.visible = true;
  24568. this.lightDistance.scale.set( d, d, d );
  24569. }
  24570. */
  24571. };
  24572. /**
  24573. * @author abelnation / http://github.com/abelnation
  24574. * @author Mugen87 / http://github.com/Mugen87
  24575. * @author WestLangley / http://github.com/WestLangley
  24576. */
  24577. function RectAreaLightHelper( light, color ) {
  24578. Object3D.call( this );
  24579. this.light = light;
  24580. this.light.updateMatrixWorld();
  24581. this.matrix = light.matrixWorld;
  24582. this.matrixAutoUpdate = false;
  24583. this.color = color;
  24584. var material = new LineBasicMaterial( { fog: false } );
  24585. var geometry = new BufferGeometry();
  24586. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24587. this.line = new Line( geometry, material );
  24588. this.add( this.line );
  24589. this.update();
  24590. }
  24591. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24592. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24593. RectAreaLightHelper.prototype.dispose = function () {
  24594. this.children[ 0 ].geometry.dispose();
  24595. this.children[ 0 ].material.dispose();
  24596. };
  24597. RectAreaLightHelper.prototype.update = function () {
  24598. // calculate new dimensions of the helper
  24599. var hx = this.light.width * 0.5;
  24600. var hy = this.light.height * 0.5;
  24601. var position = this.line.geometry.attributes.position;
  24602. var array = position.array;
  24603. // update vertices
  24604. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24605. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24606. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24607. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24608. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24609. position.needsUpdate = true;
  24610. if ( this.color !== undefined ) {
  24611. this.line.material.color.set( this.color );
  24612. } else {
  24613. this.line.material.color.copy( this.light.color );
  24614. }
  24615. };
  24616. /**
  24617. * @author alteredq / http://alteredqualia.com/
  24618. * @author mrdoob / http://mrdoob.com/
  24619. * @author Mugen87 / https://github.com/Mugen87
  24620. */
  24621. function HemisphereLightHelper( light, size, color ) {
  24622. Object3D.call( this );
  24623. this.light = light;
  24624. this.light.updateMatrixWorld();
  24625. this.matrix = light.matrixWorld;
  24626. this.matrixAutoUpdate = false;
  24627. this.color = color;
  24628. var geometry = new OctahedronBufferGeometry( size );
  24629. geometry.rotateY( Math.PI * 0.5 );
  24630. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24631. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  24632. var position = geometry.getAttribute( 'position' );
  24633. var colors = new Float32Array( position.count * 3 );
  24634. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24635. this.add( new Mesh( geometry, this.material ) );
  24636. this.update();
  24637. }
  24638. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24639. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24640. HemisphereLightHelper.prototype.dispose = function () {
  24641. this.children[ 0 ].geometry.dispose();
  24642. this.children[ 0 ].material.dispose();
  24643. };
  24644. HemisphereLightHelper.prototype.update = function () {
  24645. var vector = new Vector3();
  24646. var color1 = new Color();
  24647. var color2 = new Color();
  24648. return function update() {
  24649. var mesh = this.children[ 0 ];
  24650. if ( this.color !== undefined ) {
  24651. this.material.color.set( this.color );
  24652. } else {
  24653. var colors = mesh.geometry.getAttribute( 'color' );
  24654. color1.copy( this.light.color );
  24655. color2.copy( this.light.groundColor );
  24656. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24657. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24658. colors.setXYZ( i, color.r, color.g, color.b );
  24659. }
  24660. colors.needsUpdate = true;
  24661. }
  24662. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24663. };
  24664. }();
  24665. /**
  24666. * @author mrdoob / http://mrdoob.com/
  24667. */
  24668. function GridHelper( size, divisions, color1, color2 ) {
  24669. size = size || 10;
  24670. divisions = divisions || 10;
  24671. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24672. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24673. var center = divisions / 2;
  24674. var step = size / divisions;
  24675. var halfSize = size / 2;
  24676. var vertices = [], colors = [];
  24677. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24678. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24679. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24680. var color = i === center ? color1 : color2;
  24681. color.toArray( colors, j ); j += 3;
  24682. color.toArray( colors, j ); j += 3;
  24683. color.toArray( colors, j ); j += 3;
  24684. color.toArray( colors, j ); j += 3;
  24685. }
  24686. var geometry = new BufferGeometry();
  24687. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24688. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24689. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24690. LineSegments.call( this, geometry, material );
  24691. }
  24692. GridHelper.prototype = Object.create( LineSegments.prototype );
  24693. GridHelper.prototype.constructor = GridHelper;
  24694. /**
  24695. * @author mrdoob / http://mrdoob.com/
  24696. * @author Mugen87 / http://github.com/Mugen87
  24697. * @author Hectate / http://www.github.com/Hectate
  24698. */
  24699. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24700. radius = radius || 10;
  24701. radials = radials || 16;
  24702. circles = circles || 8;
  24703. divisions = divisions || 64;
  24704. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24705. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24706. var vertices = [];
  24707. var colors = [];
  24708. var x, z;
  24709. var v, i, j, r, color;
  24710. // create the radials
  24711. for ( i = 0; i <= radials; i ++ ) {
  24712. v = ( i / radials ) * ( Math.PI * 2 );
  24713. x = Math.sin( v ) * radius;
  24714. z = Math.cos( v ) * radius;
  24715. vertices.push( 0, 0, 0 );
  24716. vertices.push( x, 0, z );
  24717. color = ( i & 1 ) ? color1 : color2;
  24718. colors.push( color.r, color.g, color.b );
  24719. colors.push( color.r, color.g, color.b );
  24720. }
  24721. // create the circles
  24722. for ( i = 0; i <= circles; i ++ ) {
  24723. color = ( i & 1 ) ? color1 : color2;
  24724. r = radius - ( radius / circles * i );
  24725. for ( j = 0; j < divisions; j ++ ) {
  24726. // first vertex
  24727. v = ( j / divisions ) * ( Math.PI * 2 );
  24728. x = Math.sin( v ) * r;
  24729. z = Math.cos( v ) * r;
  24730. vertices.push( x, 0, z );
  24731. colors.push( color.r, color.g, color.b );
  24732. // second vertex
  24733. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24734. x = Math.sin( v ) * r;
  24735. z = Math.cos( v ) * r;
  24736. vertices.push( x, 0, z );
  24737. colors.push( color.r, color.g, color.b );
  24738. }
  24739. }
  24740. var geometry = new BufferGeometry();
  24741. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24742. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24743. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24744. LineSegments.call( this, geometry, material );
  24745. }
  24746. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24747. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24748. /**
  24749. * @author mrdoob / http://mrdoob.com/
  24750. * @author WestLangley / http://github.com/WestLangley
  24751. */
  24752. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24753. // FaceNormalsHelper only supports THREE.Geometry
  24754. this.object = object;
  24755. this.size = ( size !== undefined ) ? size : 1;
  24756. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24757. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24758. //
  24759. var nNormals = 0;
  24760. var objGeometry = this.object.geometry;
  24761. if ( objGeometry && objGeometry.isGeometry ) {
  24762. nNormals = objGeometry.faces.length;
  24763. } else {
  24764. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24765. }
  24766. //
  24767. var geometry = new BufferGeometry();
  24768. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24769. geometry.addAttribute( 'position', positions );
  24770. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24771. //
  24772. this.matrixAutoUpdate = false;
  24773. this.update();
  24774. }
  24775. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24776. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24777. FaceNormalsHelper.prototype.update = ( function () {
  24778. var v1 = new Vector3();
  24779. var v2 = new Vector3();
  24780. var normalMatrix = new Matrix3();
  24781. return function update() {
  24782. this.object.updateMatrixWorld( true );
  24783. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24784. var matrixWorld = this.object.matrixWorld;
  24785. var position = this.geometry.attributes.position;
  24786. //
  24787. var objGeometry = this.object.geometry;
  24788. var vertices = objGeometry.vertices;
  24789. var faces = objGeometry.faces;
  24790. var idx = 0;
  24791. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24792. var face = faces[ i ];
  24793. var normal = face.normal;
  24794. v1.copy( vertices[ face.a ] )
  24795. .add( vertices[ face.b ] )
  24796. .add( vertices[ face.c ] )
  24797. .divideScalar( 3 )
  24798. .applyMatrix4( matrixWorld );
  24799. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24800. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24801. idx = idx + 1;
  24802. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24803. idx = idx + 1;
  24804. }
  24805. position.needsUpdate = true;
  24806. };
  24807. }() );
  24808. /**
  24809. * @author alteredq / http://alteredqualia.com/
  24810. * @author mrdoob / http://mrdoob.com/
  24811. * @author WestLangley / http://github.com/WestLangley
  24812. */
  24813. function DirectionalLightHelper( light, size, color ) {
  24814. Object3D.call( this );
  24815. this.light = light;
  24816. this.light.updateMatrixWorld();
  24817. this.matrix = light.matrixWorld;
  24818. this.matrixAutoUpdate = false;
  24819. this.color = color;
  24820. if ( size === undefined ) size = 1;
  24821. var geometry = new BufferGeometry();
  24822. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24823. - size, size, 0,
  24824. size, size, 0,
  24825. size, - size, 0,
  24826. - size, - size, 0,
  24827. - size, size, 0
  24828. ], 3 ) );
  24829. var material = new LineBasicMaterial( { fog: false } );
  24830. this.lightPlane = new Line( geometry, material );
  24831. this.add( this.lightPlane );
  24832. geometry = new BufferGeometry();
  24833. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24834. this.targetLine = new Line( geometry, material );
  24835. this.add( this.targetLine );
  24836. this.update();
  24837. }
  24838. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24839. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24840. DirectionalLightHelper.prototype.dispose = function () {
  24841. this.lightPlane.geometry.dispose();
  24842. this.lightPlane.material.dispose();
  24843. this.targetLine.geometry.dispose();
  24844. this.targetLine.material.dispose();
  24845. };
  24846. DirectionalLightHelper.prototype.update = function () {
  24847. var v1 = new Vector3();
  24848. var v2 = new Vector3();
  24849. var v3 = new Vector3();
  24850. return function update() {
  24851. v1.setFromMatrixPosition( this.light.matrixWorld );
  24852. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24853. v3.subVectors( v2, v1 );
  24854. this.lightPlane.lookAt( v3 );
  24855. if ( this.color !== undefined ) {
  24856. this.lightPlane.material.color.set( this.color );
  24857. this.targetLine.material.color.set( this.color );
  24858. } else {
  24859. this.lightPlane.material.color.copy( this.light.color );
  24860. this.targetLine.material.color.copy( this.light.color );
  24861. }
  24862. this.targetLine.lookAt( v3 );
  24863. this.targetLine.scale.z = v3.length();
  24864. };
  24865. }();
  24866. /**
  24867. * @author alteredq / http://alteredqualia.com/
  24868. * @author Mugen87 / https://github.com/Mugen87
  24869. *
  24870. * - shows frustum, line of sight and up of the camera
  24871. * - suitable for fast updates
  24872. * - based on frustum visualization in lightgl.js shadowmap example
  24873. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24874. */
  24875. function CameraHelper( camera ) {
  24876. var geometry = new BufferGeometry();
  24877. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24878. var vertices = [];
  24879. var colors = [];
  24880. var pointMap = {};
  24881. // colors
  24882. var colorFrustum = new Color( 0xffaa00 );
  24883. var colorCone = new Color( 0xff0000 );
  24884. var colorUp = new Color( 0x00aaff );
  24885. var colorTarget = new Color( 0xffffff );
  24886. var colorCross = new Color( 0x333333 );
  24887. // near
  24888. addLine( "n1", "n2", colorFrustum );
  24889. addLine( "n2", "n4", colorFrustum );
  24890. addLine( "n4", "n3", colorFrustum );
  24891. addLine( "n3", "n1", colorFrustum );
  24892. // far
  24893. addLine( "f1", "f2", colorFrustum );
  24894. addLine( "f2", "f4", colorFrustum );
  24895. addLine( "f4", "f3", colorFrustum );
  24896. addLine( "f3", "f1", colorFrustum );
  24897. // sides
  24898. addLine( "n1", "f1", colorFrustum );
  24899. addLine( "n2", "f2", colorFrustum );
  24900. addLine( "n3", "f3", colorFrustum );
  24901. addLine( "n4", "f4", colorFrustum );
  24902. // cone
  24903. addLine( "p", "n1", colorCone );
  24904. addLine( "p", "n2", colorCone );
  24905. addLine( "p", "n3", colorCone );
  24906. addLine( "p", "n4", colorCone );
  24907. // up
  24908. addLine( "u1", "u2", colorUp );
  24909. addLine( "u2", "u3", colorUp );
  24910. addLine( "u3", "u1", colorUp );
  24911. // target
  24912. addLine( "c", "t", colorTarget );
  24913. addLine( "p", "c", colorCross );
  24914. // cross
  24915. addLine( "cn1", "cn2", colorCross );
  24916. addLine( "cn3", "cn4", colorCross );
  24917. addLine( "cf1", "cf2", colorCross );
  24918. addLine( "cf3", "cf4", colorCross );
  24919. function addLine( a, b, color ) {
  24920. addPoint( a, color );
  24921. addPoint( b, color );
  24922. }
  24923. function addPoint( id, color ) {
  24924. vertices.push( 0, 0, 0 );
  24925. colors.push( color.r, color.g, color.b );
  24926. if ( pointMap[ id ] === undefined ) {
  24927. pointMap[ id ] = [];
  24928. }
  24929. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24930. }
  24931. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24932. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24933. LineSegments.call( this, geometry, material );
  24934. this.camera = camera;
  24935. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24936. this.matrix = camera.matrixWorld;
  24937. this.matrixAutoUpdate = false;
  24938. this.pointMap = pointMap;
  24939. this.update();
  24940. }
  24941. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24942. CameraHelper.prototype.constructor = CameraHelper;
  24943. CameraHelper.prototype.update = function () {
  24944. var geometry, pointMap;
  24945. var vector = new Vector3();
  24946. var camera = new Camera();
  24947. function setPoint( point, x, y, z ) {
  24948. vector.set( x, y, z ).unproject( camera );
  24949. var points = pointMap[ point ];
  24950. if ( points !== undefined ) {
  24951. var position = geometry.getAttribute( 'position' );
  24952. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24953. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24954. }
  24955. }
  24956. }
  24957. return function update() {
  24958. geometry = this.geometry;
  24959. pointMap = this.pointMap;
  24960. var w = 1, h = 1;
  24961. // we need just camera projection matrix
  24962. // world matrix must be identity
  24963. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24964. // center / target
  24965. setPoint( "c", 0, 0, - 1 );
  24966. setPoint( "t", 0, 0, 1 );
  24967. // near
  24968. setPoint( "n1", - w, - h, - 1 );
  24969. setPoint( "n2", w, - h, - 1 );
  24970. setPoint( "n3", - w, h, - 1 );
  24971. setPoint( "n4", w, h, - 1 );
  24972. // far
  24973. setPoint( "f1", - w, - h, 1 );
  24974. setPoint( "f2", w, - h, 1 );
  24975. setPoint( "f3", - w, h, 1 );
  24976. setPoint( "f4", w, h, 1 );
  24977. // up
  24978. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24979. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24980. setPoint( "u3", 0, h * 2, - 1 );
  24981. // cross
  24982. setPoint( "cf1", - w, 0, 1 );
  24983. setPoint( "cf2", w, 0, 1 );
  24984. setPoint( "cf3", 0, - h, 1 );
  24985. setPoint( "cf4", 0, h, 1 );
  24986. setPoint( "cn1", - w, 0, - 1 );
  24987. setPoint( "cn2", w, 0, - 1 );
  24988. setPoint( "cn3", 0, - h, - 1 );
  24989. setPoint( "cn4", 0, h, - 1 );
  24990. geometry.getAttribute( 'position' ).needsUpdate = true;
  24991. };
  24992. }();
  24993. /**
  24994. * @author mrdoob / http://mrdoob.com/
  24995. * @author Mugen87 / http://github.com/Mugen87
  24996. */
  24997. function BoxHelper( object, color ) {
  24998. this.object = object;
  24999. if ( color === undefined ) color = 0xffff00;
  25000. 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 ] );
  25001. var positions = new Float32Array( 8 * 3 );
  25002. var geometry = new BufferGeometry();
  25003. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25004. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  25005. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25006. this.matrixAutoUpdate = false;
  25007. this.update();
  25008. }
  25009. BoxHelper.prototype = Object.create( LineSegments.prototype );
  25010. BoxHelper.prototype.constructor = BoxHelper;
  25011. BoxHelper.prototype.update = ( function () {
  25012. var box = new Box3();
  25013. return function update( object ) {
  25014. if ( object !== undefined ) {
  25015. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  25016. }
  25017. if ( this.object !== undefined ) {
  25018. box.setFromObject( this.object );
  25019. }
  25020. if ( box.isEmpty() ) return;
  25021. var min = box.min;
  25022. var max = box.max;
  25023. /*
  25024. 5____4
  25025. 1/___0/|
  25026. | 6__|_7
  25027. 2/___3/
  25028. 0: max.x, max.y, max.z
  25029. 1: min.x, max.y, max.z
  25030. 2: min.x, min.y, max.z
  25031. 3: max.x, min.y, max.z
  25032. 4: max.x, max.y, min.z
  25033. 5: min.x, max.y, min.z
  25034. 6: min.x, min.y, min.z
  25035. 7: max.x, min.y, min.z
  25036. */
  25037. var position = this.geometry.attributes.position;
  25038. var array = position.array;
  25039. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  25040. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  25041. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  25042. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  25043. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  25044. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  25045. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  25046. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  25047. position.needsUpdate = true;
  25048. this.geometry.computeBoundingSphere();
  25049. };
  25050. } )();
  25051. BoxHelper.prototype.setFromObject = function ( object ) {
  25052. this.object = object;
  25053. this.update();
  25054. return this;
  25055. };
  25056. /**
  25057. * @author WestLangley / http://github.com/WestLangley
  25058. */
  25059. function Box3Helper( box, hex ) {
  25060. this.type = 'Box3Helper';
  25061. this.box = box;
  25062. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25063. 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 ] );
  25064. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  25065. var geometry = new BufferGeometry();
  25066. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25067. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25068. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25069. this.geometry.computeBoundingSphere();
  25070. }
  25071. Box3Helper.prototype = Object.create( LineSegments.prototype );
  25072. Box3Helper.prototype.constructor = Box3Helper;
  25073. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  25074. var box = this.box;
  25075. if ( box.isEmpty() ) return;
  25076. box.getCenter( this.position );
  25077. box.getSize( this.scale );
  25078. this.scale.multiplyScalar( 0.5 );
  25079. Object3D.prototype.updateMatrixWorld.call( this, force );
  25080. };
  25081. /**
  25082. * @author WestLangley / http://github.com/WestLangley
  25083. */
  25084. function PlaneHelper( plane, size, hex ) {
  25085. this.type = 'PlaneHelper';
  25086. this.plane = plane;
  25087. this.size = ( size === undefined ) ? 1 : size;
  25088. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25089. var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  25090. var geometry = new BufferGeometry();
  25091. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25092. geometry.computeBoundingSphere();
  25093. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25094. //
  25095. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  25096. var geometry2 = new BufferGeometry();
  25097. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  25098. geometry2.computeBoundingSphere();
  25099. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  25100. }
  25101. PlaneHelper.prototype = Object.create( Line.prototype );
  25102. PlaneHelper.prototype.constructor = PlaneHelper;
  25103. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  25104. var scale = - this.plane.constant;
  25105. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  25106. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  25107. this.lookAt( this.plane.normal );
  25108. Object3D.prototype.updateMatrixWorld.call( this, force );
  25109. };
  25110. /**
  25111. * @author WestLangley / http://github.com/WestLangley
  25112. * @author zz85 / http://github.com/zz85
  25113. * @author bhouston / http://clara.io
  25114. *
  25115. * Creates an arrow for visualizing directions
  25116. *
  25117. * Parameters:
  25118. * dir - Vector3
  25119. * origin - Vector3
  25120. * length - Number
  25121. * color - color in hex value
  25122. * headLength - Number
  25123. * headWidth - Number
  25124. */
  25125. var lineGeometry;
  25126. var coneGeometry;
  25127. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  25128. // dir is assumed to be normalized
  25129. Object3D.call( this );
  25130. if ( color === undefined ) color = 0xffff00;
  25131. if ( length === undefined ) length = 1;
  25132. if ( headLength === undefined ) headLength = 0.2 * length;
  25133. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25134. if ( lineGeometry === undefined ) {
  25135. lineGeometry = new BufferGeometry();
  25136. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  25137. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  25138. coneGeometry.translate( 0, - 0.5, 0 );
  25139. }
  25140. this.position.copy( origin );
  25141. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  25142. this.line.matrixAutoUpdate = false;
  25143. this.add( this.line );
  25144. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  25145. this.cone.matrixAutoUpdate = false;
  25146. this.add( this.cone );
  25147. this.setDirection( dir );
  25148. this.setLength( length, headLength, headWidth );
  25149. }
  25150. ArrowHelper.prototype = Object.create( Object3D.prototype );
  25151. ArrowHelper.prototype.constructor = ArrowHelper;
  25152. ArrowHelper.prototype.setDirection = ( function () {
  25153. var axis = new Vector3();
  25154. var radians;
  25155. return function setDirection( dir ) {
  25156. // dir is assumed to be normalized
  25157. if ( dir.y > 0.99999 ) {
  25158. this.quaternion.set( 0, 0, 0, 1 );
  25159. } else if ( dir.y < - 0.99999 ) {
  25160. this.quaternion.set( 1, 0, 0, 0 );
  25161. } else {
  25162. axis.set( dir.z, 0, - dir.x ).normalize();
  25163. radians = Math.acos( dir.y );
  25164. this.quaternion.setFromAxisAngle( axis, radians );
  25165. }
  25166. };
  25167. }() );
  25168. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  25169. if ( headLength === undefined ) headLength = 0.2 * length;
  25170. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25171. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  25172. this.line.updateMatrix();
  25173. this.cone.scale.set( headWidth, headLength, headWidth );
  25174. this.cone.position.y = length;
  25175. this.cone.updateMatrix();
  25176. };
  25177. ArrowHelper.prototype.setColor = function ( color ) {
  25178. this.line.material.color.copy( color );
  25179. this.cone.material.color.copy( color );
  25180. };
  25181. /**
  25182. * @author sroucheray / http://sroucheray.org/
  25183. * @author mrdoob / http://mrdoob.com/
  25184. */
  25185. function AxisHelper( size ) {
  25186. size = size || 1;
  25187. var vertices = [
  25188. 0, 0, 0, size, 0, 0,
  25189. 0, 0, 0, 0, size, 0,
  25190. 0, 0, 0, 0, 0, size
  25191. ];
  25192. var colors = [
  25193. 1, 0, 0, 1, 0.6, 0,
  25194. 0, 1, 0, 0.6, 1, 0,
  25195. 0, 0, 1, 0, 0.6, 1
  25196. ];
  25197. var geometry = new BufferGeometry();
  25198. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25199. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25200. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  25201. LineSegments.call( this, geometry, material );
  25202. }
  25203. AxisHelper.prototype = Object.create( LineSegments.prototype );
  25204. AxisHelper.prototype.constructor = AxisHelper;
  25205. /**
  25206. * @author zz85 https://github.com/zz85
  25207. *
  25208. * Centripetal CatmullRom Curve - which is useful for avoiding
  25209. * cusps and self-intersections in non-uniform catmull rom curves.
  25210. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  25211. *
  25212. * curve.type accepts centripetal(default), chordal and catmullrom
  25213. * curve.tension is used for catmullrom which defaults to 0.5
  25214. */
  25215. /*
  25216. Based on an optimized c++ solution in
  25217. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  25218. - http://ideone.com/NoEbVM
  25219. This CubicPoly class could be used for reusing some variables and calculations,
  25220. but for three.js curve use, it could be possible inlined and flatten into a single function call
  25221. which can be placed in CurveUtils.
  25222. */
  25223. function CubicPoly() {
  25224. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  25225. /*
  25226. * Compute coefficients for a cubic polynomial
  25227. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  25228. * such that
  25229. * p(0) = x0, p(1) = x1
  25230. * and
  25231. * p'(0) = t0, p'(1) = t1.
  25232. */
  25233. function init( x0, x1, t0, t1 ) {
  25234. c0 = x0;
  25235. c1 = t0;
  25236. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  25237. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  25238. }
  25239. return {
  25240. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  25241. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  25242. },
  25243. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  25244. // compute tangents when parameterized in [t1,t2]
  25245. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  25246. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  25247. // rescale tangents for parametrization in [0,1]
  25248. t1 *= dt1;
  25249. t2 *= dt1;
  25250. init( x1, x2, t1, t2 );
  25251. },
  25252. calc: function ( t ) {
  25253. var t2 = t * t;
  25254. var t3 = t2 * t;
  25255. return c0 + c1 * t + c2 * t2 + c3 * t3;
  25256. }
  25257. };
  25258. }
  25259. //
  25260. var tmp = new Vector3();
  25261. var px = new CubicPoly();
  25262. var py = new CubicPoly();
  25263. var pz = new CubicPoly();
  25264. function CatmullRomCurve3( points ) {
  25265. Curve.call( this );
  25266. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  25267. this.points = points || [];
  25268. this.closed = false;
  25269. }
  25270. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  25271. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  25272. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  25273. var points = this.points;
  25274. var l = points.length;
  25275. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  25276. var intPoint = Math.floor( point );
  25277. var weight = point - intPoint;
  25278. if ( this.closed ) {
  25279. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  25280. } else if ( weight === 0 && intPoint === l - 1 ) {
  25281. intPoint = l - 2;
  25282. weight = 1;
  25283. }
  25284. var p0, p1, p2, p3; // 4 points
  25285. if ( this.closed || intPoint > 0 ) {
  25286. p0 = points[ ( intPoint - 1 ) % l ];
  25287. } else {
  25288. // extrapolate first point
  25289. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  25290. p0 = tmp;
  25291. }
  25292. p1 = points[ intPoint % l ];
  25293. p2 = points[ ( intPoint + 1 ) % l ];
  25294. if ( this.closed || intPoint + 2 < l ) {
  25295. p3 = points[ ( intPoint + 2 ) % l ];
  25296. } else {
  25297. // extrapolate last point
  25298. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  25299. p3 = tmp;
  25300. }
  25301. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  25302. // init Centripetal / Chordal Catmull-Rom
  25303. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  25304. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  25305. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  25306. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  25307. // safety check for repeated points
  25308. if ( dt1 < 1e-4 ) dt1 = 1.0;
  25309. if ( dt0 < 1e-4 ) dt0 = dt1;
  25310. if ( dt2 < 1e-4 ) dt2 = dt1;
  25311. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25312. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25313. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25314. } else if ( this.type === 'catmullrom' ) {
  25315. var tension = this.tension !== undefined ? this.tension : 0.5;
  25316. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25317. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25318. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25319. }
  25320. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25321. };
  25322. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25323. Curve.call( this );
  25324. this.v0 = v0;
  25325. this.v1 = v1;
  25326. this.v2 = v2;
  25327. this.v3 = v3;
  25328. }
  25329. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25330. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25331. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25332. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25333. return new Vector3(
  25334. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25335. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25336. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25337. );
  25338. };
  25339. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25340. Curve.call( this );
  25341. this.v0 = v0;
  25342. this.v1 = v1;
  25343. this.v2 = v2;
  25344. }
  25345. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25346. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25347. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25348. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25349. return new Vector3(
  25350. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25351. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25352. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25353. );
  25354. };
  25355. function LineCurve3( v1, v2 ) {
  25356. Curve.call( this );
  25357. this.v1 = v1;
  25358. this.v2 = v2;
  25359. }
  25360. LineCurve3.prototype = Object.create( Curve.prototype );
  25361. LineCurve3.prototype.constructor = LineCurve3;
  25362. LineCurve3.prototype.getPoint = function ( t ) {
  25363. if ( t === 1 ) {
  25364. return this.v2.clone();
  25365. }
  25366. var vector = new Vector3();
  25367. vector.subVectors( this.v2, this.v1 ); // diff
  25368. vector.multiplyScalar( t );
  25369. vector.add( this.v1 );
  25370. return vector;
  25371. };
  25372. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25373. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25374. }
  25375. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25376. ArcCurve.prototype.constructor = ArcCurve;
  25377. /**
  25378. * @author alteredq / http://alteredqualia.com/
  25379. */
  25380. var SceneUtils = {
  25381. createMultiMaterialObject: function ( geometry, materials ) {
  25382. var group = new Group();
  25383. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25384. group.add( new Mesh( geometry, materials[ i ] ) );
  25385. }
  25386. return group;
  25387. },
  25388. detach: function ( child, parent, scene ) {
  25389. child.applyMatrix( parent.matrixWorld );
  25390. parent.remove( child );
  25391. scene.add( child );
  25392. },
  25393. attach: function ( child, scene, parent ) {
  25394. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  25395. scene.remove( child );
  25396. parent.add( child );
  25397. }
  25398. };
  25399. /**
  25400. * @author mrdoob / http://mrdoob.com/
  25401. */
  25402. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25403. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25404. return new Face3( a, b, c, normal, color, materialIndex );
  25405. }
  25406. var LineStrip = 0;
  25407. var LinePieces = 1;
  25408. function MeshFaceMaterial( materials ) {
  25409. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25410. return materials;
  25411. }
  25412. function MultiMaterial( materials ) {
  25413. if ( materials === undefined ) materials = [];
  25414. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25415. materials.isMultiMaterial = true;
  25416. materials.materials = materials;
  25417. materials.clone = function () {
  25418. return materials.slice();
  25419. };
  25420. return materials;
  25421. }
  25422. function PointCloud( geometry, material ) {
  25423. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25424. return new Points( geometry, material );
  25425. }
  25426. function Particle( material ) {
  25427. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25428. return new Sprite( material );
  25429. }
  25430. function ParticleSystem( geometry, material ) {
  25431. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25432. return new Points( geometry, material );
  25433. }
  25434. function PointCloudMaterial( parameters ) {
  25435. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25436. return new PointsMaterial( parameters );
  25437. }
  25438. function ParticleBasicMaterial( parameters ) {
  25439. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25440. return new PointsMaterial( parameters );
  25441. }
  25442. function ParticleSystemMaterial( parameters ) {
  25443. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25444. return new PointsMaterial( parameters );
  25445. }
  25446. function Vertex( x, y, z ) {
  25447. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25448. return new Vector3( x, y, z );
  25449. }
  25450. //
  25451. function DynamicBufferAttribute( array, itemSize ) {
  25452. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25453. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25454. }
  25455. function Int8Attribute( array, itemSize ) {
  25456. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25457. return new Int8BufferAttribute( array, itemSize );
  25458. }
  25459. function Uint8Attribute( array, itemSize ) {
  25460. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25461. return new Uint8BufferAttribute( array, itemSize );
  25462. }
  25463. function Uint8ClampedAttribute( array, itemSize ) {
  25464. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25465. return new Uint8ClampedBufferAttribute( array, itemSize );
  25466. }
  25467. function Int16Attribute( array, itemSize ) {
  25468. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25469. return new Int16BufferAttribute( array, itemSize );
  25470. }
  25471. function Uint16Attribute( array, itemSize ) {
  25472. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25473. return new Uint16BufferAttribute( array, itemSize );
  25474. }
  25475. function Int32Attribute( array, itemSize ) {
  25476. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25477. return new Int32BufferAttribute( array, itemSize );
  25478. }
  25479. function Uint32Attribute( array, itemSize ) {
  25480. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25481. return new Uint32BufferAttribute( array, itemSize );
  25482. }
  25483. function Float32Attribute( array, itemSize ) {
  25484. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25485. return new Float32BufferAttribute( array, itemSize );
  25486. }
  25487. function Float64Attribute( array, itemSize ) {
  25488. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25489. return new Float64BufferAttribute( array, itemSize );
  25490. }
  25491. //
  25492. Curve.create = function ( construct, getPoint ) {
  25493. console.log( 'THREE.Curve.create() has been deprecated' );
  25494. construct.prototype = Object.create( Curve.prototype );
  25495. construct.prototype.constructor = construct;
  25496. construct.prototype.getPoint = getPoint;
  25497. return construct;
  25498. };
  25499. //
  25500. function ClosedSplineCurve3( points ) {
  25501. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25502. CatmullRomCurve3.call( this, points );
  25503. this.type = 'catmullrom';
  25504. this.closed = true;
  25505. }
  25506. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25507. //
  25508. function SplineCurve3( points ) {
  25509. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25510. CatmullRomCurve3.call( this, points );
  25511. this.type = 'catmullrom';
  25512. }
  25513. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25514. //
  25515. function Spline( points ) {
  25516. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25517. CatmullRomCurve3.call( this, points );
  25518. this.type = 'catmullrom';
  25519. }
  25520. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25521. Object.assign( Spline.prototype, {
  25522. initFromArray: function ( a ) {
  25523. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25524. },
  25525. getControlPointsArray: function ( optionalTarget ) {
  25526. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25527. },
  25528. reparametrizeByArcLength: function ( samplingCoef ) {
  25529. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25530. }
  25531. } );
  25532. //
  25533. function BoundingBoxHelper( object, color ) {
  25534. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25535. return new BoxHelper( object, color );
  25536. }
  25537. function EdgesHelper( object, hex ) {
  25538. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25539. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25540. }
  25541. GridHelper.prototype.setColors = function () {
  25542. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25543. };
  25544. SkeletonHelper.prototype.update = function () {
  25545. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  25546. };
  25547. function WireframeHelper( object, hex ) {
  25548. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25549. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25550. }
  25551. //
  25552. function XHRLoader( manager ) {
  25553. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25554. return new FileLoader( manager );
  25555. }
  25556. function BinaryTextureLoader( manager ) {
  25557. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25558. return new DataTextureLoader( manager );
  25559. }
  25560. //
  25561. Object.assign( Box2.prototype, {
  25562. center: function ( optionalTarget ) {
  25563. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25564. return this.getCenter( optionalTarget );
  25565. },
  25566. empty: function () {
  25567. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25568. return this.isEmpty();
  25569. },
  25570. isIntersectionBox: function ( box ) {
  25571. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25572. return this.intersectsBox( box );
  25573. },
  25574. size: function ( optionalTarget ) {
  25575. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25576. return this.getSize( optionalTarget );
  25577. }
  25578. } );
  25579. Object.assign( Box3.prototype, {
  25580. center: function ( optionalTarget ) {
  25581. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25582. return this.getCenter( optionalTarget );
  25583. },
  25584. empty: function () {
  25585. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25586. return this.isEmpty();
  25587. },
  25588. isIntersectionBox: function ( box ) {
  25589. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25590. return this.intersectsBox( box );
  25591. },
  25592. isIntersectionSphere: function ( sphere ) {
  25593. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25594. return this.intersectsSphere( sphere );
  25595. },
  25596. size: function ( optionalTarget ) {
  25597. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25598. return this.getSize( optionalTarget );
  25599. }
  25600. } );
  25601. Line3.prototype.center = function ( optionalTarget ) {
  25602. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25603. return this.getCenter( optionalTarget );
  25604. };
  25605. _Math.random16 = function () {
  25606. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25607. return Math.random();
  25608. };
  25609. Object.assign( Matrix3.prototype, {
  25610. flattenToArrayOffset: function ( array, offset ) {
  25611. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25612. return this.toArray( array, offset );
  25613. },
  25614. multiplyVector3: function ( vector ) {
  25615. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25616. return vector.applyMatrix3( this );
  25617. },
  25618. multiplyVector3Array: function ( a ) {
  25619. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  25620. },
  25621. applyToBuffer: function( buffer, offset, length ) {
  25622. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25623. return this.applyToBufferAttribute( buffer );
  25624. },
  25625. applyToVector3Array: function( array, offset, length ) {
  25626. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25627. }
  25628. } );
  25629. Object.assign( Matrix4.prototype, {
  25630. extractPosition: function ( m ) {
  25631. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25632. return this.copyPosition( m );
  25633. },
  25634. flattenToArrayOffset: function ( array, offset ) {
  25635. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25636. return this.toArray( array, offset );
  25637. },
  25638. getPosition: function () {
  25639. var v1;
  25640. return function getPosition() {
  25641. if ( v1 === undefined ) v1 = new Vector3();
  25642. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25643. return v1.setFromMatrixColumn( this, 3 );
  25644. };
  25645. }(),
  25646. setRotationFromQuaternion: function ( q ) {
  25647. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25648. return this.makeRotationFromQuaternion( q );
  25649. },
  25650. multiplyToArray: function () {
  25651. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25652. },
  25653. multiplyVector3: function ( vector ) {
  25654. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25655. return vector.applyMatrix4( this );
  25656. },
  25657. multiplyVector4: function ( vector ) {
  25658. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25659. return vector.applyMatrix4( this );
  25660. },
  25661. multiplyVector3Array: function ( a ) {
  25662. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  25663. },
  25664. rotateAxis: function ( v ) {
  25665. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25666. v.transformDirection( this );
  25667. },
  25668. crossVector: function ( vector ) {
  25669. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25670. return vector.applyMatrix4( this );
  25671. },
  25672. translate: function () {
  25673. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25674. },
  25675. rotateX: function () {
  25676. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25677. },
  25678. rotateY: function () {
  25679. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25680. },
  25681. rotateZ: function () {
  25682. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25683. },
  25684. rotateByAxis: function () {
  25685. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25686. },
  25687. applyToBuffer: function( buffer, offset, length ) {
  25688. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25689. return this.applyToBufferAttribute( buffer );
  25690. },
  25691. applyToVector3Array: function( array, offset, length ) {
  25692. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25693. },
  25694. makeFrustum: function( left, right, bottom, top, near, far ) {
  25695. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25696. return this.makePerspective( left, right, top, bottom, near, far );
  25697. }
  25698. } );
  25699. Plane.prototype.isIntersectionLine = function ( line ) {
  25700. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25701. return this.intersectsLine( line );
  25702. };
  25703. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25704. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25705. return vector.applyQuaternion( this );
  25706. };
  25707. Object.assign( Ray.prototype, {
  25708. isIntersectionBox: function ( box ) {
  25709. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25710. return this.intersectsBox( box );
  25711. },
  25712. isIntersectionPlane: function ( plane ) {
  25713. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25714. return this.intersectsPlane( plane );
  25715. },
  25716. isIntersectionSphere: function ( sphere ) {
  25717. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25718. return this.intersectsSphere( sphere );
  25719. }
  25720. } );
  25721. Object.assign( Shape.prototype, {
  25722. extrude: function ( options ) {
  25723. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25724. return new ExtrudeGeometry( this, options );
  25725. },
  25726. makeGeometry: function ( options ) {
  25727. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25728. return new ShapeGeometry( this, options );
  25729. }
  25730. } );
  25731. Object.assign( Vector2.prototype, {
  25732. fromAttribute: function ( attribute, index, offset ) {
  25733. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25734. return this.fromBufferAttribute( attribute, index, offset );
  25735. }
  25736. } );
  25737. Object.assign( Vector3.prototype, {
  25738. setEulerFromRotationMatrix: function () {
  25739. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25740. },
  25741. setEulerFromQuaternion: function () {
  25742. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25743. },
  25744. getPositionFromMatrix: function ( m ) {
  25745. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25746. return this.setFromMatrixPosition( m );
  25747. },
  25748. getScaleFromMatrix: function ( m ) {
  25749. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25750. return this.setFromMatrixScale( m );
  25751. },
  25752. getColumnFromMatrix: function ( index, matrix ) {
  25753. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25754. return this.setFromMatrixColumn( matrix, index );
  25755. },
  25756. applyProjection: function ( m ) {
  25757. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25758. return this.applyMatrix4( m );
  25759. },
  25760. fromAttribute: function ( attribute, index, offset ) {
  25761. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25762. return this.fromBufferAttribute( attribute, index, offset );
  25763. }
  25764. } );
  25765. Object.assign( Vector4.prototype, {
  25766. fromAttribute: function ( attribute, index, offset ) {
  25767. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25768. return this.fromBufferAttribute( attribute, index, offset );
  25769. }
  25770. } );
  25771. //
  25772. Geometry.prototype.computeTangents = function () {
  25773. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25774. };
  25775. Object.assign( Object3D.prototype, {
  25776. getChildByName: function ( name ) {
  25777. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25778. return this.getObjectByName( name );
  25779. },
  25780. renderDepth: function () {
  25781. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25782. },
  25783. translate: function ( distance, axis ) {
  25784. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25785. return this.translateOnAxis( axis, distance );
  25786. }
  25787. } );
  25788. Object.defineProperties( Object3D.prototype, {
  25789. eulerOrder: {
  25790. get: function () {
  25791. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25792. return this.rotation.order;
  25793. },
  25794. set: function ( value ) {
  25795. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25796. this.rotation.order = value;
  25797. }
  25798. },
  25799. useQuaternion: {
  25800. get: function () {
  25801. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25802. },
  25803. set: function () {
  25804. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25805. }
  25806. }
  25807. } );
  25808. Object.defineProperties( LOD.prototype, {
  25809. objects: {
  25810. get: function () {
  25811. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25812. return this.levels;
  25813. }
  25814. }
  25815. } );
  25816. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25817. get: function () {
  25818. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25819. },
  25820. set: function () {
  25821. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25822. }
  25823. } );
  25824. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25825. get: function () {
  25826. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25827. return this.arcLengthDivisions;
  25828. },
  25829. set: function ( value ) {
  25830. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25831. this.arcLengthDivisions = value;
  25832. }
  25833. } );
  25834. //
  25835. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25836. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25837. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25838. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25839. this.setFocalLength( focalLength );
  25840. };
  25841. //
  25842. Object.defineProperties( Light.prototype, {
  25843. onlyShadow: {
  25844. set: function () {
  25845. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25846. }
  25847. },
  25848. shadowCameraFov: {
  25849. set: function ( value ) {
  25850. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25851. this.shadow.camera.fov = value;
  25852. }
  25853. },
  25854. shadowCameraLeft: {
  25855. set: function ( value ) {
  25856. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25857. this.shadow.camera.left = value;
  25858. }
  25859. },
  25860. shadowCameraRight: {
  25861. set: function ( value ) {
  25862. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25863. this.shadow.camera.right = value;
  25864. }
  25865. },
  25866. shadowCameraTop: {
  25867. set: function ( value ) {
  25868. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25869. this.shadow.camera.top = value;
  25870. }
  25871. },
  25872. shadowCameraBottom: {
  25873. set: function ( value ) {
  25874. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25875. this.shadow.camera.bottom = value;
  25876. }
  25877. },
  25878. shadowCameraNear: {
  25879. set: function ( value ) {
  25880. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25881. this.shadow.camera.near = value;
  25882. }
  25883. },
  25884. shadowCameraFar: {
  25885. set: function ( value ) {
  25886. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25887. this.shadow.camera.far = value;
  25888. }
  25889. },
  25890. shadowCameraVisible: {
  25891. set: function () {
  25892. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25893. }
  25894. },
  25895. shadowBias: {
  25896. set: function ( value ) {
  25897. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25898. this.shadow.bias = value;
  25899. }
  25900. },
  25901. shadowDarkness: {
  25902. set: function () {
  25903. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25904. }
  25905. },
  25906. shadowMapWidth: {
  25907. set: function ( value ) {
  25908. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25909. this.shadow.mapSize.width = value;
  25910. }
  25911. },
  25912. shadowMapHeight: {
  25913. set: function ( value ) {
  25914. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25915. this.shadow.mapSize.height = value;
  25916. }
  25917. }
  25918. } );
  25919. //
  25920. Object.defineProperties( BufferAttribute.prototype, {
  25921. length: {
  25922. get: function () {
  25923. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25924. return this.array.length;
  25925. }
  25926. }
  25927. } );
  25928. Object.assign( BufferGeometry.prototype, {
  25929. addIndex: function ( index ) {
  25930. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25931. this.setIndex( index );
  25932. },
  25933. addDrawCall: function ( start, count, indexOffset ) {
  25934. if ( indexOffset !== undefined ) {
  25935. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25936. }
  25937. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25938. this.addGroup( start, count );
  25939. },
  25940. clearDrawCalls: function () {
  25941. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25942. this.clearGroups();
  25943. },
  25944. computeTangents: function () {
  25945. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25946. },
  25947. computeOffsets: function () {
  25948. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25949. }
  25950. } );
  25951. Object.defineProperties( BufferGeometry.prototype, {
  25952. drawcalls: {
  25953. get: function () {
  25954. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25955. return this.groups;
  25956. }
  25957. },
  25958. offsets: {
  25959. get: function () {
  25960. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25961. return this.groups;
  25962. }
  25963. }
  25964. } );
  25965. //
  25966. Object.defineProperties( Uniform.prototype, {
  25967. dynamic: {
  25968. set: function () {
  25969. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25970. }
  25971. },
  25972. onUpdate: {
  25973. value: function () {
  25974. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25975. return this;
  25976. }
  25977. }
  25978. } );
  25979. //
  25980. Object.defineProperties( Material.prototype, {
  25981. wrapAround: {
  25982. get: function () {
  25983. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25984. },
  25985. set: function () {
  25986. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25987. }
  25988. },
  25989. wrapRGB: {
  25990. get: function () {
  25991. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25992. return new Color();
  25993. }
  25994. },
  25995. shading: {
  25996. get: function () {
  25997. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  25998. },
  25999. set: function ( value ) {
  26000. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  26001. this.flatShading = ( value === FlatShading );
  26002. }
  26003. }
  26004. } );
  26005. Object.defineProperties( MeshPhongMaterial.prototype, {
  26006. metal: {
  26007. get: function () {
  26008. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  26009. return false;
  26010. },
  26011. set: function () {
  26012. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  26013. }
  26014. }
  26015. } );
  26016. Object.defineProperties( ShaderMaterial.prototype, {
  26017. derivatives: {
  26018. get: function () {
  26019. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26020. return this.extensions.derivatives;
  26021. },
  26022. set: function ( value ) {
  26023. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26024. this.extensions.derivatives = value;
  26025. }
  26026. }
  26027. } );
  26028. //
  26029. Object.assign( WebGLRenderer.prototype, {
  26030. getCurrentRenderTarget: function () {
  26031. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  26032. return this.getRenderTarget();
  26033. },
  26034. getMaxAnisotropy: function () {
  26035. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  26036. return this.capabilities.getMaxAnisotropy();
  26037. },
  26038. getPrecision: function () {
  26039. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  26040. return this.capabilities.precision;
  26041. },
  26042. resetGLState: function () {
  26043. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  26044. return this.state.reset();
  26045. },
  26046. supportsFloatTextures: function () {
  26047. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  26048. return this.extensions.get( 'OES_texture_float' );
  26049. },
  26050. supportsHalfFloatTextures: function () {
  26051. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  26052. return this.extensions.get( 'OES_texture_half_float' );
  26053. },
  26054. supportsStandardDerivatives: function () {
  26055. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  26056. return this.extensions.get( 'OES_standard_derivatives' );
  26057. },
  26058. supportsCompressedTextureS3TC: function () {
  26059. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  26060. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  26061. },
  26062. supportsCompressedTexturePVRTC: function () {
  26063. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  26064. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  26065. },
  26066. supportsBlendMinMax: function () {
  26067. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  26068. return this.extensions.get( 'EXT_blend_minmax' );
  26069. },
  26070. supportsVertexTextures: function () {
  26071. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  26072. return this.capabilities.vertexTextures;
  26073. },
  26074. supportsInstancedArrays: function () {
  26075. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  26076. return this.extensions.get( 'ANGLE_instanced_arrays' );
  26077. },
  26078. enableScissorTest: function ( boolean ) {
  26079. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  26080. this.setScissorTest( boolean );
  26081. },
  26082. initMaterial: function () {
  26083. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  26084. },
  26085. addPrePlugin: function () {
  26086. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  26087. },
  26088. addPostPlugin: function () {
  26089. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  26090. },
  26091. updateShadowMap: function () {
  26092. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  26093. }
  26094. } );
  26095. Object.defineProperties( WebGLRenderer.prototype, {
  26096. shadowMapEnabled: {
  26097. get: function () {
  26098. return this.shadowMap.enabled;
  26099. },
  26100. set: function ( value ) {
  26101. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  26102. this.shadowMap.enabled = value;
  26103. }
  26104. },
  26105. shadowMapType: {
  26106. get: function () {
  26107. return this.shadowMap.type;
  26108. },
  26109. set: function ( value ) {
  26110. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  26111. this.shadowMap.type = value;
  26112. }
  26113. },
  26114. shadowMapCullFace: {
  26115. get: function () {
  26116. return this.shadowMap.cullFace;
  26117. },
  26118. set: function ( value ) {
  26119. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  26120. this.shadowMap.cullFace = value;
  26121. }
  26122. }
  26123. } );
  26124. Object.defineProperties( WebGLShadowMap.prototype, {
  26125. cullFace: {
  26126. get: function () {
  26127. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  26128. },
  26129. set: function ( cullFace ) {
  26130. var value = ( cullFace !== CullFaceBack );
  26131. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  26132. this.renderReverseSided = value;
  26133. }
  26134. }
  26135. } );
  26136. //
  26137. Object.defineProperties( WebGLRenderTarget.prototype, {
  26138. wrapS: {
  26139. get: function () {
  26140. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26141. return this.texture.wrapS;
  26142. },
  26143. set: function ( value ) {
  26144. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26145. this.texture.wrapS = value;
  26146. }
  26147. },
  26148. wrapT: {
  26149. get: function () {
  26150. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26151. return this.texture.wrapT;
  26152. },
  26153. set: function ( value ) {
  26154. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26155. this.texture.wrapT = value;
  26156. }
  26157. },
  26158. magFilter: {
  26159. get: function () {
  26160. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26161. return this.texture.magFilter;
  26162. },
  26163. set: function ( value ) {
  26164. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26165. this.texture.magFilter = value;
  26166. }
  26167. },
  26168. minFilter: {
  26169. get: function () {
  26170. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26171. return this.texture.minFilter;
  26172. },
  26173. set: function ( value ) {
  26174. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26175. this.texture.minFilter = value;
  26176. }
  26177. },
  26178. anisotropy: {
  26179. get: function () {
  26180. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26181. return this.texture.anisotropy;
  26182. },
  26183. set: function ( value ) {
  26184. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26185. this.texture.anisotropy = value;
  26186. }
  26187. },
  26188. offset: {
  26189. get: function () {
  26190. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26191. return this.texture.offset;
  26192. },
  26193. set: function ( value ) {
  26194. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26195. this.texture.offset = value;
  26196. }
  26197. },
  26198. repeat: {
  26199. get: function () {
  26200. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26201. return this.texture.repeat;
  26202. },
  26203. set: function ( value ) {
  26204. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26205. this.texture.repeat = value;
  26206. }
  26207. },
  26208. format: {
  26209. get: function () {
  26210. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26211. return this.texture.format;
  26212. },
  26213. set: function ( value ) {
  26214. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26215. this.texture.format = value;
  26216. }
  26217. },
  26218. type: {
  26219. get: function () {
  26220. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26221. return this.texture.type;
  26222. },
  26223. set: function ( value ) {
  26224. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26225. this.texture.type = value;
  26226. }
  26227. },
  26228. generateMipmaps: {
  26229. get: function () {
  26230. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26231. return this.texture.generateMipmaps;
  26232. },
  26233. set: function ( value ) {
  26234. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26235. this.texture.generateMipmaps = value;
  26236. }
  26237. }
  26238. } );
  26239. //
  26240. Audio.prototype.load = function ( file ) {
  26241. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  26242. var scope = this;
  26243. var audioLoader = new AudioLoader();
  26244. audioLoader.load( file, function ( buffer ) {
  26245. scope.setBuffer( buffer );
  26246. } );
  26247. return this;
  26248. };
  26249. AudioAnalyser.prototype.getData = function () {
  26250. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  26251. return this.getFrequencyData();
  26252. };
  26253. //
  26254. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  26255. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  26256. return this.update( renderer, scene );
  26257. };
  26258. //
  26259. var GeometryUtils = {
  26260. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  26261. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  26262. var matrix;
  26263. if ( geometry2.isMesh ) {
  26264. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  26265. matrix = geometry2.matrix;
  26266. geometry2 = geometry2.geometry;
  26267. }
  26268. geometry1.merge( geometry2, matrix, materialIndexOffset );
  26269. },
  26270. center: function ( geometry ) {
  26271. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  26272. return geometry.center();
  26273. }
  26274. };
  26275. var ImageUtils = {
  26276. crossOrigin: undefined,
  26277. loadTexture: function ( url, mapping, onLoad, onError ) {
  26278. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  26279. var loader = new TextureLoader();
  26280. loader.setCrossOrigin( this.crossOrigin );
  26281. var texture = loader.load( url, onLoad, undefined, onError );
  26282. if ( mapping ) texture.mapping = mapping;
  26283. return texture;
  26284. },
  26285. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  26286. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  26287. var loader = new CubeTextureLoader();
  26288. loader.setCrossOrigin( this.crossOrigin );
  26289. var texture = loader.load( urls, onLoad, undefined, onError );
  26290. if ( mapping ) texture.mapping = mapping;
  26291. return texture;
  26292. },
  26293. loadCompressedTexture: function () {
  26294. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  26295. },
  26296. loadCompressedTextureCube: function () {
  26297. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  26298. }
  26299. };
  26300. //
  26301. function Projector() {
  26302. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  26303. this.projectVector = function ( vector, camera ) {
  26304. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  26305. vector.project( camera );
  26306. };
  26307. this.unprojectVector = function ( vector, camera ) {
  26308. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  26309. vector.unproject( camera );
  26310. };
  26311. this.pickingRay = function () {
  26312. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  26313. };
  26314. }
  26315. //
  26316. function CanvasRenderer() {
  26317. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  26318. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26319. this.clear = function () {};
  26320. this.render = function () {};
  26321. this.setClearColor = function () {};
  26322. this.setSize = function () {};
  26323. }
  26324. 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, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, Box3Helper, PlaneHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WebGLUtils, 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, MeshDistanceMaterial, 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 };